How to get rows into comma separated values column in sql


How to get rows into comma separated values column in sql. Fetching rows values into comma separated column value is required lots of time in our projects. So I tried to achieve this and lastly found one solution. Use this to get all row values into one single column value with comma separation.

Fetching rows values into comma separated column value is required lots of time in our projects. So I tried to achieve this and lastly found one solution.

For Example :



We have the following data in a Table called TABLE1.

TABLE1 - Table name

Name - column name

India

USA

Japan

China

I want to fetch data like below :

India, USA, Japan, China

To achieve this, lets start with below example:

Create a table named TABLE1 with one field named Name and set varchar as datatype.

Code :

Create TABLE TABLE1 ([Name] Varchar(30) )


Now insert 4 country into the newly created table.

Code :

INSERT INTO TABLE1 VALUES ('India')

INSERT INTO TABLE1 VALUES ('USA')

INSERT INTO TABLE1 VALUES ('Japan')

INSERT INTO TABLE1 VALUES ('China')


We will first create xml and then with the help of stuff We will create comma separated value:


SELECT STUFF(( SELECT ', ' + [Name] FROM (SELECT [Name] FROM TABLE1) AS T FOR XML PATH('') ) ,1,1,'') AS [Name]

and output will be :

Name
------------------------------------

India, USA, Japan, China

Thank You.

Reference: http://dotnetsquare.com/resources/4-How-to-convert-rows-into-comma-separated-values-column


Article by Manoranjan Sahoo
If it helps you then Rate this. Best Regards, Manoranjan Sahoo http://www.dotnetsquare.com Blog: http://blog.msahoo.net

Follow Manoranjan Sahoo or read 63 articles authored by Manoranjan Sahoo

Comments

No responses found. Be the first to comment...


  • Do not include your name, "with regards" etc in the comment. Write detailed comment, relevant to the topic.
  • No HTML formatting and links to other web sites are allowed.
  • This is a strictly moderated site. Absolutely no spam allowed.
  • Name:
    Email: