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
Multiple readers can sometimes read the same row simultaneously causing a false result. SQL Server 2005 expert Adam Machanic suggests modifying the ... Continue Reading
Migrating to SQL Server 2005 from SQL Server 2000 is a hefty feat when compared to upgrading from 7.0 to SQL Server 2000. Site expert Adam Machanic ... Continue Reading
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
Have a question for an expert?
Please add a title for your question
Get answers from a TechTarget expert on whatever's puzzling you.