Most of them might be aware that we can create a Managed Code and we can deploy it in SQL Server 2005 because SQL Server 2005 has CLR Enabled with it. In this tutorial we are going to have a look on how to create a SQL Server User Defined Function in C# and deploy that in SQL Server 2005. I have attached a file which contains the screen shots of the steps. We have to go through few steps in achieving this. - Create Project of Type DataBase and select SQL Server in the Project Template.
- Add an item of type User-Defined Functions.
- Write your code.
- Select Build ? Deploy <your projectName>
- If you have not enabled the CLR in SQL Server 2005. Before you have to enable the CLR in the SQL Server 2005.
- This can be done by executing the following statements in Query Window of SQL Server 2005.
EXEC sp_configure 'clr enabled' , 1 Go reconfigure; Then select Deploy Option from the menu.
Creating Database Project
- Go to File --> Project
- Select the project type as Database and Template as SQL Server Project

- In the next step you will be prompted to create a connection. You will get a popup window to select one connection or create a new connection for this project. I made use of my Local SQL Server Express database and selected NORTHWIND as the database.

- Then right click the project and select Add ? User-Defined Functions.
- Select User Defined Function under Visual Studio Installed Templates.
-


- I just named the CS file as Add3Numbers.
[Microsoft.SqlServer.Server.SqlFunction] public static SqlInt32 Add3Numbers(int firstNumber, int secondNumber, int thirdNumber) { return firstNumber + secondNumber + thirdNumber; }
- Build the application to make sure that it’s compiling successfully.
- Then, select Build ? Deploy <yourprojectName>
- It will deploy the function successfully. You can try running the following query in Management Studio.
- Login to the SQL Server and select the database which you have used to create a connection and run the following statement.
- select dbo.Add3Numbers(20,30,40)
- You will get a following error if CLR is not enabled
Msg 6263, Level 16, State 1, Line 1 Execution of user code in the .NET Framework is disabled. Enable "clr enabled" configuration option.- You have to run the following statement to execute the function. This has to be executed in Query Window of SQL Server 2005.
- EXEC sp_configure 'clr enabled' , 1
- This will enable the CLR in SQL Server 2005.
- Then execute [B]select dbo.Add3Numbers(20,30,40)[/B]
Even though it doesn’t cover an in-depth of deploying Managed Code in SQL Server, it covers a bit to get started with.
I will post some more articles on deploying managed code in SQL Server 2005 in coming days. If you have any comments/queries/suggestions, please leave here.
Regards, Brainstorming Guy aka Venkatarajan A
AttachmentsImages (19679-2253-Images.doc)



|
No responses found. Be the first to respond and make money from revenue sharing program.
|