.NET CLR Programming with SQL Server 2005 Made Simple

This article explains how to create .NET based CLR sub-routines in SQL Server 2005 in the simplest way possible. It is mainly targeted at .NET developers who want to work with SQL Server 2005 at server side.

Contributed by
Rating: 5 stars5 stars5 stars5 stars5 stars / 17
August 30, 2006
Rate this Article:
MEH MEH++


SEARCH ASP FREE
TOOLS YOU CAN USE

advertisement

A downloadable file for this article is available here.

The following are the topics covered in this article:

  • Creating a new database, table and a few rows.
  • Creating, coding and testing a .NET CLR stored procedure.
  • Creating, coding and testing a .NET CLR user-defined function.
  • Creating, coding and testing a .NET CLR aggregate function.

The entire source code for this contribution is freely available for download.

Creating your own database in SQL Server 2005

This section mainly covers the creation of a database and tables to be used in this series. Go through the following steps:

  • Go to Start -> Programs -> Microsoft SQL Server 2005 -> SQL Server Management Studio and connect to your SQL Server 2005 instance with the necessary credentials.
  • Once connected, open the SQL Server 2005 instance using the “Object Explorer," right click on “databases” and select “New Database” (Fig 1).

You will be presented with the “New Database” dialog.  Provide the database name “Sample” and click on “OK” to create the new database within the same instance.

  • Once the database is created, you must be able to watch the same in “Object explorer.”
  • Using the “Object explorer,” open “Sample” database, right click on “tables”   and select “new table" (Fig. 2). 
     
  • Create the structure of the table as shown in the following figure
    (Fig 3) and save the table with the name “emp.”


  • Once you have created the table “emp,” open it (Fig 4) and fill with rows as shown (Fig 5). 
     

    

.NET CLR stored procedure in SQL Server 2005 database: creation

Once you have created the database and tables as shown in the previous section, complete the following steps to create a .NET CLR stored procedure in a SQL Server 2005 database:

  • Go to Start -> Programs -> Microsoft Visual Studio 2005 -> Microsoft Visual Studio 2005.
  • Go to File -> New -> Project.
  • Within the “New Project” dialog box, select "database" for the "Project Type" in the “Visual Basic” tree and select “SQL Server Project” as the template.  Provide the name “SampleAllInOne.”  By this time, the dialog box should look something like the following (Fig 6).
           

 

  • Once you click “OK”, you will be provided with the “New Database Reference” dialog.  Provide your own instance name, select the database “Sample” (created in previous section) and test the connection (Fig 7).

     
  • Once testing is successfully completed, click on “OK” to create the project.
  • You will be provided with a dialog box, which asks you to enable CLR debugging or not.  Please click on “Yes” for that (Fig 8).

  • Using the “Solution explorer,” right click on the “SampleAllInOne” Project, and go to Add-> Stored Procedure (to create a new stored procedure) (Fig 9). 

  • You will be presented with the “Add New Item” dialog box.  Within that dialog box, select “Stored Procedure” as template and provide the name as “IncSalaries” and finally click on “Add” (Fig 10).

.NET CLR stored procedure in SQL Server 2005 database: Coding

Before proceeding through this section, make sure that you have completed everything in the previous section.

Once the “IncSalaries.vb” is created, modify your code in such a way that it looks something like the following:

ImportsSystem

ImportsSystem.Data

ImportsSystem.Data.SqlClient

ImportsSystem.Data.SqlTypes

ImportsMicrosoft.SqlServer.Server

 

 

PartialPublic Class StoredProcedures

    <Microsoft.SqlServer.Server.SqlProcedure()> _

    Public Shared Sub IncSalaries(ByVal IncVal As SqlDouble)

        ' Add your code here

        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

EndClass

The above is a simple CLR based stored procedure written using Visual Basic.NET 2005 to get it deployed in SQL Server 2005.  The name of the stored procedure is “IncSalaries;” it accepts a single parameter, “IncVal.” The above stored procedure simply increases the salaries of every employee in the table “emp” with the value provided as the parameter.

.NET CLR stored procedure in SQL Server 2005 database: Testing

 

To test the above stored procedure, follow the following steps:

  • Using “Solution Explorer,” open “test.sql” in “test scripts” (Fig 11).

  • Go to the last line and modify the code as follows:

--select 'To run your project, please edit the Test.sql file in
your project. This file is located in the Test Scripts folder in
the Solution Explorer.'

exec IncSalaries 50

  • Go to Start -> Programs -> Microsoft SQL Server 2005 -> Configuration Tools -> SQL Server Surface Area Configuration.
  • Within the window, click on “Surface Area Configuration for Features” (Fig 12). 


     
  • Enable the CLR integration as shown (Fig 13).

  • Press F5 to execute the whole solution.  If it executed with any errors, everything gets displayed in the “Output” window.
  • If the stored procedure executes successfully, you should be able to see all the salaries increased by 50.

.NET CLR user-defined function in SQL Server 2005 database

