On a SQL Server 2008 I'm trying to get a comma separated list of all selected values into a variable.
SELECT field
FROM table
returns:
+-------+
| field |
+-------+
| foo |
+-------+
| bar |
+-------+
I'd like to get: "foo, bar, "
I tried:
DECLARE @foo NVARCHAR(MAX)
SET @foo = ''
SELECT @foo = @foo + field + ','
FROM TABLE
PRINT @foo
Which returns nothing. What am I doing wrong?
You'll need to change NULLs
SELECT @foo = @foo + ISNULL(field + ',', '')
FROM TABLE
or remove them
SELECT @foo = @foo + field + ','
FROM TABLE
WHERE field IS NOT NULL
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