Return Comma Separated Value From a Table

We will create a table variable and populate it with some data. We will retrieve the studentname column values asa  comma separated string. Let us see how to do this.

Write the following script in SQL SERVER:

  1. DECLARE @Student TABLE  
  2. (  
  3. StudentIdintNOTNULL,  
  4. StudentNamevarchar(20),  
  5. Marks int  
  6. )  
  7.   
  8.   
  9. InsertInto @Student(StudentID,StudentName,Marks)Values (1,'Nitin Tyagi',200)  
  10. InsertInto @Student(StudentID,StudentName,Marks)Values (2,'Amar Singh',400)  
  11. InsertInto @Student(StudentID,StudentName,Marks)Values (3,'Vicky',300)  
  12.   
  13. SELECTSUBSTRING((  
  14. SELECT','+CAST(StudentNameASVARCHAR)FROM @Student   
  15. FORXMLPATH('')), 2,10000)ASStudentName 
Let us execute the query and check the output.

output

As we can see we get the StudentName column value asa comma separated string.