15.02.2015 Views

C# 4 and .NET 4

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

966 ❘ ChaPTer 34 .net prOGrAmminG with sQl server<br />

In the code sample, the variable sum is used for accumulation of all values of a group. In the Init() method,<br />

the variable sum is initialized for every new group to accumulate. The method Accumulate() , which is<br />

invoked for every value, adds the value of the parameter to the sum variable. With the Merge() method,<br />

one aggregated group is added to the current group. Finally, the method Terminate() returns the result of<br />

a group:<br />

[Serializable]<br />

[SqlUserDefinedAggregate(Format.Native)]<br />

public struct SampleSum<br />

{<br />

private int sum;<br />

public void Init()<br />

{<br />

sum = 0;<br />

}<br />

public void Accumulate(SqlInt32 Value)<br />

{<br />

sum += Value.Value;<br />

}<br />

public void Merge(SampleSum Group)<br />

{<br />

sum += Group.sum;<br />

}<br />

}<br />

public SqlInt32 Terminate()<br />

{<br />

return new SqlInt32(sum);<br />

}<br />

code snippet SqlSamplesUsingAdventureWorks/SampleSum.cs<br />

You can use the Aggregate template from Visual Studio to create the core code for<br />

building the user - defi ned aggregate. The template from Visual Studio creates a struct<br />

that uses the SqlString type as a parameter <strong>and</strong> return type with the Accumulate <strong>and</strong><br />

Terminate methods. You can change the type to a type that represents the requirement<br />

of your aggregate. In the example, the SqlInt32 type is used.<br />

using user - defined aggregates<br />

The user - defi ned aggregate can be deployed either with Visual Studio or with the CREATE AGGREGATE<br />

statement. Following the CREATE AGGREGATE is the name of the aggregate, the parameter (@value int) ,<br />

<strong>and</strong> the return type. EXTERNAL NAME requires the name of the assembly <strong>and</strong> the .<strong>NET</strong> type including the<br />

namespace:<br />

CREATE AGGREGATE [SampleSum] (@value int) RETURNS [int] EXTERNAL NAME<br />

[Demo].[SampleSum]<br />

After the user - defi ned aggregate has been installed, it can be used as shown in the following<br />

SELECT statement, where the number of ordered products is returned by joining the Product<br />

<strong>and</strong> PurchaseOrderDetail tables. For the user - defi ned aggregate, the OrderQty column of the<br />

Order PurchaseOrderDetail table is defi ned as an argument:<br />

www.it-ebooks.info

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!