Click here to Skip to main content
15,878,814 members
Articles / Programming Languages / C#

Execute .NET Code under SQL Server 2005

Rate me:
Please Sign up or sign in to vote.
4.60/5 (59 votes)
26 Aug 2007CPOL5 min read 255.6K   2K   97   46
Article describes all the problems and constraints defined to use managed code under SQL Server 2005.

Introduction

First of all, I would like to congratulate the Microsoft Development Team for their superb and innovative technology using which we can use managed code written in any of the .NET supported languages in Microsoft SQL Server 2005 Stored Procedures. If I make it simple, then "Now you can call any function written in .NET class library in your SQL Server stored procedure". This technology will allow us to use the features of .NET language with the extendibility of SQL Server.

Description

I got an article of using MSMQ from SQL Server in CodeProject written by a gentlemen regarding MSMQ, and Messaging was used from SQL SP. I tried to show the constraints and limitations of using such assemblies and the required configuration in SQL Server 2005, so that the developers can begin. And I am sharing the practical problems which I faced in the actual implementation of this.

Before starting, you have to enable the managed code execution feature of the SQL Server which is disabled by default. To enable it, execute the following code as a query in your SQL Server query editor.

SQL
sp_configure 'clr enable', 1
GO
RECONFIGURE
GO

Now your server is ready to run managed code under its runtime. But let me tell you it's not magic but it's the same technology being used by the .NET framework. The only important part is that now SQL Server is also able to execute code on CLR. Isn't it great? Before writing this article, I did a lot of research on this. I got several articles explaining the same. But I faced a lot of problems because things were scattered. Now I am trying to simulate the whole procedure in this article. I did this study because of my specific requirements. I was using Message Queuing Service of Microsoft in C# .NET. But after some time, I got a requirement in which I needed to send a message from a Stored Procedure to MSMQ Queue. And till that time for me it was possible by using the System. Messaging namespace of .NET runtime only. I know most of the developers are wondering about MSMQ. Don't worry, I won't go into details of that right now. We will start with a simple application which will use a simple string returning function of C# .NET class library. Let's start with the class library.

  • Start .NET 2005 Studio.
  • Open a new class library.
  • Select C# as the language.
  • Name the project as ManagedCodeAndSQLServer.
  • By default, you will find a class named Class1.cs created for you.
  • Rename it as BaseFunctionClass.cs.

Create a simple function in the class as follows:

C#
using System;
using System.Collections.Generic;
using System.Text;
using System.IO;
using System.Data.SqlTypes;
using System.Data.SqlClient;
using Microsoft.SqlServer.Server;

namespace ManagedCodeAndSQLServer
{
    public class BaseFunctionClass
    {
        #region "Default Constructor"
        public BaseFunctionClass()
        { 
                   
        }
        #endregion

        #region "Welcome Function"
        /// <summary>
        /// This function will be called from the SQL Stored Procedure.
        /// </summary>
        /// <param name=""strName"">Name</param>
        /// <returns>Welcome Message</returns>
        [SqlProcedure]
        public static void GetMessage(SqlString strName, out SqlString  
        strMessge)
        {
          strMessge = "Welcome," + strName + ", " + "your code is getting
          executed under CLR !";
        }

        #endregion
    }
}

Important Points

I hope you are able to notice some new things in the above code. First of all, the [SqlProcedure] attribute on the GetMessage function intimates the CLR that the function is callable from SQL Server Stored procedure. The things that I am telling you are my own experiences; you may not find these things in articles published on the Internet. When using a CLR function, you must remember that the SQL server nvarchar is equivalent to System.String. But the most important part is that "CLR enabled procedure can only return Int32, Int and void data types". That's why I have used output parameter with the GetMessage function. Also I have used SqlString instead of System.String. Please keep all the above things in mind.

Now build the project and leave it because your work from the .NET class library point of view is over. Now come to your SQL Server again. I hope you still remember that we enabled CLR integration in our server at the start of the article. If not, then don't wait for me to come and enable it.

We have to register ManagedCodeAndSQLServer.dll as an assembly in our database. To register the assembly, you should have owner rights in your database or you should be the local system admin or Server Admin. The assemblies that we are going to register should be registered in UnSafe mode. Otherwise they would not be able to access resources external to SQL Server 2005. And to register an unsafe assembly, you should have 'unsafe' rights enabled in your username or role. All the above things are very important so take care of them, otherwise you won't be able to register your assembly. So create a database 'TestingCLR'. Before registering the .NET assembly in the database, you have to set the trustworthy option of the database on using the following code:

SQL
ALTER DATABASE TestingCLR SET TRUSTWORTHY ON
GO

Now register ManagedCodeAndSQLServer.dll under that using the following code:

SQL
CREATE ASSEMBLY ManagedCodeAndSQLServer
AUTHORIZATION dbo
FROM 'E:\Important\SQL\ManagedCodeAndSQLServer\ManagedCodeAndSQLServer\bin\
Debug\ManagedCodeAndSQLServer.dll'
WITH PERMISSION_SET = UNSAFE
GO


I am again saying if the dbo is not having 'unsafe assembly' right, it won't work. Similarly if I am using a specific class of .NET in my DLL, I have to register it prior to DLL registration in the same way. For example, I am using System.Messaging in my assembly, then I have to register it using the following code:

SQL
CREATE ASSEMBLY Messaging
AUTHORIZATION dbo
FROM 'C:\WINDOWS\Microsoft.NET\Framework\v2.0.50727\System.Messaging.dll'
WITH PERMISSION_SET = UNSAFE
GO

