Posts Tagged ‘Comma separated values’

SQL Query : Comma separated values

September 17, 2009 Leave a comment

Level: Intermediate

This might be a very simple task for experienced programmers, but I want to point it out here in case if any one wonders how to do this.

Have you ever written a query that returns comma separated values from a column? Before I wrote this query I was thinking it must very hard to achieve this. But in truth it is not. Here is the table that has 3 columns namely Id, Name, and Dept.

I need to write a query that gives all the values in the name column separated by comma.Here is how to do it!

Id Name Dept
1 name1 dept1
2 name2 dept1
3 name3 dept1
4 name4 dept4
5 name5 dept4

declare @mname varchar(1000)

set @mname=”

select @mname= @mname + ltrim(rtrim(name)) + ‘,’ from table2

print @mname

Output: name1,name2,name3,name4,name5,

Happy Querying!