利用游标合并字符

create table tb (col1 nvarchar(50),col2 nvarchar(10))

insert tb select 'a','1'
union all select 'a','2'
union all select 'a','3'
union all select 'b','1'
union all select 'c','2'
union all select 'c','1'
union all select 'b','2'

select * from tb

-----declare cursor and merge data
declare @t table(col1 nvarchar(50),col2 nvarchar(100))
declare tb cursor local  for select col1,col2 from tb order by col1,col2

--declare @col1_old
declare @col1_old nvarchar(50),@col1 nvarchar(10), @col2 nvarchar(10),@s nvarchar(100)
--open cursor
open tb
fetch tb into @col1,@col2
select @col1_old = @col1,@s=''
while @@fetch_status =0
begin
      if @col1 = @col1_old  --当前的列与上次读取的列进行比较
         select @s=@s+','+cast(@col2 as nvarchar(10))
      else
         begin
         insert @t values(@col1_old,stuff(@s,1,1,''))
         select @s=','+cast(@col2 as varchar),@col1_old=@col1
         end
fetch tb into @col1,@col2
end 
insert @t values(@col1_old,stuff(@s,1,1,''))
close tb
deallocate tb

select *from @t 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值