您的位置:首页 > 数据库

【Transact-SQL】通过递归来实现:将多条记录的某个字段的值,用斜杠拼接在一起

2011-11-19 10:14 501 查看
 需要把表@tt中的idd相同的记录中tchar字段的内容拼接在一起,结果如下

1,'abc/xyz/ggg'

2,'111/soft'

 

实验代码如下:

declare @tt table(idd int,tchar varchar(10))

insert into @tt
select 1,'abc' union all
select 1,'xyz' union all
select 1,'ggg' union all
select 2,'111' union all
select 2,'soft'

;with c
as
(
select idd,
tchar,
row_number() over(partition by idd order by tchar) as row
from @tt
),

cc --递归CTE
as
(
select idd,
cast(tchar as varchar(1000)) as ch,
row
from c
where row = 1

union all

select cc.idd,
ch=cast(cc.ch+'/'+c.tchar as varchar(1000)),
c.row
from cc
inner join c
on c.idd = cc.idd
and c.row = cc.row+1
),
ccc
as
(
select idd,ch,row,
row_number() over(partition by idd order by row desc) as rownum
from cc
)

select * from ccc
where rownum=1
/*
idd ch row rownum
1 abc/ggg/xyz 3 1
2 111/soft 2 1
*/
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