Now we shall extend the previous sections to add a stored function to our existing solution.

  • Using the “Solution explorer,” right click on the “SampleAllInOne” Project and go to Add-> User-defined Function (to create a new stored function) (Fig 14). 

  • You will be presented with the “Add New Item” dialog box.  Within that dialog box, select “User defined function” as the template, provide the name “getNetSalary” and finally click on “Add” (Fig 15).

Once the “getNetSalary.vb” is created, modify your code in such a way that it looks something like the following:

ImportsSystem

ImportsSystem.Data

ImportsSystem.Data.SqlClient

ImportsSystem.Data.SqlTypes

ImportsMicrosoft.SqlServer.Server

 

PartialPublic Class UserDefinedFunctions

    <Microsoft.SqlServer.Server.SqlFunction
(DataAccess:=DataAccessKind.Read)> _

    Public Shared Function getNetSalary(ByVal empno As SqlString)
As SqlDouble

        ' Add your code here

        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

EndClass

To test the above stored procedure, follow the following steps:

  • Using “Solution Explorer,” open “test.sql” in “test scripts” (Fig 11).

  • Go to the last line and modify the code as follows:

--select 'To run your project, please edit the Test.sql file in
your project. This file is located in the Test Scripts folder in
the Solution Explorer.'

--exec IncSalaries 50

select dbo.getNetSalary(empno) from sample.dbo.emp

Press F5 to execute the function and you should be able to see the result.

.NET CLR user-defined aggregate in SQL Server 2005 database

Now we shall extend the previous sections to add a stored function to our existing solution.

  • Using the “Solution explorer,” right click on the “SampleAllInOne” Project and go to Add-> Aggregate (to create a new aggregate function) (Fig 16).

  • You will be presented with the “Add New Item” dialog box. Within that dialog box, select “Aggregate” as the template, provide the name “NetSal” and finally click on “Add” (Fig 17).

Once the “NetSal.vb” is created, modify your code in such a way that it looks something like the following:

ImportsSystem

ImportsSystem.Data

ImportsSystem.Data.SqlClient

ImportsSystem.Data.SqlTypes

ImportsMicrosoft.SqlServer.Server

 

 

<Serializable()> _

<Microsoft.SqlServer.Server.SqlUserDefinedAggregate(Format.Native)> _

PublicStructure NetSal

 

    Public SumNetSal As SqlDouble

 

    Public Sub Init()

        ' Put your code here

        SumNetSal = 0

    End Sub

 

    Public Sub Accumulate(ByVal value As SqlDouble)

        ' Put your code here

        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)

        ' Put your code here

        SumNetSal += obj.SumNetSal

    End Sub

 

    Public Function Terminate() As SqlDouble

        ' Put your code here

        Return SumNetSal

    End Function

 

EndStructure

 

To test the above stored procedure, follow the following steps:

  • Using “Solution Explorer,” open “test.sql” in “test scripts.”

  • Go to the last line and modify the code as follows:

--select 'To run your project, please edit the Test.sql file in
your project. This file is located in the Test Scripts folder in
the Solution Explorer.'

--exec IncSalaries 50

--select dbo.getNetSalary(empno) from sample.dbo.emp

select dbo.NetSal(sal) from sample.dbo.emp

Press F5 to execute the function and you should be able to see the result.

The next article will follow with .NET CLR based User-Defined Types (UDT) and triggers in SQL Server 2005. This entire solution was developed using Microsoft SQL Server 2005 Developer edition along with Microsoft Visual Studio 2005 Professional Edition on Microsoft Windows Server 2003 Enterprise Edition. I didn’t really test the solution in any other version.

Any feedback, bugs, errors, suggestions, doubts etc., are highly appreciated at jag_chat@yahoo.com.

blog comments powered by Disqus
MS SQL SERVER ARTICLES

- Windows Azure Media Services Launched by Mic...
- Windows Server 8 Cloud Backup Beta Released
- Idera Announces SQL Compliance Manager 3.6
- Idera SQL Doctor 3.0 and MS SQL Changes
- Microsoft Cuts Windows Azure Compute and Sto...
- Express5800 to Mesh with SQL Server 2012
- Microsoft Azure Outage
- Windows Azure Server Supported by RealCloud ...
- Idera Releases SQL Diagnostic Manager v7.1
- MS SQL Sever 2012 Launch, New Idera Release
- OpenText Azure Cloud Solution, Geminaire Raa...
- Melissa Data Releases MatchUp Tool for SQL S...
- Glovia`s G2 ERP Solution to Support SQL Serv...
- Upgrade Assistant for SQL Server 2012 Releas...
- Azure Update Features Several New Improvemen...

ASP Web Hosting ASP.Net Web Hosting Windows Web Hosting
ASP Free Forums 
 RSS  Tutorials RSS
 RSS  Forums RSS
 RSS  All Feeds
Site Map 
Request Media Kit
Write For Us Get Paid 
Weekly Newsletter
 
Developer Updates  
Free Website Content 
Privacy Policy 
Support 


© 2003-2012 by Developer Shed. All rights reserved. DS Cluster 8 - Follow our Sitemap
Most Popular Topics
All ASP.Net Tutorials