Welcome to TechNet Blogs Sign in | Join | Help

Database Programming: The String Concatenation XML Trick, Finalized

It's an especially Good Friday when we can close the loop on a technical conversation, and I believe that our modifications to The Technique That Lance Found, also discussed here and here, are complete.  Scott Whigham left a comment on the most recent post offering an XML implementation that will run in AdventureWorks.  A little fiddling with Scott's syntax yields this approach to the original issue:

;WITH ColumnToPivot ([data()]) AS (
    SELECT p.ParentString + N', '
    FROM Parent p
    JOIN Child c
    ON c.ParentId = p.ParentId
    WHERE c.ChildId = 2
    ORDER BY p.ParentId
    FOR XML PATH(''), TYPE
),
    XmlRawData (CSVString) AS (
        SELECT (SELECT [data()] AS mydata FROM ColumnToPivot AS d FOR XML RAW, TYPE).value( '/row[1]/mydata[1]', 'NVARCHAR(max)') AS CSV_Column
)
SELECT
LEFT(CSVString, LEN(CSVString)-1) AS CSVList
FROM XmlRawData

This construction has a number of things going for it.  It seems to be the fastest of the lot (no nested SELECTs!), which is always nice, and it manages to impose an ORDER BY without resorting to the use of TOP, so we're out of the "dirty trick" business.  It also strikes me as the easiest of the bunch to read.

For the record, here's the result set from this latest syntax:

CSV_List
<Parent 1 String>,<Parent 2 String>,<Parent 3 String>

Thanks again to Lance Larsen, Adam Machanic, and Scott Whigham for contributing to this conversation.  Isn't community grand?

     -wp

Published Friday, March 21, 2008 7:15 AM by Ward Pond

Comment Notification

If you would like to receive an email when updates are made to this post, please register here

Subscribe to this post's comments using RSS

Comments

# http://sqlservercode.blogspot.com/2008/03/links-of-week-20080322.html

Sunday, March 23, 2008 5:28 PM by TrackBack

# re: Database Programming: The String Concatenation XML Trick, Finalized

Monday, March 24, 2008 7:09 PM by Scott Whigham

Very cool - I love the community approach!

# May Glad Tidings be Upon You

Saturday, December 20, 2008 10:55 AM by Ward Pond's SQL Server blog

UPDATED 20 Dec 2008 to fix links It’s that time of year again, when I disappear from the blogosphere

# Database Programming: The String Concatenation XML Trick, Revisited

Thursday, February 26, 2009 10:31 PM by Ward Pond's SQL Server blog

I’ve got to pay more punctual attention to my comment pool.. RBarryYoung’s movingsql.com will be on my

# T-SQL Challenge: Grouped String Concatenation

Friday, February 27, 2009 1:25 PM by Adam Machanic

It's been quite a while since the LIKE vs ? Puzzle , and I feel like it's time for another one. Response

Leave a Comment

(required) 
required 
(required) 

  
Enter Code Here: Required
 
Page view tracker