SQL 2005 – Return query rows as one delimited column
Once in a while we need to return data from SQL as delimited string of values and not as rows. There are several ways to do that, but personally i like the next one.
SELECT CustomerID AS 'data()'
FROM Customer
FOR XML PATH('')
-- This will result one column with a value like this: 1 2 3 4 5 6 7 8
-- And to get the column as part of some other query:
SELECT CustomerID,
(SELECT OrderID AS 'data()'
FROM Order O WHERE O.CustomerID = C.Customer ID
FOR XML PATH('')) AS OrderList
FROM Customer C
-- The result of the above query will be something like this :
-- CustomerID | OrderList
-- --------------------------------
-- 1 | 1 2 5 9 90 200
-- 2 | 2 7 10 22
-- 3 | 12 17 246
-- 4 | 83 92 1002
-- And of course we could return it as XML
SELECT CustomerID AS '@id',
(SELECT OrderID AS 'data()'
FROM Order O WHERE O.CustomerID = C.Customer ID
FOR XML PATH('')) AS '@ordelist'
FROM Customer C
FOR XML PATH('customer'), ROOT('root')
-- The result of the above query will be something like this :
<root>
<customer id="1" orderlist="1 2 5 9 90 200"/>
<customer id="2" orderlist="2 7 10 22"/>
<customer id="3" orderlist="12 17 246"/>
<customer id="4" orderlist="83 92 1002"/>
</root>
A few posts you might find interesting:
Categories: ASP.NET, Interview Questions, Programming, SQL, SQL 2005, Tips & Tricks, XML

Cool post, just subscribed.
I have already seen it somethere…
AnnaHopn
Well, everything is out there somewhere.
The question is how easy to find it.
Not sure that this is true:), but thanks for a post.
You are welcome
Anyway, a very similar example can be found on : MSDN Examples: Using PATH Mode