34,590
社区成员
发帖
与我相关
我的任务
分享
if OBJECT_ID('test')is not null
drop table test
go
create table test(id int,clid int,[desc] varchar(20))
insert into test
select 1, 2, '西瓜' union all
select 2, 3, '萝卜' union all
select 3, 3, '芹菜' union all
select 4, 2, '苹果' union all
select 5, 1, '豆腐' union all
select 6, 2, '葡萄'
declare @val varchar(max)
select @val=ISNULL(@val+',','')+[desc] from test where clid=2
select @val
select b.[cid],left(StuList,len(StuList)-1)as tb from (
SELECT [cid],
(SELECT [desc]+',' FROM tb
WHERE [cid]=a.[cid]
FOR XML PATH('')) AS StuList
FROM tb A
GROUP BY cid
) B
select cid,stuff((select ','+[desc] from table where a.cid=cid for xml path('')),1,1,'')
from table as a where cid=2
group by cid
适用sql2005及以上版本