To use the normal functionality, we need not register the DLL from .NET runtime as in our case. Now in your server explorer, go to your TestingCLR database, select Programmability and in Assemblies, you will find an assembly registered with the name given by you, i.e., "HelloDotNet". Now you are almost done. You should know the full path (namespace convention) of the function that you are going to use from that assembly. In our case, it is: ManagedCodeAndSQLServer.BaseFunctionClass and GetMessage is our function to be used. Now I am creating a simple Stored Procedure to use this assembly as follows:

SQL
CREATE PROCEDURE usp_UseHelloDotNetAssembly
@name nvarchar(200),
@msg nvarchar(MAX)OUTPUT
AS EXTERNAL NAME ManagedCodeAndSQLServer.[ManagedCodeAndSQLServer.
BaseFunctionClass].GetMessage
GO

To execute the procedure:

SQL
DECLARE @msg varchar(MAX)
EXEC usp_UseHelloDotNetAssembly 'Kittu And Tannu',@msg output
PRINT @msg

You will get the following output: Welcome, Kittu And Tannu, your code is getting executed under CLR !

Try it and enjoy!

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Technical Lead Government of Dubai
United Arab Emirates United Arab Emirates
Thank you for visiting my profile at Code Project.

I have a proven track record of delivering excellence in working on many technically challenging project across the organizations I have had worked with. My core competencies are SharePoint Development, Administration, ASP.NET, .NET MVC, SQL Server.

Adding great values to the project and team is what I work for. I believe we should deliver the best possible solutions to the customer without compromising best practices and recommendations. Also for a better project management we need to juggle things like time, cost, risk, and quality and customer satisfaction in a successful project delivery.

Specialties: Competent technologist in the field of Microsoft .NET and SharePoint Technologies.
“A successful application development always leads to Feasibility, Reliability, Scalability and more importantly a better usability.”

Blogspot Articles: Visit my blog


"Improvement is the only thing which makes me happy...."
e-mail Addresses: kamalkharayat@gmail.com
skype id: stek_ks

Comments and Discussions

 
QuestionSystem.NullReferenceException: at TwilioSMS.SMS.ListarMensajes(String& respuesta) Pin
Ronnie Rios2-Oct-14 12:07
Ronnie Rios2-Oct-14 12:07 
AnswerRe: System.NullReferenceException: at TwilioSMS.SMS.ListarMensajes(String& respuesta) Pin
Ronnie Rios3-Oct-14 6:43
Ronnie Rios3-Oct-14 6:43 
GeneralMy vote of 5 Pin
Аslam Iqbal4-Mar-14 19:54
professionalАslam Iqbal4-Mar-14 19:54 
GeneralMy vote of 5 Pin
HimanshuJain6-Feb-14 5:22
HimanshuJain6-Feb-14 5:22 
GeneralMy vote of 5 Pin
abeethadesilva7-Aug-13 8:36
abeethadesilva7-Aug-13 8:36 
GeneralMy vote of 5 Pin
Member 255869716-Jan-13 17:16
Member 255869716-Jan-13 17:16 
QuestionNice tutorial Pin
donpp4623-Nov-12 1:08
donpp4623-Nov-12 1:08 
GeneralMy vote of 5 Pin
e.BISHOP12-Oct-12 7:31
e.BISHOP12-Oct-12 7:31 
GeneralMy vote of 5 Pin
Kanasz Robert25-Sep-12 22:46
professionalKanasz Robert25-Sep-12 22:46 
QuestionSuperb article!!!...Very few People Know how to run .Net code from SQL Pin
Punit Jain India15-May-12 23:28
Punit Jain India15-May-12 23:28 
QuestionWaking up a windows service on a remote server from T-SQL using .NET CLR Pin
mtrudel27-Mar-12 3:52
mtrudel27-Mar-12 3:52 
QuestionProblems with your explanation Pin
Member 235697716-Mar-12 9:46
Member 235697716-Mar-12 9:46 
GeneralMy vote of 5 Pin
neo_monty15-Nov-10 22:53
neo_monty15-Nov-10 22:53 
GeneralYour Job is really good Pin
Pradip.Kumar.Meta18-Jun-10 22:04
Pradip.Kumar.Meta18-Jun-10 22:04 
GeneralRe: Your Job is really good Pin
Kamal Singh Kharayat19-Jun-10 2:00
Kamal Singh Kharayat19-Jun-10 2:00 
GeneralProblem with sqlstring execution. Pin
Vvr1514-Apr-10 19:11
Vvr1514-Apr-10 19:11 
GeneralExcellent article. udf calling external function - need help Pin
Member 22538551-Apr-10 10:14
Member 22538551-Apr-10 10:14 
GeneralTransaction code Pin
kaams28-Feb-10 19:55
kaams28-Feb-10 19:55 
QuestionNaming Error? Pin
smcintyr_1126-Oct-09 12:21
smcintyr_1126-Oct-09 12:21 
AnswerRe: Naming Error? Pin
max_j_liang5-Nov-10 8:36
max_j_liang5-Nov-10 8:36 
GeneralRe: Naming Error? Pin
rameshKumar171714-Feb-16 18:35
rameshKumar171714-Feb-16 18:35 
GeneralCollation Error but lovly article Pin
skashifz27-May-09 14:32
skashifz27-May-09 14:32 
GeneralRe: Collation Error but lovly article Pin
Kamal Singh Kharayat27-May-09 18:06
Kamal Singh Kharayat27-May-09 18:06 
GeneralRe: Collation Error but lovly article Pin
Kamal Singh Kharayat27-May-09 18:09
Kamal Singh Kharayat27-May-09 18:09 
GeneralRe: Collation Error but lovly article Pin
Vvr1514-Apr-10 19:13
Vvr1514-Apr-10 19:13 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.