Skip to content

Instantly share code, notes, and snippets.

@ronmichael
Last active December 11, 2015 09:49
Show Gist options
  • Save ronmichael/4582689 to your computer and use it in GitHub Desktop.
Save ronmichael/4582689 to your computer and use it in GitHub Desktop.
Use XML to concatenate multiple records into a single field in MSSQL
select
s.name,
stuff (
( SELECT ',' + c.name AS [text()] FROM cities c where c.stateid=s.id
FOR XML PATH('') ),
1, 1, '') cities
from states s;
select
s.name,
( SELECT '<city>' + c.name + '</city>' AS [text()] FROM cities c where c.stateid=s.id
FOR XML PATH('')
) cities
from states s;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment