ceate sp..
(@month int)
as
begin
declare @m1 varchar(10)
declare @mn varchar(10)
declare @sql varchar(500)
declare @i int
set @m1=' isnull(m1,0)'
set @mn =' '
set @i=2
while @i<=@month
begin
--build columns
Set @mn =@mn + ' + isnull(m' + convert(@i,varchar(2)) + ',0) ,'
end
Set @sql = ' select sum ( ' + @m1+ sunstring (@mn , len(@mn)-1) + ' ) from .......where ....'
---------------------------------------------------remove the latest ','
exec @sql'
end
没装sql,可能有不少错误,不过大概就这个意思吧.用sp做,比建query方便得多.
(@month int)
as
begin
declare @m1 varchar(10)
declare @mn varchar(10)
declare @sql varchar(500)
declare @i int
set @m1=' isnull(m1,0)'
set @mn =' '
set @i=2
while @i<=@month
begin
--build columns
Set @mn =@mn + ' + isnull(m' + convert(@i,varchar(2)) + ',0) ,'
end
Set @sql = ' select sum ( ' + @m1+ sunstring (@mn , len(@mn)-1) + ' ) from .......where ....'
---------------------------------------------------remove the latest ','
exec @sql'
end
没装sql,可能有不少错误,不过大概就这个意思吧.用sp做,比建query方便得多.