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).

Unknown's avatar

About Jennifer Phillips Campbell

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

Leave a comment