tags:

views:

434

answers:

4

In a SQL statement ( or procedure ) I want to collapse the rows of this table into a single comma delimited string.

simpleTable

id  value
--  ----- 
1    "a"
2    "b"
3    "c"

Collapse to:

"a, b, c"
+4  A: 

You can concatenate using an embedded 'set' statement in a query:

declare @combined varchar(2000)
select @combined = isnull(@combined + ', ','') + isnull(value,'')
from simpleTable

print @combined

(Note that the first isnull() initialises the string, and the second isnull() is especially important if there's any chance of nulls in the 'value' column, because otherwise a single null could wipe out the whole concatenation)

(edited code and explanation after comments)

codeulike
sweet! I didn't realize you could do that. I always thought set and select worked the same for assignment.
Booji Boy
you might want to make it "+ ISNULL(value,'')" because "+ value" will null out any portion of the string build up before the row with the null value
KM
you're right! don't know how I missed that ... have edited.
codeulike
+2  A: 
DECLARE @EmployeeList varchar(100)

SELECT @EmployeeList = COALESCE(@EmployeeList + ', ', '') + 
   CAST(Emp_UniqueID AS varchar(5))
FROM SalesCallsEmployees
WHERE SalCal_UniqueID = 1

SELECT @EmployeeList

Results:

1, 2, 4
hypoxide
+2  A: 

This will only work in MSSQL 2005+

select value + ',' from simpletable for xml path ('')

..one way to prevent the extra comma:

select case(row_number() over (order by id))
when 1 then value else ',' + value end
from simpletable
for xml path ('')
Gordy
Only works in SQLServer 2005+, but yeah its a fun hack.
FlySwat
if only there was a slick way to remove that last comma :)
dotjoe
added a slick way to remove that last comma :)
Gordy
nice! I always forget about the row_number()
dotjoe
A: 

This is based on @codeulike answer, but will prevent losing the portion of the string that gets concatenated before a null "value" is concatenated on.

declare @combined varchar(2000)
select @combined = isnull(@combined + ', ','') + ISNULL(value,'')
from simpleTable

print @combined
KM