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
?
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.
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('')
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('')"
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With