Home > Database, SQL Server2008 > SQL Query : Comma separated values

SQL Query : Comma separated values

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!

  1. No comments yet.
  1. No trackbacks yet.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s

%d bloggers like this: