Concatenating Column Values into a Comma-Separated List

sql-server, t-sql

Solution

You can do a shortcut using `coalesce` to concatenate a series of strings from a record in a table, for example.

declare @aa varchar (200)
set @aa = ''

select @aa = 
    case when @aa = ''
    then CarName
    else @aa + coalesce(',' + CarName, '')
    end
  from Cars

print @aa

Problem

What is the TSQL syntax to format my output so that the column values appear as a string, seperated by commas. Example, my table CARS has the following: ``` CarID CarName ---------------- 1 Porsche 2 Mercedes 3 Ferrari ``` How do I get the car names as : `Porsche, Mercedes, Ferrari`

Original source

Related problems