Welcome to Scribd, the world's digital library. Read, publish, and share books and documents. See more
Standard view
Full view
of .
Look up keyword
Like this
0 of .
Results for:
No results containing your search query
P. 1
Creating Triggers in SQL Server 2005

Creating Triggers in SQL Server 2005



|Views: 2,790 |Likes:
Published by join lucky

More info:

Published by: join lucky on Jun 06, 2008
Copyright:Attribution Non-commercial


Read on Scribd mobile: iPhone, iPad and Android.
download as DOC, PDF, TXT or read online from Scribd
See more
See less





Creating Triggers in SQL Server 2005
One of the excellent features provided by SQL Server 2005 (code named Yukon) is its integrationwith the .NET CLR which makes it possible for us to author triggers, stored procedures, user defined functions, and create other database objects using a managed language such asVB.NET, C#, and so on. This approach provides a number of benefits such as increasedproductivity, significant performance gains and the ability to leverage the features of .NET CodeAccess Security to prevent assemblies from performing certain operations and so on. In thisarticle, we will take a look at this new CLR integration feature and learn how to create triggers inSQL Server using a managed language. Along the way, we will also learn how the features of .NET code access security can be leveraged to better control the assembly executionenvironment. Finally, we will discuss when to use T-SQL and when to use a .NET language whencreating SQL Server triggers.
.NET CLR and SQL Server Integration
In previous versions of SQL Server, database programmers were limited to using Transact-SQLwhen creating server side objects such as triggers, stored procedures, and user defined functionsand so on. But now with the integration of SQL Server with .NET CLR, it opens up a wholeavenue of opportunities. Before we talk about the features of .NET CLR integration with SQLServer, let us understand the limitations of T-SQL when it comes to creating server side objects.Transact-SQL (T-SQL) is an extension of the Structured Query Language as defined by theInternational Standards Organization (ISO) and the American National Standards Institute (ANSI).Using T-SQL, database developers can create, modify and delete databases and tables, as wellas insert, retrieve, modify and delete data stored in a database. T-SQL is specifically designed for direct data access and manipulation. While T-SQL can be very useful for data access andmanagement, it is not a full-fledged programming language in the way that Visual Basic .NET andC# are. For example, T-SQL does not support arrays, strongly typed objects, collections, for eachloops, bit shifting or classes and so on. While some of these constructs can be simulated in T-SQL, managed code based languages such as VB.NET or C# have first-class support for theseconstructs. Now that we have understood the limitations of T-SQL, let us talk about theadvantages of .NET CLR integration with SQL Server.With CLR integration, things have changed dramatically. The CLR provides the executionenvironment for all the server side objects that are created using a .NET language. This meansthe database developers can now perform tasks that were impossible or difficult to achieve withT-SQL alone. Especially when working with large amounts of server code, developers can easilyorganize and maintain your code investments. By allowing the code to run under the control of .NET CLR, you can also leverage the code access security features of .NET. For example, beforeexecuting code, the CLR can check to see if the code is safe. This process is known as"verification." During verification, the CLR performs several checks to ensure that the code is safeto run. For example, the code is checked to ensure that no memory is read that has not be beenwritten to. The CLR will also prevent buffer overflows. Now that we have had a complete overviewof the .NET CLR integration, let us understand the steps to be followed for creating a trigger inVB.NET.
Creating a Trigger using Managed Code in SQL Server 
As you may know, triggers are executed as the result of a user action against a table, such as anINSERT, UPDATE or DELETE statement. To create a trigger using a managed language such asC# or VB.NET, you need to go through the following steps.
Create a .NET class and implement the functionality of the extended trigger within thatclass.
Compile that class to produce a .NET assembly.
Register that assembly in SQL Server using the Create Assembly statement.
Create trigger definitions. As part of this, you also associate the trigger with the actualmethods in the assembly. Once this is done, the triggers are configured and can beinvoked automatically like any other triggers.In the next section, we will take an in-depth look at the above steps and understand what it takesto create a trigger using C#.
Implementation of .NET class that will act as an extended Trigger 
Before we go onto creating the .NET class that will implement the functionalities of the trigger, letus create a simple table named Users using the following DDL statement.
CREATE TABLE Users(UserName Varchar (100) )
Now that we have created the table, let us create the C# class that implements the functionalitiesrequired of the trigger. Towards this end, we will create a C# class named Users and modify itscode to look like the following code.
using System.Data;using System.Data.Sql;using System.Data.SqlServer;public class Users{public static void InsertTrigger(){SqlTriggerContext triggerContext = SqlContext.GetTriggerContext();SqlPipe sqlPipe = SqlContext.GetPipe();SqlCommand command = SqlContext.GetCommand();if (triggerContext.TriggerAction ==System.Data.Sql.TriggerAction.Insert){command.CommandText = "SELECT * FROM INSERTED";sqlPipe.Execute(command);}}}
Let us walk through the above code. To execute .NET code in SQL server, you need to referencethe System.Data.Sql and System.Data.SqlServer namespaces. Then we declare a class namedUsers that is mainly used to implement the trigger functionalities for the Users table. Then we getreference to the current trigger context by invoking the GetTriggerContext method of theSqlContext class. The SqlTriggerContext object enables the code to access the virtual table that'screated during the execution of the trigger. This virtual table stores the data that caused thetrigger to fire. The SqlPipe object enables the extended trigger to communicate with the externalcaller. To get reference to the SqlPipe object, we invoke the GetPipe method of the SqlContextclass. Once we have reference to the SqlPipe object, we can then return tabular results andmessages to the client. In this example, the SqlTriggerContext object is used to first determine if the trigger action was an insert operation. If so, then the contents of the virtual trigger table areretrieved and sent to the caller.
Compilation of .NET class to create a .NET Assembly
Now that we have created the C# class, let us compile that class to produce a .NET assembly,which can then be registered with SQL Server. The following screenshot shows how to compilethe C# class to produce the .NET assembly.As shown in above screenshot, we need to reference the sqlaccess.dll since our code uses theclasses contained in the System.Data.SqlServer namespaces.
Registering the assembly in SQL Server 
When writing managed code, the deployment unit is called an assembly. An assembly ispackaged as a DLL or executable (EXE) file. While an executable can run on its own, a DLL mustbe hosted in an existing application. Managed DLL assemblies can be loaded into and hosted byMicrosoft SQL Server. To load an assembly into SQL Server, you need to use the CreateAssembly statement.
CREATE ASSEMBLY UsersFROM 'C:\Program Files\Microsoft SQLServer\MSSQL.1\MSSQL\Binn\Test\CLRProcedures\CS\Users.dll'
The FROM clause specifies the pathname of the assembly to load. This path can either be aUNC path or a physical file path that is local to the machine. The above statement will register theassembly with the SQL Server. Note that the assembly name should be unique within a database.Once you load the assembly, a copy of the assembly is loaded into SQL Server. After that, if youwant to make changes to the assembly, you need to drop the assembly first and then reregister that with SQL Server again. To drop an assembly from SQL Server, you need to use the DropAssembly statement. For example, to drop the assembly that we created earlier, we need to usethe following command.
Loading an assembly into Microsoft SQL Server is the first step in exposing the functionality thatthe assembly provides. Now that we have loaded the assembly, the next step is to associate anextended trigger to a specific method of the class that is contained in the assembly.
Creating Trigger Definitions
In this step, we will create an extended trigger using the Create Trigger statement. SQL Server 2005 supports a new clause named External Name that allows you to reference a method in theregistered assembly. By referencing this method, we hook the trigger to that method in theassembly.

Activity (9)

You've already reviewed this. Edit your review.
1 hundred reads
1 thousand reads
rohitpr1111 liked this
rohitpr1111 liked this
Indresh Pandey liked this
soni_vinay liked this
Vinay V Perla liked this

You're Reading a Free Preview

/*********** DO NOT ALTER ANYTHING BELOW THIS LINE ! ************/ var s_code=s.t();if(s_code)document.write(s_code)//-->