A very common question in Microsoft SQL Server forums is whether SQL Server 2005 has any kind of aggregate that functions similarly to SUM, but works over sets of strings. For instance, assume that a database has the following table and data:
CREATE TABLE Strings ( String VARCHAR(20) ) INSERT Strings VALUES ('A') INSERT Strings VALUES ('B') INSERT Strings VALUES ('C')
Such an aggregate might be used on this table in order to produce a list of strings:
SELECT LISTAGG(String) FROM Strings Output: 'A, B, C'
Although this aggregate is not built into SQL Server 2005, the new system introduces a way of easily achieving this functionality. The most obvious way might be to use the new CLR user-defined aggregates (UDAs). Unfortunately, UDAs have an 8000-byte limit, which severely limits their use when aggregating large sets.
Another method for achieving this in SQL Server 2005 is a byproduct of the new FOR XML PATH functionality. By specifying an empty path, it's possible to produce a string aggregation-like functionality:
SELECT String + ', ' AS [text()] FROM Strings ORDER BY String FOR XML PATH('')
More information on this technique can be found on Aaron Bertrand's ASP FAQ site.
Do you have comments on this Ask the Expert Q&A? Let us know.
Dig Deeper on Microsoft SQL Server 2005
Related Q&A from Adam Machanic
SQL Server 2005 and T-SQL do have differences. The advantages and disadvantages would depend user environment as described by SQL Server 2005 expert... Continue Reading
SQL Server expert Adam Machanic highlights the differences to consider when weighing the move to SQL Server 2005 Enterprise and Standard Edtions. Continue Reading
Writing a generic audit trail trigger in SQL Server to keep track of inserts, deletes, and updates within a table is explained in this expert ... Continue Reading