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
8条答案
按热度按时间jucafojl1#
For SQL Server 2017 and newer versions see the answer by gpanagakis: https://stackoverflow.com/a/41851771/218408
For SQL Server 2016 and older versions:
jw5wzhpr2#
You can do a shortcut using
coalesce
to concatenate a series of strings from a record in a table, for example.7y4bm7vi3#
If you are running on SQL Server 2017 or Azure SQL Database you do something like this :
0s7z1bwu4#
You can do this using stuff:
lx0bsm1f5#
Thanks are due to whoever on SO showed me the use of accumulating data during a query.
rta7y2nd6#
Another solution within a query :
(EDIT: thanks @user007 for the STUFF declaration)
gab6jxml7#
Please try this with the following code:
nwwlzxa78#