Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Join query result to a single line of values separated by comma [duplicate]

Possible Duplicate:
SQL Server: Can I Comma Delimit Multiple Rows Into One Column?

I have a query like this:

SELECT name from users

and it's result is a number of records:

1 user1
2 user2
3 user3

I want to get all this records in a single line separated by comma:

user1, user2, user3

and an empty line if query result is empty.

How to get this using T-SQL? UNPIVOT?

like image 604
abatishchev Avatar asked Mar 02 '10 22:03

abatishchev


People also ask

How can we get result in comma separated values from SQL query?

In order to fetch the comma separated (delimited) values from the Stored Procedure, you need to make use of a variable with data type and size same as the Output parameter and pass it as Output parameter using OUTPUT keyword.


2 Answers

You can use the COALESCE function to achieve this:

declare @result varchar(max)

select @result = COALESCE(@result + ', ', '') + name
from users

select @result

This will work in sql server 2000 and later (probably earlier versions too). Note that you don't have varchar(max) in sql server 2000 though.

In later versions of sql server (2005 and later), it is also possible to do this using XML Path()

select name + ','
from users
for xml path('')
like image 102
David Hall Avatar answered Sep 22 '22 06:09

David Hall


You can do it like this too except its not formatted all that nicely when displayed to the DOS shell:

echo Batch file SQL 2005
echo. 
"%PROGRAMFILES%\Microsoft SQL Server\90\Tools\BINN\osql" -S . -E -Q "SELECT name + ', ' FROM sysdatabases order by name for XML PATH('')"
like image 45
djangofan Avatar answered Sep 22 '22 06:09

djangofan