Download presentation
Presentation is loading. Please wait.
Published byShanon McDonald Modified over 9 years ago
1
SQL Server 2005 The Common Language Runtime (CLR) Integration Presented by Tarek Ghazali IT Technical Specialist Microsoft SQL Server MVP Web Development MCP LebDev Vice President © 2006 Tarek Ghazali. All rights reserved.
2
CLR Integration CLR Introduction Highlights Highlights –Common type system (CTS) Mapping of data types. Programming language Framework Mapping of data types. Programming language Framework –Just-in-time (JIT) compilers JIT compiles intermediary language (MSIL) into native code JIT compiles intermediary language (MSIL) into native code Highly optimized for platform or device Highly optimized for platform or device –Garbage collector –Permission and policy-based security –Exceptions –Threading –Diagnostics and profiling
3
CLR Integration CLR Diagram Common Language Runtime Diagram Common Language Runtime Diagram Class Loader MSIL to Native Compilers (JIT) Code Manager Garbage Collector (GC) Security EngineDebug EngineType CheckerException ManagerThread SupportCOM Marshaler Base Class Library Support
4
CLR Integration SQL Server 2005 – CLR Run managed code within a database by using in-process assemblies Run managed code within a database by using in-process assemblies Create managed stored procedures, triggers, user-defined functions, user- defined types, and aggregates Create managed stored procedures, triggers, user-defined functions, user- defined types, and aggregates Integration benefits: Integration benefits: –Enhanced programming model –Enhanced safety and security –Common development environment –Performance and scalability
5
CLR Integration Deep Integration with the Database CLR Hosting layer provides coordination CLR Hosting layer provides coordination –Assembly Loading –Memory management –Security Model –Reliability –Threads & Fibers –Deadlock detection –Execution context Windows OS SQL OS Layer SQL Engine HostingLayer CLR
6
VS.NET Project Assembly: “TaxLib.dll” VB,C#,C++ Build SQL Server SQL Data Definition: create assembly … create function … create procedure … create trigger … create type … SQL Queries: select sum(tax(sal,state)) from Emp where county = ‘King’ Runtime hosted by SQL (in-proc) The Developer Experience
7
CLR Integration Available Classes Even in supported assemblies, some APIs are not available in SQL Even in supported assemblies, some APIs are not available in SQL –Environment.Exit(), Console, etc. Potentially unreliable constructs disabled Potentially unreliable constructs disabled –No thread creation –No shared state or synchronization –No listening on sockets in server –No finalizers Eliminate functionality N/A to database Eliminate functionality N/A to database –System.Windows.Forms –System.Drawing –System.Web, …
8
CLR Integration SQL Server Projects in Visual Studio 2005 Project for creating managed database objects Project for creating managed database objects Automatically includes necessary references Automatically includes necessary references –System –System.Data.dll Includes templates for each object type Includes templates for each object type –Stored procedure –Trigger –User-defined function –User-defined type –Aggregate Allows immediate deployment and debugging Allows immediate deployment and debugging
9
CLR Integration The System.Data.SqlServer Namespace ClassDescription SqlContext Provides access to other objects, like a connection SqlConnection An open connection to a SQL Server database SqlCommand Used to send a command to the database server SqlParameter Supplies a parameter for a SqlCommand object SqlPipe Used to send results or information to the client SqlDataReader Reads the data one row at a time, forward only SqlResultSet For working with flexible server-side cursors SqlTransaction For providing transactional behavior SqlTriggerContext Provides information about the trigger action
10
CLR Integration Registering an assembly CREATE ASSEMBLY assembly_name CREATE ASSEMBLY assembly_name –[ AUTHORIZATION owner_name ] –FROM { | [,...n] } –[ WITH PERMISSION_SET = { SAFE | EXTERNAL_ACCESS | UNSAFE } ] – :: = – '[\\machine_name\]share_name\[path\]manifest_file_nam e' – :: = – { varbinary_literal | varbinary_expression } CREATE ASSEMBLY assembly_name CREATE ASSEMBLY assembly_name –[ AUTHORIZATION owner_name ] –FROM { | [,...n] } –[ WITH PERMISSION_SET = { SAFE | EXTERNAL_ACCESS | UNSAFE } ] – :: = – '[\\machine_name\]share_name\[path\]manifest_file_nam e' – :: = – { varbinary_literal | varbinary_expression }
11
CLR Integration Assembly Security -PERMISSION_SET SAFE SAFE –May not access external resources: registry, file system, or network –May access data using the current context but not via SQLClient or any other data provider –No thread processing EXTERNAL_ACCESS EXTERNAL_ACCESS –May access external resources: registry, file system, network, environment variables UNSAFE UNSAFE –May access external resources –Can use SQLClient and other data providers –Can use thread constructs –(No restrictions; similar to extended stored procedures)
12
CLR Integration Meta Data of Assemblies Create Assembly Details of Assembly: Sys.assemblies Assembly source code: Sys.assembly_files Assembly references: Sys.assembly_references Other meta data information SYS.OBJECTS SYS.OBJECTS SYS.ASSEMBLY_MODULES SYS.ASSEMBLY_MODULES SYS.ASSEMBLY_TYPES SYS.ASSEMBLY_TYPES
13
CLR Integration User Defined Functions Similar to T-SQL function Similar to T-SQL function Written in CLR language Written in CLR language –Decorated with [SqlFunction] attribute in code –Assembly loaded into the database –Function defined from assembly Limits on functions Limits on functions –must be in public class –cannot be in nested class –method must be public and static
14
CLR Integration User Defined Functions -Example public class MyFunctions { [SqlFunction] public static SqlString GetLongDate(SqlDateTime DateVal) { // Return the date as a long string return DateVal.Value.ToLongDateString(); }
15
CLR Integration User Defined Functions Properties have impact on whether or not computed column that use these functions can be indexed. Properties have impact on whether or not computed column that use these functions can be indexed. –IsDeterministic = true (it always produces the same output values given the same input values and the same database state.) –DataAccess DataAccessKind.None: Does not access data. DataAccessKind.None: Does not access data. DataAccessKind.Read: Only reads data. DataAccessKind.Read: Only reads data. –SystemDataAccess SystemDataAccessKind.None: Does not access system data. SystemDataAccessKind.None: Does not access system data. SystemDataAccessKind.Read: Only reads system data. SystemDataAccessKind.Read: Only reads system data. –IsPrecise = { true | false } (that indicates whether the routine involves imprecise computations such as floating point operations. )
16
CLR Integration.Net Stored Procedures (1) Capable of doing everything a T-SQL proc can do. Capable of doing everything a T-SQL proc can do. Uses a Shared method (static in C#) Uses a Shared method (static in C#) Pass parameters both ways Pass parameters both ways –OUTPUT parameters should be byref (ref in C#) Return multiple result sets Return multiple result sets
17
CLR Integration.Net Stored Proc Can Return (2) Numeric return code Numeric return code Count of rows affected by the command Count of rows affected by the command Scalar value Scalar value Single row Single row One or more multi row result sets One or more multi row result sets A stream of XML A stream of XML
18
CLR Integration Stored Procedure public class ContactCode { [SqlProcedure] public static void GetContactNames() { SqlCommand cmd = ……. …… cmd.CommandText = "SELECT FirstName + ' ' + LastName" + – –" AS [Name] FROM Person.Contact"; SqlDataReader rdr = cmd.ExecuteReader(); SqlPipe sp = …………..; sp.Send(rdr); }
19
CLR Integration Create Sql Server Proc. Syntax : create procedure ProcName as external name.. as external name.. Example : create procedure GetContactsName as external name assemblyname. create procedure GetContactsName as external name assemblyname.ContactCode. GetContactNames
20
CLR Integration Triggers public class ContactCode { [SqlTrigger(Name="ContactUpdTrg", Target="Person.Contact", Event="FOR UPDATE")] public static void ChangeEmail() {SqlTriggerContext trg = SqlContext.GetTriggerContext();
21
DEMO
22
CLR Integration When to use T-SQL T-SQL better used for data access T-SQL better used for data access –All pre-SQL Server 2005 code is written in T-SQL –SQL Server 2005 adds exception handling to T- SQL T-SQL can be faster for data access T-SQL can be faster for data access –Direct access to SQL Server's internal buffers –Rich, data-centric library of functions –No conversion of types
23
CLR Integration Feature Comparison with T-SQL T-SQLCLR User Defined Functions XX Stored Procedures XX TriggersXX User Defined Types X AggregatesX
24
CLR Integration Best uses of SQLCLR Computational functions are always faster Computational functions are always faster Streaming table valued functions Streaming table valued functions User defined aggregates User defined aggregates –Orders magnitude faster than server or client cursor solutions Scalar functions Scalar functions –Function body is compiled to native code Use managed code for: Use managed code for: –Procedures that feature complex logic –Access to the.NET Framework class library –CPU intensive functions
25
SQLCLR Guidance Mid Tier vs. Data Tier SQLCLR support does not mean move all business logic to server SQLCLR support does not mean move all business logic to server Candidates for moving to server Candidates for moving to server –Centralized data validation –Process large amount of data while needing a small portion of it for application use
26
Resources & Questions Microsoft Resources: Microsoft Resources: –msdn.microsoft.com/sqlserver/ msdn.microsoft.com/sqlserver/ –www.microsoft.com/sql/community www.microsoft.com/sql/community Contact me: Contact me: –tghazali@sqlmvp.com –www.sqlmvp.com (will be available soon) www.sqlmvp.com Download Presentation : Download Presentation : – www.lebdev.net www.lebdev.net Thanks.
Similar presentations
© 2025 SlidePlayer.com. Inc.
All rights reserved.