Tuesday, 15 October 2013

SQL Server - How convert SQL rows to Comma Separated String (CSV)

declare @T table (GroupID int, Value varchar(10))

insert into @T values (1, 'Row 1')
insert into @T values (1, 'Row 2')
insert into @T values (2, 'Row 3')
insert into @T values (2, 'Row 4')
insert into @T values (2, 'Row 5')

select GroupID,
  stuff(
  (select ','+Value as '*'
   from @T as T2
   where T2.GroupID = T1.GroupID
   for xml path('')), 1, 1, '') as [Values]
from @T as T1
group by GroupID

go