12.4. Creating an Aggregate Function
Problem
You need to create a CLR aggregate function.
Solution
This solution creates, registers, and executes a user-defined aggregate function that returns the sum of a SqlMoney column in a table. Follow these steps:
Create a new SQL Server project in Visual Studio and name it
ClrAggregateFunction.Create an aggregate item in the project. Name the item SumMoney.cs.
The C# code in SumMoney.cs in the project
ClrAggregateFunctionis shown in Example 12-7.Example 12-7. SumMoney.cs
using System; using System.Data; using System.Data.SqlClient; using System.Data.SqlTypes; using Microsoft.SqlServer.Server; [Serializable] [Microsoft.SqlServer.Server.SqlUserDefinedAggregate(Format.Native)] public struct SumMoney { private SqlMoney sum; public void Init( ) { sum = 0; } public void Accumulate(SqlMoney Value) { sum += Value; } public void Merge(SumMoney Group) { sum += Group.sum; } public SqlMoney Terminate( ) { return sum; } }Build the solution.
Register the assembly and create the aggregate function by executing the following T-SQL statement in SQL Server Management Studio, replacing
<path>appropriately:USE AdventureWorks GO CREATE ASSEMBLY ClrAggregateFunction FROM '<path>\ClrAggregateFunction\bin\Debug\ClrAggregateFunction.dll' GO CREATE AGGREGATE udfSumMoney ( @Value money ) RETURNS money EXTERNAL NAME ClrAggregateFunction.SumMoney
Execute the aggregate function on the
Sales.SalesOrderHeadertable inAdventureWorks:SELECT dbo.udfSumMoney(SubTotal), dbo.udfSumMoney(TaxAmt), ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access