Q
Problem solve Get help with specific problems with your technologies, process and projects.

Aggregate functions in SQL Server 2005

SQL Server 2005 expert Adam Machanic answers a commonly asked question regarding aggregate functions in SQL Server 2005.

Is there a string concatenation or list aggregate in SQL Server 2005?

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.
This was last published in October 2005

Dig Deeper on Microsoft SQL Server 2005

Have a question for an expert?

Please add a title for your question

Get answers from a TechTarget expert on whatever's puzzling you.

You will be able to add details on the next page.

Start the conversation

Send me notifications when other members comment.

Please create a username to comment.

-ADS BY GOOGLE

SearchBusinessAnalytics

SearchDataCenter

SearchDataManagement

SearchAWS

SearchOracle

SearchContentManagement

SearchWindowsServer

Close