Concatenate strings

0

Please login or register to vote for this query.

(click on this box to dismiss)

concatenating strings using for xml path('')

Lifehacks

Q&A for people looking to bypass life's everyday problems with simple tricks

-- Concatenate strings
-- concatenating strings using for xml path('')

;with form(id, name) as
(
select 1,   'Green Box' union all
select 2,   'Red Box' union all
select 3,   'Yellow Box'
),

fruitboxes(boxID, name) as
(
select 1,      'apple' union all
select 1,      'orange' union all
select 2,      'apple' union all
select 2,      'orange' union all
select 3,      'apple'
)

select
  b.id,
  b.name,
  stuff((select ','+f.name
         from fruitboxes as f 
         where f.boxID = b.id
         for xml path(''), type).value('.', 'nvarchar(max)'), 1, 1, '') as Fruits
from form as b

Enter Parameters

Options:
Switch to meta site
loading Hold tight while we fetch your results