Based on some googling I came up with this:
drop table #temp
create table #temp
(
id int,
name nvarchar(max)
)
insert into #temp (id,name) values (1,'bla1')
insert into #temp (id,name) values (1,'bla2')
insert into #temp (id,name) values (3,'bla3')
;with cte1 as
(
select id, stuff((select ', ' + CAST(t2.name as nvarchar(max))
from #temp t2 where t1.id = t2.id
for xml path('')),1,1,'') name
from #temp t1
)
select id, name from cte1 group by id, name
Is this the best way to do things? Thanks!
Christian
This approach is slightly better as it just sorts on
idrather thanid,nameIf you have a table containing just the distinct
idfields already you would probably be better off using that.The approach you are using only works correctly if the data is guaranteed not to contain any characters such as
<,>,&