/*
纵向表内容
f_billno,f_invname
0001 商品1
0002 商品A
0001 商品2
0001 商品3
0002 商品B
0003 商品I
0003 商品II
目标效果
fid,ftext
0001 商品1商品2商品3
0002 商品A商品B
0003 商品I商品II

以下是SQL语句,用到了临时表和游标的使用。
*/
--查看源数据
select f_billno,f_invname from test

--定义两个临时变量用来保存游标取得的数据
DECLARE @c varchar(255)
DECLARE @c1 varchar(255)
--删除临时表
if object_id('tempdb..#tmp') is not null drop table #tmp
--建立临时表及生成数据
Create Table #tmp(fid varchar(4),ftext varchar(255))
insert into #tmp
select f_billno,'' from test group by f_billno
--取游标数据
declare cur_test CURSOR FOR
select f_billno,f_invname from test
open cur_test
fetch next from cur_test into @c,@c1
--第一个循环
while @@fetch_status=0
begin
--重复取数据并生成相应的处理SQL
exec('update #tmp set ftext=ftext+'''+@c1+' '' where fid='''+@c+'''');
fetch next from cur_test into @c,@c1
end
--显示结果数据
select * from #tmp
--关闭游标
close cur_test
deallocate cur_test

 

posted on 2010-11-19 16:18  星五  阅读(441)  评论(0编辑  收藏  举报