65.9K
CodeProject is changing. Read more.
Home

String concatenation in Transact-SQL

starIconstarIconstarIconstarIcon
emptyStarIcon
starIcon

4.87/5 (13 votes)

Oct 28, 2010

CPOL
viewsIcon

28533

Performing fast concatenation of strings from different records

Many articles show how to concatenate rowset in single string using FOR XML PATH('') as follows:
    SELECT ProductName + ','
    FROM Northwind.dbo.Products
    FOR XML PATH('');
The problem here is that XML entities can appear in the result string. If you have "Head & Shoulders" in list of products, you will find "Head & Shoulders" in the resulting string. The following code performs correct concatenation:
    DECLARE @iXml xml;

    SELECT @iXml = (
      SELECT ProductName + ','
      FROM Northwind.dbo.Products
      FOR XML PATH);

    SELECT @iXml.value('.','nvarchar(max)');