Group_concat in T-SQL

You may wish group_concat while working with MS SQL Server. Here’s a solution!

Say you have these tables:
a: id, content
b: id, val
rel_a_b: a_id, b_id

The SQL query

1
2
3
4
5
6
7
8
9
select a.*,
stuff(
(
select cast(';' as varchar(max)) + b.val
from b
inner join rel_a_b on b.id = rel_a_b.b_id and rel_a_b.a_id = a.id
for xml path('')
),1,1,'') as vals_combined
from a

Leave a Reply

Why ask?