Converting Rows To Comma Separated Values In SQL

let’s first create a table and load some data with the script given below

  1. CREATE TABLE Fruits  
  2. Name VARCHAR(50) )  
  3. GO   
  4. INSERT Fruits(NameVALUES ('Apple')  
  5. INSERT Fruits(NameVALUES ('Banana')   
  6. INSERT Fruits(NameVALUES ('Orange')   
Now we have values in rows and to convert them to a single comma separated value, you can use the script below, which uses the COALESCE inbuilt function.
  1. DECLARE @ConcatString VARCHAR(4000)  
  2. SELECT @ConcatString = COALESCE(@ConcatString + ', ''') + Name FROM Fruits   
  3. SELECT @ConcatString AS Fruits