tags:

views:

841

answers:

4

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'

Thanks, Murali

+1  A: 

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 = 
    coalesce (case when @aa = ''
                   then CarName
                   else @aa + ',' + CarName
               end
              ,'')
  from Cars

print @aa
ConcernedOfTunbridgeWells
+3  A: 
DECLARE @CarList nvarchar(max);
SET @CarList = N'';
SELECT @CarList+=CarName+N','
FROM dbo.CARS;
SELECT LEFT(@CarList,LEN(@CarList)-1);

Thanks are due to whoever on SO showed me the use of accumulating data during a query.

John Saunders
+5  A: 
SELECT LEFT(Car, LEN(Car) - 1)
FROM (
    SELECT Car + ', '
    FROM Cars
    FOR XML PATH ('')
  ) c (Car)
Lieven
Thanks. I had never seen this syntax for naming the columns of a subquery. I wonder if you can edit your answer to include that part of the TSQL syntax that permits this?
John Saunders
It's a construction I picked up right here at Stackoverflow. I don't know where or even if it is mentioned in any TSQL specification.
Lieven
A: 

DECLARE @SQL AS VARCHAR(500)

SELECT @SQL ISNULL(@SQL ' ')+' ' + ColumnName FROM TableName

SELECT @SQL