let’s first create a table and load some data with the script given below
- CREATE TABLE Fruits
- ( Name VARCHAR(50) )
- GO
- INSERT Fruits(Name) VALUES ('Apple')
- INSERT Fruits(Name) VALUES ('Banana')
- INSERT Fruits(Name) VALUES ('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.
- DECLARE @ConcatString VARCHAR(4000)
- SELECT @ConcatString = COALESCE(@ConcatString + ', ', '') + Name FROM Fruits
- SELECT @ConcatString AS Fruits