用什么游标,看看下面这段,也许有用:
rop proc getlist
go
create proc getlist @idlist varchar(100) as
/***************************
@idlist : 课程列表参数,
格式为:‘1,2,3’
***************************/
declare @strSQL1 varchar(5000), @strSQL2 varchar(5000), @colname varchar(50)
declare @i int,@j char
create table #temp(stu_id varchar(5))
set @strSQL1 = ''
set @strSQL2 = ''
set @i = 1
while @i<=len(@idlist)
begin
set @j = substring(@idlist,@i,1)
if @j <> ','
begin
set @strSQL1 = @strSQL1 + ' sum(case table1.id when ' + @j + ' then table2.s else 0 end) as f' + @j +', '
select @colname=test from table1 where id=@j
set @strSQL2 = @strSQL2 + @colname + ' decimal(5,2),'
end
set @i = @i + 1
end
set @strSQL1 = left(@strSQL1, len(@strSQL1)-1)
set @strSQL2 = 'alter table #temp add ' + @strSQL2 + '合计 decimal(7,2), 名次 int identity'
exec(@strSQL2)
set @strSQL1 = 'insert #temp select t1.* , t2.ff2 from
(select table2.stu_id,' + @strSQL1 + ' from table1,table2 where table1.id=table2.id group by table2.stu_id) as t1,
(select table2.stu_id, sum(table2.s) as ff2 from table2 group by table2.stu_id) as t2
where t1.stu_id=t2.stu_id order by t2.ff2 desc'
exec(@strSQL1)
select * from #temp order by stu_id