SQL Server string concatenation method
Problem description:
You need to aggregate strings from multiple lines into a single line. COALESCE and FOR XML won't do what you need, and Azure doesn't support CLR-defined aggregate functions. You need to look for the best alternative.
Solution:
Using standard Transact SQL, you can concatenate strings efficiently by following these steps:
Instructions:
This method uses three CTEs:
To use this solution, you must specify grouping and sorting criteria. For example, in your case, rows with the same ID are concatenated and sorted alphabetically.
Example:
Consider the following data:
<code>ID Name -- -- 1 Matt 1 Rocks 2 Stylus 3 Foo 3 Bar 3 Baz</code>
The query and its output are as follows:
<code class="language-sql">WITH Partitioned AS ( SELECT ID, Name, ROW_NUMBER() OVER (PARTITION BY ID ORDER BY Name) AS NameNumber, COUNT(*) OVER (PARTITION BY ID) AS NameCount FROM dbo.SourceTable ), Concatenated AS ( SELECT ID, CAST(Name AS nvarchar(max)) AS FullName, Name, NameNumber, NameCount FROM Partitioned WHERE NameNumber = 1 UNION ALL SELECT P.ID, CAST(C.FullName + ', ' + P.Name AS nvarchar(max)), P.Name, P.NameNumber, P.NameCount FROM Partitioned AS P INNER JOIN Concatenated AS C ON P.ID = C.ID AND P.NameNumber = C.NameNumber + 1 ) SELECT ID, FullName FROM Concatenated WHERE NameNumber = NameCount;</code>
<code>ID FullName -- ------------------------------ 2 Stylus 3 Bar, Baz, Foo 1 Matt, Rocks</code>
Improvement description: Change the nvarchar
type to nvarchar(max)
to support longer string concatenation results. This avoids potential string length overflow errors.
The above is the detailed content of How Can I Efficiently Concatenate Strings from Multiple Rows in SQL Server Without Using FOR XML or CLR Functions?. For more information, please follow other related articles on the PHP Chinese website!