Skip to main content

You are not logged in. Your edit will be placed in a queue until it is peer reviewed.

We welcome edits that make the post easier to understand and more valuable for readers. Because community members review edits, please try to make the post substantially better than how you found it, for example, by fixing grammar or adding additional resources and hyperlinks.

Required fields*

21
  • 18
    Great solution. The following may be helpful if you need to handle special characters like those in HTML: Rob Farley: Handling special characters with FOR XML PATH(''). Commented Apr 17, 2013 at 12:35
  • 14
    Apparently this doesn't work if the names contain XML characters such as < or &. See @BenHinman's comment. Commented Aug 13, 2013 at 1:26
  • 32
    NB: This method is reliant on undocumented behavior of FOR XML PATH (''). That means it should not be considered reliable as any patch or update could alter how this functions. It's basically relying on a deprecated feature. Commented Nov 13, 2014 at 18:54
  • 35
    @Whelkaholism The bottom line is that FOR XML is intended to generate XML, not concatenate arbitrary strings. That's why it escapes &, < and > to XML entity codes (&amp;, &lt;, &gt;). I assume it also will escape " and ' to &quot; and &apos; in attributes as well. It's not GROUP_CONCAT(), string_agg(), array_agg(), listagg(), etc. even if you can kind of make it do that. We should be spending our time demanding Microsoft implement a proper function. Commented Mar 23, 2015 at 14:15
  • 30
    Good news: MS SQL Server will be adding string_agg in v.Next. and all of this can go away. Commented Apr 6, 2017 at 0:32