Possible Duplicates:
Implode type function in SQL Server 2000?
Concatenate row values T-SQL
I have a view which I'm querying that looks like this:
BuildingName PollNumber ------------ ---------- Foo Centre 12 Foo Centre 13 Foo Centre 14 Bar Hall 15 Bar Hall 16 Baz School 17
I need to write a query that groups BuildingNames together and displays a list of PollNumbers like this:
BuildingName PollNumbers ------------ ----------- Foo Centre 12, 13, 14 Bar Hall 15, 16 Baz School 17
How can I do this in T-SQL? I'd rather not resort to writing a stored procedure for this, since it seems like overkill, but I'm not exactly a database person. It seems like an aggregate function like SUM() or AVG() is what I need, but I don't know if T-SQL has one. I'm using SQL Server 2005.
There is no built in function in Sql Server, but it can be achieved by writing a user defined aggregate. This article mentions such a function as part of the SQL Server samples: http://msdn.microsoft.com/en-us/library/ms182741.aspx
As an example I include the code for a Concatenate aggregate. To use it, create a database project in Visual Studio, add new SqlAggregate and replace the code with the sample below. Once deployed you should find a new assembly in your database and an aggregate function
Concatenate
To use it, you can simply write an aggregate query:
The output of the query is:
I packaged up the class and the aggregate as a script which you can find here: https://gist.github.com/FilipDeVos/5b7b4addea1812067b09
for SQL Server 2017 and up use:
STRING_AGG()
OUTPUT:
for SQL Server 2005 and up to 2016, you need to do something like this:
OUTPUT:
Also, watch out, not all
FOR XML PATH
concatenations will properly handle XML special characters like my above example will.