id code name
1 1 a
2 1 b
3 1 c
4 2 d
5 2 e
6 1 f条件是code = 1我要查询的结果是
name
--------------------------------------------
a,b,c,f
1 1 a
2 1 b
3 1 c
4 2 d
5 2 e
6 1 f条件是code = 1我要查询的结果是
name
--------------------------------------------
a,b,c,f
调试欢乐多
set @vstr=''
select @vstr=@vstr+name+',' from 表名 where code= 1print @vstr
insert into @tb select 1,1,'a'
insert into @tb select 2,1,'b'
insert into @tb select 3,1,'c'
insert into @tb select 4,2,'d'
insert into @tb select 5,2,'e'
insert into @tb select 6,1,'f'select name=stuff((select N','+name from @tb where code=1 For XML PATH(''), ROOT('R'), TYPE).value('/R[1]','nvarchar(max)'),1,1,'')a,b,c,f
insert into @tb select 1,1,'a'
insert into @tb select 2,1,'b'
insert into @tb select 3,1,'c'
insert into @tb select 4,2,'d'
insert into @tb select 5,2,'e'
insert into @tb select 6,1,'f'select
a.code,b.name
from
(select distinct code from @tb) a
cross apply
(select name=(stuff((select N','+name from @tb where code=a.code For XML PATH(''), ROOT('R'), TYPE).value('/R[1]','nvarchar(max)'),1,1,'')))b
code name
1 a,b,c,f
2 d,e