SQL SERVER – Introduction to CLR – Simple Example of CLR Stored Procedure

CLR is abbreviation of Common Language Runtime. In SQL Server 2005 and later version of it database objects can be created which are created in CLR. Stored Procedures, Functions, Triggers can be coded in CLR. CLR is faster than T-SQL in many cases. CLR is mainly used to accomplish task which are not possible by T-SQL or can use lots of resources. CLR can be usually implemented where there is intense string operation, thread management or iteration methods which can be complicated for T-SQL. Implementing CLR provides more security to Extended Stored Procedure.

Let us create one very simple CLR where we will print current system datetime.

1) Open Microsoft Visual Studio >> Click New Project >> Select Visual C# >> Database >> SQL Server Project

SQL SERVER - Introduction to CLR - Simple Example of CLR Stored Procedure clr1

2) Either choose from existing database connection as reference or click on Add New Reference. In my example I have selected Add New Reference.

SQL SERVER - Introduction to CLR - Simple Example of CLR Stored Procedure clr2

3) If you have selected existing reference skip to next step or add database reference as displayed in image.

SQL SERVER - Introduction to CLR - Simple Example of CLR Stored Procedure clr3

4) Once database reference is added following project will be displayed in Solution Explorer. Right click on Solution Explorer >> Click on Add >> Stored Procedure.

SQL SERVER - Introduction to CLR - Simple Example of CLR Stored Procedure clr4

5) Add new stored procedure template from following screen.

SQL SERVER - Introduction to CLR - Simple Example of CLR Stored Procedure clr5

6) Once template added it will look like following image.

SQL SERVER - Introduction to CLR - Simple Example of CLR Stored Procedure clr6

7) Now where it suggest to //Put your code here. Replace it with code displayed in the image. Once the code is complete do following two steps.
a) Click on menu bar >> Build >> Build ProjectName
b) Click on menu bar >> Build >> Deploy ProjectName
Building and Deploying project should give successful message.

SQL SERVER - Introduction to CLR - Simple Example of CLR Stored Procedure clr7
using System;
using System.Data;
using System.Data.SqlClient;
using System.Data.SqlTypes;
using Microsoft.SqlServer.Server;

public partial class StoredProcedures
{
[Microsoft.SqlServer.Server.SqlProcedure] public static void CLRSPTest()
{
SqlPipe sp;
sp = SqlContext.Pipe;
String strCurrentTime = “Current System DateTime is: “
+ System.DateTime.Now.ToString();
sp.Send(strCurrentTime);
}
};
8) Now open SQL Server Management Studio and run following script in Query Editor. It should return current system datetime. Running it again the time will change.

SQL SERVER - Introduction to CLR - Simple Example of CLR Stored Procedure clr8

USE AdventureWorks
GO
EXEC dbo.CLRSPTest
GO

