-2

Can we have the column values displayed rowwise separated by commas. For example, the below returns a column. Can we make the expected output happen

select [name] as database_name
from sys.databases

Actual output

database_name
db1
db2
db3

Expected output

database_name
db1, db2, db3
  • Which SQL Server version? – jarlh Jul 31 '20 at 07:18
  • 2012........... – Vinay prakash Jul 31 '20 at 07:26
  • Please check this: https://stackoverflow.com/questions/6899/how-to-create-a-sql-server-function-to-join-multiple-rows-from-a-subquery-into – Mitz Jul 31 '20 at 07:27
  • Does this answer your question? [How to concatenate text from multiple rows into a single text string in SQL server?](https://stackoverflow.com/questions/194852/how-to-concatenate-text-from-multiple-rows-into-a-single-text-string-in-sql-serv) – Nissus Jul 31 '20 at 07:53

1 Answers1

1

Yes, you can use FOR XML PATH to concatenate column values:

SELECT name = STUFF((
            SELECT ',' + NAME
            FROM sys.databases
            FOR XML PATH('')
            ), 1, 1, '')
Luke
  • 127
  • 1
  • 6