比较笨的办法如下(已测试通过),创建存储过程实现。
create procedure sp_cross
as
declare @FieldCount int,
@id int ,
@Money int,
@CurId int,
@RecNo int,
@i int,
@StrSql varchar(1000),
@Str_Sp varchar(10)
--获得同一id的最大记录数
select @FieldCount=max(cc) from
(select id,count(*) as cc from list group by id) as TmpCount
--根据最大记录数创建临时表,表名为:‘Tmp’+进程号
set @Str_Sp=Convert(varchar(10),@@spId)
if exists (select * from dbo.sysobjects where id = object_id(N'[Tmp_Tab'+Convert(varchar(10),@@spId)+']') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
exec ('drop table [Tmp_Tab'+@Str_Sp+']')
exec('create Table Tmp_Tab'+@Str_Sp+'(id int)')
set @i=0
while @i<@FieldCount
begin
set @StrSql='alter Table Tmp_Tab'+@Str_Sp+' add Money'+Convert(varchar(5),@i+1)+' numeric(7,2) default 0'
print @StrSql
exec(@StrSql)
set @i=@i+1
end
--向临时表插入数据
exec('insert Tmp_Tab'+@Str_Sp+'(id) select Distinct id from list')
set @CurId=0
set @RecNo=0
declare AddTag cursor for
select id,Money from List
for read only
open AddTag
fetch AddTag into @id,@Money
while (@@fetch_status<>-1)
begin
if @CurId=@Id
set @RecNo=@RecNo+1
else
begin
set @CurId=@Id
set @RecNo=1
end
set @StrSql='update Tmp_Tab'+@Str_Sp+' set Money'+convert(varchar(5),@RecNo)+'='+convert(varchar(10),abs(@Money))+ ' where id='+Convert(varchar(5),@id)
print @StrSql
exec(@StrSql)
fetch next from AddTag into @id,@Money
end
close AddTag
deallocate AddTag
--获得结果记录集
exec ('select * from Tmp_Tab'+@Str_Sp)
--清除临时表
if exists (select * from dbo.sysobjects where id = object_id(N'[Tmp_Tab'+@Str_Sp+']') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
exec ('drop table [Tmp_Tab'+@Str_Sp+']')
GO