游标实例行转列

Posted 屎涂行者

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了游标实例行转列相关的知识,希望对你有一定的参考价值。

 
alter proc SP_Cut_CutBundNoList
as 
begin


declare @MoNO VARCHAR(100)
declare @CutLotNo int


select MONo,CutLotNo,GarPart,ColorName,
BundNo,SizeName,Qty into #cutd
 from tCutD  where MONo='1631040011' and CutLotNo in(6,7,8,9,10,11,12,13,26,27)
 
 --select * from #cutd
-- drop table #SizeOrder


select DIstinct ColorName  into #CutColor from #cutd
SELECT DISTINCT SizeName into #CutSize  FROM #cutd
select ROW_NUMBER() over(order by  SizeName ) as SizeID, SizeName into #SizeOrder from #CutSize




select ColorName,SizeName,SUM(Qty) AS 'Qty'
into #CutCOlorQty from #cutd
GROUP BY ColorName,SizeName






declare @SizeID Int 
declare @SizeName varchar(50)
declare @sql varchar(300)
declare @AdName varchar(100)


set @SizeName='';
set @SizeID=0;
set @sql='';
set @AdName='';


Declare  chimayoubiao  Cursor for select sizeName from  #SizeOrder order by sizeID for read only;
open chimayoubiao
fetch next from  chimayoubiao into @SizeName;

while @@FETCH_STATUS =0 
begin
set @AdName='size'+@sizeName;
set @sql='alter table #CutColor add '+@AdName+' varchar(50) default(0);';
  exec(@sql);
  print @sql;
  set @sql='update #CutColor set '+@AdName+'= q.Qty 
  from #CutColor C join #CutCOlorQty Q on c.ColorName=Q.ColorName
  and SUBSTRING(''c.'+@AdName+''',7,100)  =Q.SizeName';
  Exec(@sql);
 
  set @sql=' update #CutColor set '+ @AdName +'=0 where '+ @AdName +' is null';
  Exec(@sql);
  fetch next from chimayoubiao into @sizeName;
end;

-----SP_Cut_CutBundNoList

select * from #CutColor;
close chimayoubiao;
deallocate chimayoubiao

truncate table #CutCOlorQty;
truncate table #SizeOrder;
truncate table #CutSize;
truncate table #CutColor;
truncate table #cutD ;

drop  table #CutCOlorQty;
drop  table #SizeOrder;
drop  table #CutSize;
drop  table #CutColor;
drop  table #cutD ;
 

end;

结果如下:



原始数据如下:









以上是关于游标实例行转列的主要内容,如果未能解决你的问题,请参考以下文章

R语言数据框行转列实例

sqlserver日期行转列的问题

oracle 行转列,用特殊符号拼接

MySQL 行转列 -》动态行转列 -》动态行转列带计算

MySQL行转列与列转行

PIVOT:行转列函数