探讨SQL Server 2005.NET CLR编程(4)
http://www.sina.com.cn 2006年10月08日 08:54
天极yesky
六. 定义.NET CLR用户定义聚合器 现在,我们开始在上一节基础上在我们的现有方案上添加一个聚合函数。
· 使用"Solution explorer",右击"SampleAllInOne"工程并转到"Add->Aggregate"(以创建一个新的聚合函数)(图16)。
图16 |
· 之后,出现"Add New Item"对话框。在该对话框内,选择"Aggregate"作为模板,输入名字"NetSal"并点击"Add"(图17)。
图17 |
一旦创建"NetSal.vb",接下来以下列方式修改你的代码:
Imports System Imports System.Data Imports System.Data.SqlClient Imports System.Data.SqlTypes Imports Microsoft.SqlServer.Server <Serializable()> _ <Microsoft.SqlServer.Server.SqlUserDefinedAggregate(Format.Native)> _ PublicStructure NetSal Public SumNetSal As SqlDouble Public Sub Init() '在此加入你的代码 SumNetSal = 0 End Sub Public Sub Accumulate(ByVal value As SqlDouble) '在此加入你的代码 Dim sal As Double = CType(value, Double) Dim hra As Double = sal * 10 / 100 Dim ta As Double = 200 Dim gross As Double = sal + hra + ta Dim epf As Double = sal * 5 / 100 Dim net As Double = gross - epf SumNetSal += net End Sub Public Sub Merge(ByVal obj As NetSal) '在此加入你的代码 SumNetSal += obj.SumNetSal End Sub Public Function Terminate() As SqlDouble '在此加入你的代码 Return SumNetSal End Function EndStructure |
为了测试上面的存储过程,遵循下列步骤:
· 使用"Solution Explorer",然后在"test scripts"中打开"test.sql"。
· 转到最后一行并修改如下代码:
--为运行你的工程,请编辑你的工程的test.sql文件。 --这个文件位于Solution Explorer的"Test Scripts"文件夹下 --exec IncSalaries 50 --select dbo.getNetSalary(empno) from sample.dbo.emp select dbo.NetSal(sal) from sample.dbo.emp |
按F5执行该函数,你应该能够观察到相应的结果。