SIGN UP MEMBER LOGIN:    
ARTICLE

Create Your First CLR Trigger in SQL Server 2008 Using C#

Posted by Vishal Nayan Articles | SQL Server 2012 May 05, 2011
Here you will see how to create your first CLR Trigger for SQL Server 2008 using C#.
Reader Level:
Download Files:
 


Create your first CLR Trigger for SQL Server 2008 using C#.

What are CLR Triggers?

  • CLR triggers are trigger based on CLR.
  • CLR integration is new in SQL Server 2008. It allows for the database objects (such as a trigger) to be coded in .NET.
  • Objects that have heavy computation or that require a reference to an object outside SQL are coded in the CLR.
  • We can code both DDL and DML triggers by using a supported CLR language like C#.

Let us follow below some simple steps to create a CLR trigger:

Step 1: Create the CLR class. We code the CLR class module with a reference to the namespace required to compile CLR database objects.

Add the following references:

using Microsoft.SqlServer.Server;
using System.Data.SqlTypes;

So the following is the complete code for the class:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data.Sql;
using System.Data.SqlClient;
using Microsoft.SqlServer.Server;
using System.Data.SqlTypes;
using System.Text.RegularExpressions;

namespace CLRTrigger
{
    public class CLRTrigger
    {
        public static void showinserted()
        {
            SqlTriggerContext triggContext = SqlContext.TriggerContext;
            SqlConnection conn = new SqlConnection(" context connection =true ");
            conn.Open();
            SqlCommand sqlComm = conn.CreateCommand();
            SqlPipe sqlP = SqlContext.Pipe;
            SqlDataReader dr;
            sqlComm.CommandText = "SELECT pub_id, pub_name from inserted";
            dr = sqlComm.ExecuteReader();
            while (dr.Read())
                sqlP.Send((string)dr[0] + "," + (string)dr[1]);
        }
 
    }
}

Step 2: Compile this class and in the BIN folder of project we will get CLRTrigger.dll generated. After compiling for CLRTrigger.dll, we need to load the assembly into SQL Server.

Step 3: Now we will use T-SQL command to execute to create the assembly for CLRTrigger.dll. For that we will use CREATE ASSEMBLY in SQL Server.

CREATE ASSEMBLY   triggertest
FROM 'C:\CLRTrigger\CLRTrigger.dll'
WITH PERMISSION_SET = SAFE

CLRTrigger.gif

Step 4: The final step is to create the trigger that references the assembly. Now we will write the following T-SQL commands to add a trigger on the publishers table in the Pubs database.

CREATE TRIGGER tri_Publishes_clr
ON publishers
FOR INSERT
AS
      EXTERNAL NAME triggertest.CLRTrigger.showinserted

If you get a compatibility-related error message, run the following command to set compatibility.

ALTER DATABASE pubs
SET COMPATIBILITY_LEVEL =  100

Step 5: Enable CLR Stored procedure on SQL Server. For this run the following code:

EXEC sp_configure 'show advanced options' , '1';
reconfigure;

EXEC sp_configure 'clr enabled' , '1' ;
reconfigure;

EXEC sp_configure 'show advanced options' , '0';
reconfigure;

Step 6: Now we will run INSERT statement to the publishers table that fires the newly created CLR trigger.

INSERT publishers
(pub_id, pub_name)
values ('9922','Vishal Nayan')

The trigger simply echoes the contents of the inserted table. The output from the trigger is based on the insertion above.

-----------------------------------------------------
9922,Vishal Nayan

(1 row(s) affected)


The line of code which is printing the query result is actually the following code written in a managed environment.

while (dr.Read())
sqlP.Send((string)dr[0] + "," + (string)dr[1]);

Conclusion: The tri_Publishes_clr trigger demonstrates the basic steps for creating a CLR trigger. The true power of CLR triggers lies in performing more complex calculations, string manipulations
and things of this nature that can be done much more efficiently with CLR programming languages than they can in T-SQL.

Login to add your contents and source code to this article
share this article :
post comment
 

Thank you, excellent article :-) I had to make a minor adjustment to the trigger creation because of the namespace. CREATE TRIGGER tri_Publishes_clr ON publishers FOR INSERT AS EXTERNAL NAME triggertest.[CLRTrigger.CLRTrigger].showinserted Your demo included a select command. How about updates to multiple other columns in the newly inserted row of the table? I believe a CLR function is not allowed to alter data when called from a trigger. I did try that but got an error indicating that the INSERTED and DELETED tables cannot be updated. Maybe the CLR function can somehow be configured to return a string array and have the trigger do the updates? Regards, Markus Sveinn Markusson

Posted by Markus Sveinn Markusson Nov 25, 2011

:)

Posted by Vishal Nayan May 05, 2011

Thanks for Sharing...

Posted by Dinesh Beniwal May 05, 2011
Become a Sponsor
PREMIUM SPONSORS
  • ceTE software specializes in components for dynamic PDF generation and manipulation. The DynamicPDF™ product line allows you to dynamically generate PDF documents, merge PDF documents and new content to existing PDF documents from within your applications. Visit DynamicPDF here
    Finally – a virtual platform that delivers next-generation Windows Server 2008 Hyper-V virtualization technology from a managed hosting partner you can truly depend on. Visit www.maximumasp.com/max for a FREE 30 day trial. Hurry offer ends soon. Climb aboard the MaxV platform and take advantage of High Availability, Intelligent Monitoring, Recurrent Backups, and Scalability – with no hassle or hidden fees. As a managed hosting partner focused solely on Microsoft technologies since 2000, MaximumASP is uniquely qualified to provide the superior support that our business is built on. Unparalleled expertise with Microsoft technologies lead to working directly with Microsoft as first to offer IIS 7 and SQL 2008 betas in a hosted environment; partnering in the Go Live Program for Hyper-V; and product co-launches built on WS 2008 with Hyper-V technology.
Team Foundation Server Hosting
Become a Sponsor