Concatenating column from many side of one-to-many into single record using STUFF

SELECT OneTable.col1, OneTable.col2, 
     STUFF (
          (
               SELECT ' ' + mt.col1
               FROM ManyTable mt
               WHERE mt.foreignkeycol = OneTable.primarykeycol 
               FOR xml path('')
          ),
          1, 1, ''
     ) AS concatenatedcol
FROM  OneTable


Note: remember the '' in the inner SELECT statement, otherwise the concatenated column will contain XML tags (with the first bracket stripped).

Advertisements

About Jennifer Phillips Campbell

Software Developer and Medieval Historian
This entry was posted in SQL. Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s