Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Concatenating Column Values into a Comma-Separated List

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

like image 234
Murali B Avatar asked Jun 26 '09 09:06

Murali B


People also ask

How do you turn a column of data into a comma separated list?

Type the formula =CONCATENATE(TRANSPOSE(A1:A7)&",") in a blank cell adjacent to the list's initial data, for example, cell C1. (The column A1:A7 will be converted to a comma-serrated list, and the separator "," will be used to separate the list.)

How do I concatenate comma separated values in SQL?

You can concatenate rows into single string using COALESCE method. This COALESCE method can be used in SQL Server version 2008 and higher. All you have to do is, declare a varchar variable and inside the coalesce, concat the variable with comma and the column, then assign the COALESCE to the variable.


1 Answers

SELECT LEFT(Car, LEN(Car) - 1) FROM (     SELECT Car + ', '     FROM Cars     FOR XML PATH ('')   ) c (Car) 
like image 64
Lieven Keersmaekers Avatar answered Oct 04 '22 19:10

Lieven Keersmaekers