SQL Azure string efficient connection solution
In SQL Azure, efficiently aggregating disparate string data into a single entity is critical. Due to the lack of CLR custom aggregate functions in SQL Azure, efficient alternatives need to be found.
Transact SQL Solution
An efficient way is to use WITH clause and recursive CTE (Common Table Expression). This method includes:
Description
Please consider the following inquiry:
<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>
Example
For the following data:
<code>ID Name ------- -------- 1 Matt 1 Rocks 2 Stylus 3 Foo 3 Bar 3 Baz</code>
Returns the following aggregate results:
<code>ID FullName ------- --------------------- 1 Matt, Rocks 2 Stylus 3 Foo, Bar, Baz</code>
Advantages
Note: In order to avoid the length overflow of nvarchar data type, change the type of CAST to nvarchar(max). In addition, the sorting in the example results is slightly different from the original text. This is because the sorting basis of ROW_NUMBER() OVER (PARTITION BY ID ORDER BY Name) is the Name field, resulting in differences in the sorting results. If you need a specific sorting method, modify the ORDER BY clause.
The above is the detailed content of How Can I Optimally Concatenate Strings in SQL Azure Without CLR Aggregate Functions?. For more information, please follow other related articles on the PHP Chinese website!