Professional Documents
Culture Documents
CLR Integration
CLR Integration
CLR Integration
In
SQL Server 2005
The common language runtime (CLR) is the heart of the Microsoft .NET
Framework and provides the execution environment for all .NET Framework code. Code
that runs within the CLR is referred to as managed code. The CLR provides various
functions and services required for program execution, including just-in-time (JIT)
compilation, allocating and managing memory, enforcing type safety, exception
handling, thread management, and security.
With the CLR hosted in Microsoft SQL Server (called CLR integration), you can author
stored procedures, triggers, user-defined functions, user-defined types, and user-
defined aggregates in managed code. Because managed code compiles to native code
prior to execution, you can achieve significant performance increases in some
scenarios.
Managed code uses Code Access Security (CAS), code links, and application domains
to prevent assemblies from performing certain operations. SQL Server 2005 uses CAS
to help secure the managed code and prevent compromise of the operating system or
database server.
What follows is a brief overview of the SQL Server functionality that is enabled
by CLR integration and how Visual Studio 2005 supports these features.
Manual Deployment
Registering and executing managed code in the database consists of the following
steps:
1. The developer writes a managed program as a set of class definitions. SQL
Server routines—stored procedures, functions, or triggers—are written as static
(or Shared in Microsoft Visual Basic .NET) methods of a class. User-defined
types and aggregates are written as entire classes. The developer compiles the
code and creates an assembly.
2. The assembly is uploaded into a SQL Server database, where it is stored in the
system catalogs using the CREATE ASSEMBLY data definition language (DDL)
statement.
3. Transact-SQL (T-SQL) objects, such as routines, types, and aggregates are
then created and bound to entry points (methods in the case of routines and
classes for types and aggregates) in the assembly that has been already
uploaded. This is accomplished using the CREATE
PROCEDURE/FUNCTION/TRIGGER/TYPE/AGGREGATE statements.
4. After routines are created, they can be used like T-SQL routines by applications.
For example, CLR functions can be called from T-SQL queries and CLR
procedures can be called from a client application or from a T-SQL batch as if
they were T-SQL procedures.
In evaluating the use of CLR integration a developer needs to compare it to the other
available options. Here we aim to provide a base for that comparison, positioning it
against existing programming techniques: Transact-SQL, extended stored procedures,
and code in the middle-tier. In this section we will concentrate on user defined
routines.
CLR vs. Transact-SQL
Transact-SQL (T-SQL) is the native programming language supported by SQL Server.
Like most versions of SQL, it contains data manipulation features and data definition
features. The data manipulation features can be broadly categorized into two parts: a
declarative query language (composed of SELECT/INSERT/UPDATE/DELETE
statements) and a procedural language (WHILE, assignment, triggers, cursors, etc.)
Broadly speaking, CLR support in SQL Server provides an alternative to the procedural
portion of T-SQL.
Even without CLR support, it is important to recognize that database applications
should use the declarative query language as much as possible. This portion of the
language is able to leverage the power of the query processor, which is best able to
optimize and perform bulk operations. Database applications should only resort to
procedural programming to express logic that cannot be expressed within the query
language.
All of this remains true with CLR support in SQL Server: the CLR should not be used to
write procedural code that can be expressed using the declarative features of the T-
SQL language. Developers should be aware that there are a number of significant
enhancements to the T-SQL query language in SQL Server 2005 that augment the
expressive power of the T-SQL query language, and should ensure that they are taking
full advantage of them before writing procedural code, whether in the CLR or not.
Some of these added features include:
• The ability to write recursive queries to traverse recursive hierarchies in
a table
• New analytical functions such as RANK and ROW_NUMBER that allow
ranking rows in a result set
• New relational operators such as EXCEPT, INTERSECT, APPLY, PIVOT and
UNPIVOT
In previous releases of SQL Server, extended stored procedures (XPs) were the only
alternative to T-SQL with which to write server-side code with logic that was difficult to
write in T-SQL. CLR integration provides a more robust alternative to XPs. In addition,
with CLR integration, many stored procedures can be better expressed as table-valued
functions, allowing them to be invoked and manipulated using the query language.
The easiest way to write managed code for SQL Server 2005 is to use Visual
Studio 2005. To write managed code for SQL Server, you must have at least the Team
Server edition of Visual Studio.
For each type of managed code that is supported, there are related attributes that are
used to decorate the code to help SQL Server know about specific behaviors about the
managed code. These attributes include SqlProcedure, SqlFunction,
SqlUserDefinedAggregate, SqlUserDefinedType and SqlMethod. Each of these
attributes is explained below.
Stored Procedures:
The most common — and useful — managed code in your own projects are probably
stored procedures. Creating managed stored procedures have the following three
requirements:
1. The containing class must be public.
2. The exposed method must be public.
3. The exposed method must be static.
4. That is all that is required. For example, to expose a simple stored
procedure:
Notice there is nothing especially different about this method from any other .NET
code. The SqlProcedure attribute marks this code as a stored procedure. The attribute
is not required, but is good form as documentation of what code is used where. It is
also used in Visual Studio to allow for the automatic deployment. The only parameter
that it accepts is the name parameter that will rename the automatically deployed
stored procedure:
public class SqlClr {
[SqlProcedure(Name="spMyProc")]
public static void MyProc() {
// Put your code here
}
}
You can specify in, out, in-out and return parameters as simple .NET parameters and
return types:
// Input Parameter
[SqlParameter]
public static void InputProcedure(int number) {
}
// Output Parameter
[SqlParameter]
public static void OutputProcedure(out int number) {
number = 5;
}
// In/Out Parameter
[SqlParameter]
public static void InOutProcedure(ref int number) {
number = 4;
}
// Return Parameter
[SqlParameter]
public static int ReturnProcedure() {
return 3;
}
Functions
[SqlFunction]
public static int Subtraction(int x, int y) {
return x - y;
}
Managed Triggers
Much like T-SQL, SQL Server 2005 allows you to create triggers in managed code. You
must take special care to understand the performance implications in using managed
triggers, as their performance is likely to be lower than similarly written T-SQL
triggers.
Assuming you have taken the performance considerations into account, you would
write triggers by simply annotating them with the SqlTrigger attribute. The SqlTrigger
attribute requires two parameters:
• Event: The event to fire the trigger for. This syntax is identical to the T-SQL
syntax for the event name (e.g. FOR INSERT, INSTEAD OF DELETE, etc.). In
addition, you can specify event names for DDL triggers (a new SQL Server 2005
feature) by specifying a DDL event name (e.g. FOR CREATE TABLE, FOR DROP
USER, etc.).
• Target: The source of the event. Usually, this is a table or view name for DML
triggers or a database name for DDL triggers.
NOTE: Using the SqlTrigger attribute is broken in the Beta 2 version of Visual Studio.
You can write the triggers, but you must register them manually, and debugging is
impossible at the moment.
In writing a managed trigger, your code may look something like this:
if (ctx.TriggerAction == TriggerAction.Insert) {
string msg = ";
Writing a trigger normally requires that you have some access to the data that was
affected (in this case, the row being inserted). To access that information, SQL Server
supports the SqlTriggerContext object that is used to get information about the trigger.
With the SqlTriggerContext object (which can be retrieved from the SqlContext object),
you can see what the trigger action was, and determine what columns were affected in
the statement that caused the trigger to fire.
Default Supported .Net Framework Libraries
These are the list of supported .NET Framework Libraries, which have been tested to
ensure that they meet reliability and security standards for interaction with SQL Server
2005 in any mode of assembly creation. Supported libraries do not need to be
explicitly registered on the server, but unsupported libraries must first be registered in
SQL Server database using CREATE ASSEMBLY before calling them in managed codes.
• CustomMarshalers
• Microsoft.VisualBasic
• Microsoft.VisualC
• Mscorlib
• System
• System.Configuration
• System.Data
• System.Data.OracleClient
• System.Data.SqlXml
• System.Deployment
• System.Security
• System.Transactions
• System.Web.Services
• System.Xml
The common language runtime (CLR) integration feature is off by default in Microsoft
SQL Server, and must be enabled in order to use objects that are implemented using
CLR integration. To enable CLR integration, use the clr enabled option of the
sp_configure stored procedure as shown:
You can disable CLR integration by setting the clr enabled option to 0. When you
disable CLR integration, SQL Server stops executing all CLR routines and unloads all
application domains.
USEFUL LINKS
http://msdn.microsoft.com/en-us/library/ms255336(VS.80).aspx
http://aspalliance.com/1081_CLR_Integration_in_SQL_Server_2005
http://www.developer.com/net/net/article.php/3548331
http://www.codeguru.com/cpp/data/mfc_database/sqlserver/article.php/c10453
http://www.devsource.com/c/a/Using-VS/Introducing-SQL-Server-2005s-CLR-
Integration/1/
QUESTIONS AND ANSWERS