本文将解释如何在SQL Server 2005中以尽可能最简单的方法创建基于.NET的CLR子例程。本文主要针对在服务器端使用SQL Server 2005的.NET开发者。
一. 创建SQL Server 2005数据库
这一节主要讨论创建一个将用于本文中的数据库和表格。详见下列步骤:
· 执行"Start->PRograms->Microsoft SQL Server 2005->SQL Server Management Studio",并使用必要的证书连接到你的SQL Server 2005实例。
· 一旦建立连接,使用"Object Explorer"打开SQL Server 2005实例,然后右击"databases"并选择"New Database"(图1)。
图1. |
图2. |
图3. |
图4. 图5. |
图6. |
图7 |
图8 |
图9 |
图10 |
Imports System Imports System.Data Imports System.Data.SqlClient Imports System.Data.SqlTypes Imports Microsoft.SqlServer.Server Partial Public Class StoredProcedures <Microsoft.SqlServer.Server.SqlProcedure()> _ Public Shared Sub IncSalaries(ByVal IncVal As SqlDouble) '在此添加你的代码 Using cn As New SqlConnection("context connection=true") Dim cmd As New SqlCommand("update sample.dbo.emp set sal = sal + " & IncVal.ToString, cn) cmd.Connection.Open() cmd.ExecuteNonQuery() End Using End Sub End Class |
图11 |
--为运行你的工程,请编辑你的工程的Test.sql文件。 --这个文件位于Solution Explorer的"Test Scripts"文件夹下 exec IncSalaries 50 |
图12. |
图13. |
图14 |
图15. |
Imports System Imports System.Data Imports System.Data.SqlClient Imports System.Data.SqlTypes Imports Microsoft.SqlServer.Server PartialPublic Class UserDefinedFunctions <Microsoft.SqlServer.Server.SqlFunction (Dataaccess:=DataAccessKind.Read)> _ Public Shared Function getNetSalary(ByVal empno As SqlString) As SqlDouble '在此添加你的代码 Dim sal As Double Using cn As New SqlConnection("context connection=true") Dim cmd As New SqlCommand("select sal from sample.dbo.emp where empno='" & empno.ToString & "'", cn) cmd.Connection.Open() sal = CType(cmd.ExecuteScalar, Double) cmd.Dispose() End Using 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 Return net End Function End Class |
--为运行你的工程,请编辑你的工程的test.sql文件。 --这个文件位于Solution Explorer的"Test Scripts"文件夹下 --exec IncSalaries 50 select dbo.getNetSalary(empno) from sample.dbo.emp |
图16 |
图17 |
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 |
--为运行你的工程,请编辑你的工程的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 |
新闻热点
疑难解答