`

关于数据库动态转行问题

 
阅读更多

 数据库动态转行问题, 附上代码,

declare @sqlStr varchar(5000),@sqlCell varchar(5000) --临时变量
set @sqlStr=''
set @sqlCell=''

declare MyDdecl cursor scroll
for
select d from #TMP07 group by d --找出所有列

open MyDdecl   --打开游标

declare @d sysname

fetch next from MyDdecl into @d

while(@@fetch_status=0)--这里判断是不是到了最后。
begin
   
 set @sqlStr=@sqlStr+RTRIM(@d)+'=isnull(sum(case d when '''+RTRIM(@d)+''' then qty end),0)'
 set @sqlCell=@sqlCell+'sum(a.'+RTRIM(@d)+') '''+RTRIM(@d)+''''

 fetch next from MyDdecl into @d
 if @@fetch_status=0 begin
  set @sqlStr=@sqlStr+','
  set @sqlCell=@sqlCell+','
 end
end

close MyDdecl--关闭
deallocate MyDdecl --删除这个游标

print @sqlStr
print @sqlCell

declare @sql varchar(3000)
set @sql='select Wo_ptr,plant_ptr,'+@sqlCell+' from ('
set @sql=@sql+'select Wo_ptr,plant_ptr,'+@sqlStr+' from (select TOP (100) PERCENT * from #TMP07 order by SEQ_no ) #TMP07 group by WO_ptr ,plant_ptr '
set @sql=@sql+' ) a group by WO_ptr,plant_ptr'
print @sql
exec(@sql)

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics