Tuesday, March 22, 2016

comma separated values in a single cell (T-SQL)

Hi,

I reviewed my solution back from 2015-05-27 ( http://itados.blogspot.co.at/2015/05/sql-recursive-functions-linked-lists-in.html ). I thought it would be easy to explain a colleague how to put multiple values into a cell based on this article, but it took me over 5 minutes of staring at the code to remember how this all works...

Here an easier example:


 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
declare @x as table (id int, val int)

insert into @x values (1,1)
insert into @x values (1,2)
insert into @x values (1,3)
insert into @x values (2,1)
insert into @x values (2,2)
insert into @x values (2,4)

select 
  o.id, 
  stuff(
    (
      select ', ' + cast(i.val as nvarchar) 
      from @x i
      where o.id = i.id
      for xml path('')
    ), 1, 2, ''
  )
from @x o 
group by id

kind regards,
Daniel

No comments: