Return Coma Separated Value From a Table

Suppose I have a table as in the following:



And you need to return all the names as a comma separated string, as in the following:

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

Use the following command:

  1. SELECT SUBSTRING((  
  2. SELECT ',' + CAST(Name AS VARCHARFROM Employee   
  3. FOR XML PATH('')), 2,10000) AS NAME


If you want to provide a condition then:
  1. SELECT SUBSTRING((  
  2. SELECT ',' + CAST(Name AS VARCHARFROM Employee WHERE Country='India'  
  3. FOR XML PATH('')), 2,10000) AS NAME  


I you want to show your result group by a column then use the following query:
  1. SELECT DISTINCT Country,  
  2. STUFF(  
  3. (  
  4. SELECT ',' + CAST(Name AS VARCHAR)  
  5. FROM Employee AS t2  
  6. WHERE t2.Country = t.Country  
  7. FOR XML PATH('')  
  8. ), 1, 1, ''AS id_list  
  9. FROM Employee AS t  

Up Next
    Ebook Download
    View all
    Learn
    View all