IT tutorials
 
Database
 

SQL Server 2008 R2 : Creating and Managing Triggers - Using CLR Triggers

5/1/2013 1:50:29 AM
- Free product key for windows 10
- Free Product Key for Microsoft office 365
- Malwarebytes Premium 3.7.1 Serial Keys (LifeTime) 2019
CLR triggers are triggers based on the CLR. CLR integration, which was added with SQL Server 2008, allows for database objects (such as triggers) to be coded in one of the supported .NET languages, including Visual Basic .NET and C#.

The decision to code triggers and other database objects by using the CLR depends on the type of operations in the trigger. Typically, objects that have heavy computations or require references to objects outside SQL are coded in the CLR. Triggers strictly geared toward database access should continue to be coded in T-SQL.

You can code both DDL and DML triggers by using a supported CLR language. Generally speaking, it is much easier to code a CLR trigger in the Visual Studio .NET Integrated Development Environment (IDE), but you can create them outside the IDE as well. Visual Studio .NET provides a development environment that offers IntelliSense, debugging facilities, and other user-friendly capabilities that come with a robust IDE. 

The following basic steps are required to create a CLR trigger:

1.
Create the CLR class. You code the CLR class module with references to the namespaces required to compile CLR database objects.

2.
Compile the CLR class into an assembly or a DDL file, using the appropriate language compiler.

3.
Load the CLR assembly into SQL Server so that it can be referenced.

4.
Create the CLR trigger that references the loaded assembly.

The following listings provide examples of each of these steps.

Note

The CLR must be enabled on your server before you can add CLR components. The CLR option is disabled by default. To enable the CLR, you use the sp_configure 'clr enabled', 1 T-SQL command followed by the RECONFIGURE command. You can also enable CLR integration by using SQL Server 2008 Surface Area Configuration and then choosing the Surface Area Configuration for Features and selecting the Enable CLR Integration option.


Listing 1 contains C# code that can be used for the first step: creating the CLR class. This simple example selects rows from the inserted table.

Listing 1. A CLR Trigger Class Created with C#
using System;
using System.Data;
using System.Data.Sql;
using Microsoft.SqlServer.Server;
using System.Data.SqlClient;
using System.Data.SqlTypes;
using System.Xml;
using System.Text.RegularExpressions;

public class clrtriggertest
{
    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]);

    }
}


					  

The CLR class in Listing 30.19 needs to be compiled so that SQL Server can use it. The compiler for C# is located in the .NET Framework path, which is C:\WINDOWS\Microsoft.NET\Framework\version by default. The last part of the path, version, is the number of the latest version installed on your machine. For simplicity’s sake, you can add the full .NET Framework path to your path variable in the Advanced tab of your System Properties dialog. If you add the .NET Framework path to your path variable, you can run the executable for the compiler without navigating to that location.

You can save the code from Listing 1 in a text file named clrtriggertesting.cs. Then you can open a command prompt window and navigate to the folder where you saved the clrtriggertesting.cs file. The command shown in Listing 2 compiles the clrtriggertesting.cs file into clrtriggertesting.dll. This command can be run from any directory if you have added the .NET Framework path (for example, C:\WINDOWS\Microsoft.NET\Framework\v3.5) to your path variable. Without the additional path entry, you need to navigate to the .NET Framework path prior to executing the command.

Listing 2. A CLR Trigger Class Compilation
csc /target:library clrtriggertesting.cs

After compiling clrtriggertesting.dll, you need to load the assembly into SQL Server. Listing 30.21 shows the T-SQL command you can execute to create the assembly for clrtriggertesting.dll.

Listing 30.21. Using CREATE ASSEMBLY in SQL Server
CREATE ASSEMBLY triggertesting
 from 'c:\clrtrigger\clrtriggertesting.dll'
 WITH PERMISSION_SET = SAFE

The final step is to create the trigger that references the assembly. Listing 3 shows the T-SQL commands to add a trigger on the publishers table in the BigPubs2008 database.

Listing 3. Creating a CLR Trigger
CREATE TRIGGER tri_publishers_clr
ON publishers
FOR INSERT
AS
 EXTERNAL NAME triggertesting.clrtriggertest.showinserted

Listing 4 contains an INSERT statement to the publishers table that fires the newly created CLR trigger.

Listing 4. Using an INSERT Statement to Fire a CLR Trigger
INSERT publishers
 (pub_id, pub_name)
 values ('9922','Sams Publishing')

The trigger simply echoes the contents of the inserted table. The output from the trigger based on the insertion in Listing 4 is as follows:

9922, Sams Publishing

The tri_publishers 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 the can be done much more efficiently with CLR programming languages than they can in T-SQL.

 
Others
 
 
 
Top 10
 
- Microsoft Visio 2013 : Adding Structure to Your Diagrams - Finding containers and lists in Visio (part 2) - Wireframes,Legends
- Microsoft Visio 2013 : Adding Structure to Your Diagrams - Finding containers and lists in Visio (part 1) - Swimlanes
- Microsoft Visio 2013 : Adding Structure to Your Diagrams - Formatting and sizing lists
- Microsoft Visio 2013 : Adding Structure to Your Diagrams - Adding shapes to lists
- Microsoft Visio 2013 : Adding Structure to Your Diagrams - Sizing containers
- Microsoft Access 2010 : Control Properties and Why to Use Them (part 3) - The Other Properties of a Control
- Microsoft Access 2010 : Control Properties and Why to Use Them (part 2) - The Data Properties of a Control
- Microsoft Access 2010 : Control Properties and Why to Use Them (part 1) - The Format Properties of a Control
- Microsoft Access 2010 : Form Properties and Why Should You Use Them - Working with the Properties Window
- Microsoft Visio 2013 : Using the Organization Chart Wizard with new data
Technology FAQ
- Is possible to just to use a wireless router to extend wireless access to wireless access points?
- Ruby - Insert Struct to MySql
- how to find my Symantec pcAnywhere serial number
- About direct X / Open GL issue
- How to determine eclipse version?
- What SAN cert Exchange 2010 for UM, OA?
- How do I populate a SQL Express table from Excel file?
- code for express check out with Paypal.
- Problem with Templated User Control
- ShellExecute SW_HIDE
programming4us programming4us