User defined aggregate function in SQL Server 2005
Find here the list of SQL Server aggregate functions.
Create a SQL Server project in Visual Studio 2005 or above. While creating the project provide the database information where you want to register the aggregate function.
To create an aggregate function to concatenate the values of a column to a comma separated value, use the following code. Take a look at this article for more information on the methods a user defined aggregate must implement.
| using System; using System.Data; using System.Data.SqlClient; using System.Data.SqlTypes; using Microsoft.SqlServer.Server; using System.IO; using System.Text; using System.Runtime.InteropServices; [Serializable] [StructLayout(LayoutKind.Sequential)] [SqlUserDefinedAggregate( Format.UserDefined, //use clr serialization to serialize the intermediate result IsInvariantToNulls = true, //optimizer property IsInvariantToDuplicates = false, //optimizer property IsInvariantToOrder = false, //optimizer property MaxByteSize = 8000)]//maximum size in bytes of persisted value
public class Concatenate : IBinarySerialize /// <summary> /// <summary> this.intermediateResult.Append(value.Value.ToString()).Append(‘,’); /// <summary> /// <summary> return new SqlString(output); public void Read(BinaryReader r) public void Write(BinaryWriter w) |
To enable SQL Server for CLR integration, click Start > Programs > Microsoft SQL Server 2005 > Configuration Tools > SQL Server Surface Area Configuration
Click on Surface Area Configuration for Features, choose the CLR integration and check the Enable CLR integration option.
How to register the assembly in SQL Server 2005
CREATE ASSEMBLY StringUtilities FROM ‘<file path>’
GO
CREATE AGGREGATE CONCAT (@input NVARCHAR(200)) RETURNS NVARCHAR(MAX)
EXTERNAL NAME StringUtilities.Concatenate
GO
GRANT EXEC ON dbo.CONCAT TO PUBLIC
GO
Usage:
For example, below is Table1. A query on Table1 like this SELECT Column1, Column2, CONCAT(Column3) FROM Table1 GROUPBY Column1, Column2 would return a result set A,B,’1,6’.
| Column 1 | Column 2 | Column 3 | |
| Row 1 | A | B | 1 |
| Row 2 | A | B | 6 |