How to concatenate distinct columns of otherwise duplicate rows into one row without using FOR XML PATH('')?

StackOverflow https://stackoverflow.com/questions/23142332

Question

I have this query:

SELECT DISTINCT
            f1.CourseEventKey,
            STUFF
            (
                (
                    SELECT      '; ' + Title
                    FROM        (
                                    SELECT DISTINCT
                                                ces.CourseEventKey,
                                                f.Title
                                    FROM        CourseEventSchedule ces
                                    INNER JOIN  Facility f ON f.FacilityKey = ces.FacilityKey
                                    WHERE       ces.CourseEventKey IN
                                                (
                                                    SELECT      CourseEventKey
                                                    FROM        @CourseEvents
                                                )
                                ) f2
                    WHERE       f2.CourseEventKey = f1.CourseEventKey
                    FOR XML PATH('')
                ), 1, 2, ''
            )
FROM        (
                SELECT DISTINCT
                            ces.CourseEventKey,
                            f.Title
                FROM        CourseEventSchedule ces
                INNER JOIN  Facility f ON f.FacilityKey = ces.FacilityKey
                WHERE       ces.CourseEventKey IN
                            (
                                SELECT      CourseEventKey
                                FROM        @CourseEvents
                            )
            ) f1

It produces this result set:

CourseEventKey Titles
-------------- ----------------------------------
29             Test Facility 1
30             Memphis Training Room
32             Drury Inn & Suites Creve Coeur

The data is accurate, but I can't have FOR XML PATH('') because it escapes certain special characters.

To be clear, I'm using FOR XML PATH('') because it is possible for records with the same CourseEventKey to have multiple Facility titles associated with them.

How can I retain the data returned by this query without using FOR XML PATH('')?

Was it helpful?

Solution

Change the "for xml path('') )" section to "for xml path(''), root('root'), type).query('root').value ('.', 'varchar(max)')" this will unescape the characters correctly.

Sorry for the poor formatting but not at my computer right now. I can give a full example later if you need.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top