Thursday, June 7, 2012

Comma separated column values

Few years back I have  blogged to show comma separated column values by using "COALSCE". Following is the new method to show same results and very useful than previous one.
Syntax:

SELECT field1,
 SUBSTRING( 
 (
  SELECT ( ', ' + field2)
  FROM #test t2 
  WHERE t1.Field1 = t2.Field1
  ORDER BY t1.Field1, t2.Field1
  FOR XML PATH('')
 ), 3, 1000)
FROM #test t1
GROUP BY field1