Managed code also takes advantage of the programming languages to implement complex programming logic in database objects, such as stored procedures and triggers.. Further, it explains h
Trang 1Managed code runs in the NET CLR SQL Server
2005 integrates CLR to allow execution of managed code within the SQL Server environment This
provides flexibility in writing the database code in
multiple languages supported by NET Managed
code also takes advantage of the programming
languages to implement complex programming logic
in database objects, such as stored procedures and
triggers
This chapter introduces SQLCLR, which is the CLR hosted on the SQL Server Further, it explains how
to implement stored procedures, user-defined
functions, triggers, and user-defined types by using
managed code
In this chapter, you will learn to:
Understand managed code
Create managed database objects
Objectives
Trang 3As a database developer, you create database objects, such as procedures, functions, and triggers, to implement programming logic by using T-SQL However, in some situations
it is not possible to implement the required functionality by using the T-SQL code For example, you need to store the credit card number in a table in an encrypted format so that
it cannot be tampered For this, you need to apply various string manipulations and
mathematical calculations, which involve usage of arrays and constructs It is very
complex to do this using T-SQL code
With CLR integration in SQL Server 2005, you can create programs in any of the
.NET-supported languages to implement enhanced programming logic that cannot be implemented by using T-SQL Code that is written in any of the NET supported
languages and runs in the CLR is called managed code You can embed these programs in your database so that they can run in the same environment in which the database exists
To implement managed code on the database server, it is important for you to know the details of CLR integration with the SQL Server It is also important to identify situations when it is better to implement the managed code than use T-SQL code
Database developers can use T-SQL to write codes in the form of procedures and
functions, but T-SQL is not a complete and comprehensive programming language Unlike other programming languages, T-SQL does not support object-orientation, arrays, collections, for-each loops, or usage of external resources and classes
To implement a programming logic that involves complex operations in the database, SQL Server 2005 is integrated with the NET Framework CLR is an environment that executes codes written in any NET programming language CLR integration allows the database developers to create objects in any of the NET-supported languages and embeds
the objects in the database Such a database object is called a managed database object.
CLR integration provides the following benefits:
Better programming model: The NET programming languages provide a set of
programming constructs that are not available in T-SQL In addition, NET provides
a set of classes that can be used to implement a predefined functionality For example, you need to save the data in a file in a compressed format For this, you can use BinaryStreamReader and Binary StreamWriter classes provided by the NET Framework base class library
Common development environment: Application developers can use the same tool,
Visual Studio 2005, to create the database objects and scripts as they use to create a client-tier
Understanding Managed Code
Introduction to SQL Server CLR Integration
Trang 4 Ability to define data types: Database developers can create user-defined data types
to expand the storage capabilities of the SQL Server For example, you need to store
a set of values in a single column or variable in a pre-defined format For this, you need to use an array In such a case, you can create a new data type using a NET programming language
You can use either managed code or T-SQL to implement the database programming logic However, it is not always required to create managed code to implement a
programming logic It is essential to identify the situations where creating a managed code is a better option
You should use the T-SQL statements when you need to:
Perform data access and manipulation operations that can be done using T-SQL statements
Create database objects, such as procedures, functions, or triggers, requiring basic programming logic that can be implemented by using the programming constructs provided by T-SQL
For example, T-SQL provides efficiency and ease to perform pure database oriented operations, such as joining two result sets In comparison, creating a CLR object to apply
a join involves writing code to join the data rows in one result set with the rows in another result set In such a situation, using T-SQL is a better decision
You should use managed database objects when you need to:
Implement complicated programming logic for which you can reuse the functionality provided by the NET base class libraries
Access external resources, such as calling a Web service or accessing the file system
Implement a CPU-intensive functionality that can run more efficiently as compared
to the managed code
For example, you need to extract data from a database table and store the result set in a file in the XML format You will not be able to implement this functionality by using T-SQL Instead, you can create a managed database object by using a NET language to store the data in an XML file
In addition to all the preceding points, T-SQL is interpreted at the time of execution, and therefore is slow as compared to the managed code However, the managed code is pre-compiled and faster to execute within the CLR
Identifying the Need for Managed Code
Trang 6To create managed database objects in the SQL Server, you need to first create a managed code in any of the NET programming languages A managed code contains classes and methods that provide a desired functionality Next, you need to compile the code to create
an assembly An assembly can be a dll or.exe file that contains compiled managed code SQL Server cannot directly execute the assemblies Therefore, before using the
assemblies, you need to import and configure the assemblies in the database engine Further, you need to create a database object based on the assembly that you imported earlier
You can import a NET assembly, which is a dll or an exe, in SQL Server database engine using the CREATE ASSEMBLY statement The syntax of the CREATE ASSEMBLY
command is:
CREATE ASSEMBLY assembly_name
FROM { <client_assembly_specifier> | <assembly_bits>
EXTERNAL_ACCESS: Enables the NET code to access some external resources, such
as, networks, environmental variables, and the registry
UNSAFE: Enables the NET code to access any resource, within or outside SQL Server
Creating Managed Database Objects
Importing and Configuring Assemblies
Trang 7Note
Just a minute:
Consider an example You have created a managed code and created is assembly as CLRIntegration.dll To create an assembly for this dll, you can write the following code:
CREATE ASSEMBLY CLRIntegration FROM
‘C:\CLRIntegration.dll’ WITH PERMISSION_SET = SAFE
In the preceding code, the database engine imports the CLRIntegration.dll assembly file from the C: drive of the local computer and creates an assembly object named
Which of the following PERMISSION_SET will you use to access another database server?
Trang 8Note
After importing assemblies in SQL Server, you can create managed database objects that use the managed code provided in the assembly By default, the SQL Server does not allow running managed code on the server Therefore, before creating a managed
database object in your database, you need to enable the CLR integration feature in your database To enable CLR, you need to use the following statements:
sp_configure CLR_ENABLED, 1;
GO
RECONFIGURE;
GO
You need to be a member of sysadmin server role to enable CLR
Depending on the requirements, the database developer can create the following types of database objects:
Stored procedures
Functions
Triggers
User-Defined Types
Creating Managed Stored Procedures
Stored procedures are the most common and useful database code blocks With CLR integration you can use managed code to be executed as a stored procedure For this, you need to create a procedure that refers to an imported assembly
To create a managed function using an imported assembly, you can use the CREATE PROCEDURE command, as shown in the following syntax:
CREATE PROCEDURE <Procedure Name>
AS EXTERNAL NAME <Assembly Identifier>.<Type Name>.<Method Name>,
where,
Procedure Name is the name of the procedure you want to create
Assembly Identifier is the name of the imported assembly
Creating Managed Database Objects
Trang 9Type Name is the name of the class that contains the method that will be executed through the procedure
Method Name is the name of the method that will be executed through the procedure For example, the employee data stored in the database needs to be saved in an XML file For this purpose, you need to create a function that will read the data from the table and write it into the XML file For this, you need to create a managed procedure to access an external file
To provide this functionality, you have created the ConvertXML.dll assembly by using the following code:
// Use the pre-defined namespaces to use the functionality provided
//Declare a class name XMLProc to define the functionality
public class XMLProc
{
// Marks that the code will be used as a stored procedure [Microsoft.SqlServer.Server.SqlProcedure]
//Define the function that provides functionality
public static void convXml()
{
/* Create an object of the FileStream class that opens or creates a file named XMLEmployee.xml to write xml data */
FileStream fs = new FileStream("XMLEmployee.xml", FileMode.OpenOrCreate, FileAccess.ReadWrite);
// Creates the object of a StreamWriter class that allows to write on a stream
StreamWriter sw = new StreamWriter(fs);
Trang 10using (SqlConnection connection = new
SqlConnection("context connection=true"))
{
connection.Open();
// Opens the SQL Server connection
SqlCommand cmd = new SqlCommand("SELECT * FROM HumanResources.Employee FOR XML RAW", connection);
// Creates a new SQLCommand SqlDataReader dr;
// Creates a new data reader to read data from the data source
1 Execute the following statement in the Query Editor window of the Microsoft SQL
Server Management Studio window to create an assembly named
ConvertXMLAssembly that will refer to the ConvertXML.dll file:
CREATE ASSEMBLY ConvertXMLAssembly FROM
‘C:\ConvertXML.dll’ WITH PERMISSION_SET = EXTERNAL_ACCESS
2 Create a managed stored procedure by executing the following statement:
CREATE PROCEDURE clrproc AS EXTERNAL NAME
ConvertXMLAssembly.[CLRStoredProcedure.XMLProc].convXml
Trang 11You can execute the following statement to run the managed procedure:
EXEC clrproc
When the procedure clrproc will be executed, it will create a file named
XMLEmployee.xml Next, read data from the Employee table in the HumanResources schema and write all the rows on the file
Creating Managed Functions
To create a managed function using an imported assembly, you can use the CREATE FUNCTION command, as shown in the following syntax:
CREATE FUNCTION <Function Name>
(
<Parameter List>
)
RETURNS <Return Type>
AS EXTERNAL NAME <Assembly Identifier>.<Type Name>.<Method Name>
where,
<function name> is the name of the function
<Parameter List> is the list of the parameters accepted by the funtion
<Return Type> is the type of the value the function is going to return
<Assembly Identifier> is the name of the imported assembly
<Type Name> is the name of the class that contains the method that will be executed through the procedure
<Method Name> is the name of the method that will be executed through the procedure For example, you need a function that accepts Employee ID as an input, checks the rate value for the employee and displays the total monthly salary For this, you have created a dll assembly named CalcSalAssembly.dll, using the following code:
Trang 12// Mark the code as a SQL Function
public static SqlString calcSalary(SqlString emp)
{
SqlConnection connection = new SqlConnection("context connection = true");
SqlString sr = new SqlString();
connection.Open(); // Begins the connection
SqlCommand cmd = new SqlCommand("SELECT distinct
employeeid, [Rate],[PayFrequency] FROM
[AdventureWorks].[HumanResources].[EmployeePayHistory] where ratechangedate <= modifieddate and employeeid = " + emp.ToString(), connection);
// Calculate the monthly salary }
Trang 13In the preceding code, the Pay function defines the functionality that will be used to calculate the salary To create the managed function using the CalcSalAssembly.dll file, you need to perform the following steps:
1 Execute the following statement in the Query Editor window of the Microsoft SQL
Server Management Studio window to create an assembly named
CalcSalAssembly that will refer to the CalcSalAssembly.dll file:
CREATE ASSEMBLY CalcSalAssembly FROM ‘C:\CalcSalAssembly.dll’
WITH PERMISSION_SET = UNSAFE
2 Execute the following statement to create a managed function named
SalaryCalculation from the CalcSalAssembly assembly:
CREATE FUNCTION SalaryCalculation(@EmpID as nVarchar(3))
RETURNS nVarchar(10)
AS EXTERNAL NAME CalcSalAssembly.[EmployeePay.Pay].calcSalary
You can execute the following statement to execute the managed function:
SELECT dbo.SalaryCalculation(‘23’) as TotalSalary
The preceding code displays the monthly salary for the employee with the Employee ID
as 23
Creating Managed Triggers
Managed triggers help in implementing advanced trigger logic that cannot be done using T-SQL You can create a managed user-defined type by using the CREATE TRIGGER command, as shown in the following syntax:
CREATE TRIGGER <TriggerName>
ON <Table or View> <FOR|INSTEAD OF|AFTER>
<INSERT|UPDATE|DELETE>
AS EXTERNAL NAME <Assembly Identifier>.<Type Name>.<Method Name>
where,
<TriggerName> is the name of the trigger
<Table or View> is the name of the table or view on which you want to create the trigger
<FOR|INSTEAD OF|AFTER> <INSERT|UPDATE|DELETE> specifies the type of trigger you want to create
<Assembly Identifier> is the name of the imported assembly
Trang 14<Type Name> is the name of the class that contains the method that will be executed through the procedure
<Method Name> is the name of the method that will be executed through the procedure Consider an example The database in an organization maintains the user details in the UserNameAudit table The table stores various details of the users including the e-mail address When inserting the details of users, you need to validate the e-mail address to ensure that it is a valid e-mail address For this, you have decided to create a trigger that gets executed every time a new row is inserted
To implement the logic of validating the e-mail address, you need to create a managed trigger You have created the ValidateMail.dll assembly using the following code:
using (SqlConnection connection
= new SqlConnection(@"context connection=true"))
{
connection.Open();// Opens the SQL Connection
command = new SqlCommand(@"SELECT * FROM INSERTED;", connection);