String concatenation in Transact-SQL






4.87/5 (13 votes)
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)');