views:

236

answers:

3

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?

A: 
declare @result varchar(max)
set @result = ''
select @result = @result + name + ',' from users 
if @result <> '' set @result = left(@result,len(@result)-1)
print @result
DyingCactus
@DyingCactus: How to call this in cycle of recursively so resulting string like 'user1, user2, user3, ... userN' could come out
abatishchev
Do you mean how to get the string without comma at end in one statement? David Hall's answer will do that.
DyingCactus
+2  A: 

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('')
David Hall
@David Hall: I like the first one. Second unfortunately adds a comma to the end of each record, for the last one too.
abatishchev
@abatishchev glad you found this helpful. Do have a look at this post http://msmvps.com/blogs/robfarley/archive/2007/04/08/coalesce-is-not-the-answer-to-string-concatentation-in-t-sql.aspx you may find that for large result sets the xml path method is better.
David Hall
+1  A: 

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('')"
djangofan