Anatoly Lubarsky Logo
MSSQL, .NET, Design. Life and Music

T-SQL 2005: One-to-many comma separated

We have 2 tables one-to-many. How can we fetch parent table field, and the second field is its children comma separated ? In MSSQL 2000 we could use the following function. But in MSSQL 2005 with the help of FOR XML PATH feature it is a lot easier and the performance of string concatenation is amazing.


SELECT CustomerID
      ,(SELECT CAST(OrderID AS VARCHAR(MAX)) + ',' AS [text()]
          FROM dbo.Orders AS O
         WHERE O.CustomerID = C.CustomerID
         ORDER BY OrderID
           FOR XML PATH('')) AS Orders
  FROM dbo.Customers AS C;


Related Posts:

Sunday, November 13, 2005 11:44 PM

If your feedback doesn't appear right away, please be patient as it may take a few minutes to publish.

Post a Comment

Protected by CAPTCHAEnter the code you see
Name (*)  
E-mail (*)  
Url
Remember

Comment (*)