Email: Password:       Forgot Password 
    .netCodeSG
A Saarsha Group Online Community for dot net codes group like C#, Asp.NET, VB.NET, Sharepoint, JavaScript, JQuery, Ajax, SQL, WCF, WPF.
 
TECHNOLOGIES:
 

Return Comma Separated Value from a Table In Select Query

Article:
Viewed:  860 
Posted On:  28/03/2015 06:03:20 
How we can return a column value as comma separated in SQL Server ? 

 

Suppose I have a table like below:

1.png

Image 1.

And you need to return all name as a comma separated string, Like below

Rahul Saxena,Sara Sinha,Priyanka Mathur,Shambhu Sharma,Manu Khanna,Ganga,Shweta,Shraddha,Akhilesh,
Mayank,Rakesh,Abhishek,Saurabh

Use below Command:

SELECT SUBSTRING((
SELECT ',' + CAST(Name AS VARCHAR) FROM Employee
FOR XML PATH('')), 2,10000) AS NAME

 

2.png

 

Image 2.

 

If you want to put a condition then

 

     

SELECT SUBSTRING((
SELECT ',' + CAST(Name AS VARCHAR) FROM Employee WHERE Country='India'
FOR XML PATH('')), 2,10000) AS NAME

 

3.png

 

Image 3.

 

I you want to show your result group by any column then use below Query:

 

SELECT DISTINCT Country,
      STUFF(
      (
            SELECT ',' + CAST(Name AS VARCHAR)
            FROM Employee AS t2
            WHERE t2.Country = t.Country
            FOR XML PATH('')
      ), 1, 1, '') AS id_list
FROM Employee AS t

 

4.png

 

Image 4.

  Comment:
         HOME   |   Submit Article   |   Contact Us   |   About Us   |   Terms & Condition   |   Advertise With us