Reference : Pinal Dave (https://blog.sqlauthority.com)

CLR, Software Development, SQL Scripts, SQL Stored Procedure, SQL Utility
Previous Post
SQL SERVER – Retrieve – Select Only Date Part From DateTime – Best Practice – Part 2
Next Post
SQL SERVER – Transaction and Local Variables – Swap Variables – Update All At Once Concept

Related Posts

46 Comments. Leave new

  • Can a SQL CLR stored procedure call or excute a SQL procedure or function?

    Reply
  • Bhupendra Patel
    October 20, 2008 12:40 am

    Thanks for the post Pinal, I make a point to read your blog very useful stuff. I hope you dont mind me putting reference’s to other blogs

    Hi friends
    In case you run into the same problem as i did .
    i.e. at command prompt if you get
    “Execution of user code in the .NET Framework is disabled. Enable “clr enabled” configuration option.”

    then you can correct that by

    or

    Reply
    • u can use the following query:

      EXEC sp_configure ‘show advanced options’ , ‘1’;
      reconfigure;

      EXEC sp_configure ‘clr enabled’ , ‘1’ ;
      reconfigure;

      EXEC sp_configure ‘show advanced options’ , ‘0’;
      reconfigure;

      Reply
    • –ad-hoc-update-to-system-catalogs
      sp_configure ‘user options’, 1
      reconfigure with override;
      –allow user
      sp_configure ‘Allow Updates’, 1;
      reconfigure with override;
      –enable clr for sql clr run
      sp_configure ‘clr enabled’, 1;
      reconfigure with override;

      sp_configure

      Reply
  • hello pinal. one thing puzzled me a little bit, i really need to ask this:)

    you wrote “Stored Procedures, Functions, Triggers can be coded in CLR. CLR is faster than T-SQL in many cases. CLR is mainly used to accomplish task which are not possible by T-SQL or can use lots of resources.”
    now, if i save a stored procedure in sql server management studio, isnt it saved as a clr function? up to now i always knew that stored procedures are “compiled”, but your sentences made me understand as if the sp way is similar to hardcoding the sql query text in code and execute it with a SqlConnection object.
    can you clarify this point a little bit more please?

    Reply
  • hello pinal. one thing puzzled me a little bit, i really need to ask this:)

    you wrote “Stored Procedures, Functions, Triggers can be coded in CLR. CLR is faster than T-SQL in many cases. CLR is mainly used to accomplish task which are not possible by T-SQL or can use lots of resources.”

    now, if i save a stored procedure in sql server management studio, isnt it saved as a clr function? up to now i always knew that stored procedures are “compiled”, but your sentences made me understand as if the sp way is similar to hardcoding the sql query text in code and execute it with a SqlConnection object.

    can you clarify this point a little bit more please?

    Reply
  • Hi,
    Dave (Pinal). Thanks to God for bringing you to earth, you have a perculiar way of making programmers life easy, all over the web, there are lots of bla-bla..bla, but every argument you treat, is always a strait and simplest form to a solution.
    Keep up with it. YOU ARE MY OBAMA!

    Reply
  • Enjoyed post. I’m wondering why it is so difficult to find an example ( in literature or Internet at large ) of converting a T-SQL procedure which contains an “out” variable into an identicale C# CLR stored procedure. Is there something which prohibits this conversion ? If not, can you provide or cite an example ? Real world T-SQL procedures tend to have out parameters. Thx

    Reply
  • Thanks for a brilliant article Pinal. Very helpful.

    Reply
  • Interesting article, I was wondering if this is possible for a problem which I need to read from the different database to another database. Both database is in SQL Server.

    Reply
  • Really helpful…..all ur articles are wonderful…..it is simple and good….thank you

    Reply
  • I have a question :

    How can I connect to two or more databases using this project ?

    Reply
  • Great to see a simple example !
    Very useful to get started…Thanks !!!

    Reply
  • Great Article. Thank u very much..

    Reply
  • Anthony Henley
    March 25, 2011 12:03 am

    Are you saying that you need a full-blown version of Visual Studio to work with CLRs? I only have the Visual Studio that comes with SQL 2008 R2 and it does not have a Visual C# project type.

    Reply
  • Considering you are a proven expert, I wish you would have tried to add something more to this really simple example that can be found almost everywhere! but thanks for the effort.

    Reply
  • good article

    thank you very much

    Reply
  • “CLR is faster than T-SQL in many cases”
    Sorry but here i can’t agree with you. T-SQL is used mostly in stored procedures or functions, which they are stored on the server it’s self. Wright noe i am ‘translating’ a stored procedure from SQL into a CLR function, and after i tested it severl times the results are aprox:
    10 s for the SQL
    35 s for the CLR

    One of the time consuming effect for the CLR is opening/closing the readers, executing commands and all the other things that you must do in order to execute the SQL querys.
    But i think CLR are one of the best solutions if you want acces to a database from C#.

    Reply
  • When Exec dbo.clrsptest is run it puts the result in the messages tab in sql server management studio. How would one get the result into a table? This did not work.

    Use [vc]

    Create Table #t (date nvarchar (255))
    Insert Into #t
    Exec dbo.clrsptest

    Select * from #t
    Drop Table #t

    Reply
  • excellent and thank u……………….

    Reply
  • i wonder what will be the result of, sp_helptext CLRSPTest.

    Reply
  • Hi…. good article….it helped me alot….but,

    i want to use a global variable in the procedure…. how can i do this….?
    eg:

    public static string strr = “hhhiii”;

    [Microsoft.SqlServer.Server.SqlProcedure]
    public static void sp_GetHexValue(int number)
    {
    strr = “hhhhhiiiii”;
    SqlContext.Pipe.Send(strr);
    }

    i’m getting an error while deploying.

    ” Deploy error SQL01268: .Net SqlClient Data Provider: Msg 6211, Level 16, State 1, Line 1 CREATE ASSEMBLY failed because type ‘StoredProcedures’ in external_access assembly ‘TestSQL_CLR_Project’ has a static field ‘strr’. Attributes of static fields in external_access assemblies must be marked readonly in Visual C#, ReadOnly in Visual Basic, or initonly in Visual C++ and intermediate language.
    An error occurred while the batch was being executed.”

    so, i tried giving readonly property…. it worked…. but, i’m unable to set the value at runtime.

    how can i achieve this ….?

    Thanks 4 ur help.

    Reply

Leave a Reply