+ All Categories
Home > Documents > SQL Server 2005 The Common Language Runtime (CLR) Integration Presented by Tarek Ghazali IT...

SQL Server 2005 The Common Language Runtime (CLR) Integration Presented by Tarek Ghazali IT...

Date post: 27-Dec-2015
Category:
Upload: shanon-mcdonald
View: 231 times
Download: 4 times
Share this document with a friend
26
SQL Server 2005 SQL Server 2005 The Common Language Runtime (CLR) The Common Language Runtime (CLR) Integration Integration Presented by Tarek Ghazali IT Technical Specialist IT Technical Specialist Microsoft SQL Server MVP Web Development MCP Web Development MCP LebDev Vice President © 2006 Tarek Ghazali. All rights reserved.
Transcript
Page 1: SQL Server 2005 The Common Language Runtime (CLR) Integration Presented by Tarek Ghazali IT Technical Specialist Microsoft SQL Server MVP Web Development.

SQL Server 2005SQL Server 2005 The Common Language Runtime (CLR) The Common Language Runtime (CLR) IntegrationIntegration

Presented by Tarek GhazaliIT Technical SpecialistIT Technical SpecialistMicrosoft SQL Server MVPWeb Development MCPWeb Development MCPLebDev Vice President

© 2006 Tarek Ghazali. All rights reserved.

Page 2: SQL Server 2005 The Common Language Runtime (CLR) Integration Presented by Tarek Ghazali IT Technical Specialist Microsoft SQL Server MVP Web Development.

CLR IntegrationCLR IntegrationCLR IntroductionCLR Introduction

HighlightsHighlights– Common type system (CTS)Common type system (CTS)

Mapping of data types. Programming language Mapping of data types. Programming language FrameworkFramework

– Just-in-time (JIT) compilersJust-in-time (JIT) compilers JIT compiles intermediary language (MSIL) into native JIT compiles intermediary language (MSIL) into native

codecode Highly optimized for platform or deviceHighly optimized for platform or device

– Garbage collectorGarbage collector– Permission and policy-based securityPermission and policy-based security– ExceptionsExceptions– ThreadingThreading– Diagnostics and profilingDiagnostics and profiling

Page 3: SQL Server 2005 The Common Language Runtime (CLR) Integration Presented by Tarek Ghazali IT Technical Specialist Microsoft SQL Server MVP Web Development.

CLR IntegrationCLR IntegrationCLR DiagramCLR Diagram

Common Language Runtime Common Language Runtime DiagramDiagram

Class Loader

MSIL to NativeCompilers (JIT)

CodeManager

GarbageCollector (GC)

Security Engine Debug Engine

Type Checker Exception Manager

Thread Support COM Marshaler

Base Class Library Support

Page 4: SQL Server 2005 The Common Language Runtime (CLR) Integration Presented by Tarek Ghazali IT Technical Specialist Microsoft SQL Server MVP Web Development.

CLR IntegrationCLR IntegrationSQL Server 2005 – CLR SQL Server 2005 – CLR Run managed code within a database Run managed code within a database

by using in-process assembliesby using in-process assemblies Create managed stored procedures, Create managed stored procedures,

triggers, user-defined functions, user-triggers, user-defined functions, user-defined types, and aggregatesdefined types, and aggregates

Integration benefits:Integration benefits:– Enhanced programming modelEnhanced programming model– Enhanced safety and securityEnhanced safety and security– Common development environmentCommon development environment– Performance and scalabilityPerformance and scalability

Page 5: SQL Server 2005 The Common Language Runtime (CLR) Integration Presented by Tarek Ghazali IT Technical Specialist Microsoft SQL Server MVP Web Development.

CLR IntegrationCLR IntegrationDeep Integration with the Deep Integration with the DatabaseDatabase

CLR Hosting layer CLR Hosting layer provides coordinationprovides coordination– Assembly LoadingAssembly Loading– Memory managementMemory management– Security ModelSecurity Model– ReliabilityReliability– Threads & FibersThreads & Fibers– Deadlock detectionDeadlock detection– Execution contextExecution context

Windows OSWindows OS

SQL OS LayerSQL OS Layer

SQL EngineSQL Engine

HostingHostingLayerLayer

CLRCLR

Page 6: SQL Server 2005 The Common Language Runtime (CLR) Integration Presented by Tarek Ghazali IT Technical Specialist Microsoft SQL Server MVP Web Development.

VS .NET VS .NET ProjectProject

Assembly: “TaxLib.dll”

VB,C#,C++VB,C#,C++ BuildBuild

SQL ServerSQL Server

SQL Data Definition: SQL Data Definition: create create assembly … assembly … create function … create function … create create procedure … procedure … create trigger … create trigger … create create type …type …

SQL Queries: SQL Queries: select select sum(sum(tax(sal,state)tax(sal,state)) ) from Emp where county from Emp where county = ‘King’= ‘King’

Runtime hosted by SQL

(in-proc)

The Developer The Developer ExperienceExperience

Page 7: SQL Server 2005 The Common Language Runtime (CLR) Integration Presented by Tarek Ghazali IT Technical Specialist Microsoft SQL Server MVP Web Development.

CLR IntegrationCLR IntegrationAvailable ClassesAvailable Classes Even in supported assemblies, some APIs are Even in supported assemblies, some APIs are

not available in SQLnot available in SQL– Environment.Exit(), Console, etc.Environment.Exit(), Console, etc.

Potentially unreliable constructs disabled Potentially unreliable constructs disabled – No thread creationNo thread creation– No shared state or synchronizationNo shared state or synchronization– No listening on sockets in serverNo listening on sockets in server– No finalizersNo finalizers

Eliminate functionality N/A to databaseEliminate functionality N/A to database– System.Windows.FormsSystem.Windows.Forms– System.DrawingSystem.Drawing– System.Web, …System.Web, …

Page 8: SQL Server 2005 The Common Language Runtime (CLR) Integration Presented by Tarek Ghazali IT Technical Specialist Microsoft SQL Server MVP Web Development.

CLR IntegrationCLR IntegrationSQL Server Projects in Visual Studio SQL Server Projects in Visual Studio 20052005 Project for creating managed database objectsProject for creating managed database objects Automatically includes necessary referencesAutomatically includes necessary references

– SystemSystem– System.Data.dllSystem.Data.dll

Includes templates for each object typeIncludes templates for each object type– Stored procedureStored procedure– TriggerTrigger– User-defined functionUser-defined function– User-defined typeUser-defined type– AggregateAggregate

Allows immediate deployment and debuggingAllows immediate deployment and debugging

Page 9: SQL Server 2005 The Common Language Runtime (CLR) Integration Presented by Tarek Ghazali IT Technical Specialist Microsoft SQL Server MVP Web Development.

CLR IntegrationCLR IntegrationThe System.Data.SqlServer The System.Data.SqlServer NamespaceNamespace

ClassClass DescriptionDescription

SqlContext Provides access to other objects, like a Provides access to other objects, like a connectionconnection

SqlConnection An open connection to a SQL Server An open connection to a SQL Server databasedatabase

SqlCommand Used to send a command to the database Used to send a command to the database serverserver

SqlParameter Supplies a parameter for a SqlCommand Supplies a parameter for a SqlCommand objectobject

SqlPipe Used to send results or information to the Used to send results or information to the clientclient

SqlDataReader Reads the data one row at a time, forward Reads the data one row at a time, forward onlyonly

SqlResultSet For working with flexible server-side cursorsFor working with flexible server-side cursors

SqlTransaction For providing transactional behaviorFor providing transactional behavior

SqlTriggerContext

Provides information about the trigger Provides information about the trigger actionaction

Page 10: SQL Server 2005 The Common Language Runtime (CLR) Integration Presented by Tarek Ghazali IT Technical Specialist Microsoft SQL Server MVP Web Development.

CLR IntegrationCLR IntegrationRegistering an assemblyRegistering an assembly CREATE ASSEMBLY assembly_nameCREATE ASSEMBLY assembly_name

– [ AUTHORIZATION owner_name ][ AUTHORIZATION owner_name ]– FROM { < client_assembly_specifier > | < FROM { < client_assembly_specifier > | <

assembly_bits > [,...n] }assembly_bits > [,...n] }– [ WITH PERMISSION_SET = { SAFE | [ WITH PERMISSION_SET = { SAFE |

EXTERNAL_ACCESS | UNSAFE } ]EXTERNAL_ACCESS | UNSAFE } ]– < client_assembly_specifier > :: =< client_assembly_specifier > :: =– '[\\machine_name\]share_name\'[\\machine_name\]share_name\

[path\]manifest_file_name'[path\]manifest_file_name'– < assembly_bits > :: =< assembly_bits > :: =– { varbinary_literal | varbinary_expression }{ varbinary_literal | varbinary_expression }

CREATE ASSEMBLY assembly_nameCREATE ASSEMBLY assembly_name– [ AUTHORIZATION owner_name ][ AUTHORIZATION owner_name ]– FROM { < client_assembly_specifier > | < FROM { < client_assembly_specifier > | <

assembly_bits > [,...n] }assembly_bits > [,...n] }– [ WITH PERMISSION_SET = { SAFE | [ WITH PERMISSION_SET = { SAFE |

EXTERNAL_ACCESS | UNSAFE } ]EXTERNAL_ACCESS | UNSAFE } ]– < client_assembly_specifier > :: =< client_assembly_specifier > :: =– '[\\machine_name\]share_name\'[\\machine_name\]share_name\

[path\]manifest_file_name'[path\]manifest_file_name'– < assembly_bits > :: =< assembly_bits > :: =– { varbinary_literal | varbinary_expression }{ varbinary_literal | varbinary_expression }

Page 11: SQL Server 2005 The Common Language Runtime (CLR) Integration Presented by Tarek Ghazali IT Technical Specialist Microsoft SQL Server MVP Web Development.

CLR IntegrationCLR IntegrationAssembly Security -Assembly Security -PERMISSION_SETPERMISSION_SET SAFESAFE

– May not access external resources: registry, file system, or May not access external resources: registry, file system, or networknetwork

– May access data using the current context but not via SQLClient May access data using the current context but not via SQLClient or any other data provideror any other data provider

– No thread processingNo thread processing

EXTERNAL_ACCESSEXTERNAL_ACCESS– May access external resources:May access external resources:

registry, file system, network, environment variablesregistry, file system, network, environment variables

UNSAFEUNSAFE– May access external resourcesMay access external resources– Can use SQLClient and other data providersCan use SQLClient and other data providers– Can use thread constructsCan use thread constructs– (No restrictions; similar to extended stored procedures)(No restrictions; similar to extended stored procedures)

Page 12: SQL Server 2005 The Common Language Runtime (CLR) Integration Presented by Tarek Ghazali IT Technical Specialist Microsoft SQL Server MVP Web Development.

CLR IntegrationCLR Integration Meta Data of AssembliesMeta Data of Assemblies

Cre

ate

Ass

embl

yDetails of Assembly:

Sys.assembliesAssembly source code:

Sys.assembly_filesAssembly references:

Sys.assembly_references

Other meta data information•SYS.OBJECTSSYS.OBJECTS•SYS.ASSEMBLY_MODULESSYS.ASSEMBLY_MODULES•SYS.ASSEMBLY_TYPESSYS.ASSEMBLY_TYPES

Page 13: SQL Server 2005 The Common Language Runtime (CLR) Integration Presented by Tarek Ghazali IT Technical Specialist Microsoft SQL Server MVP Web Development.

CLR IntegrationCLR IntegrationUser Defined FunctionsUser Defined Functions

Similar to T-SQL functionSimilar to T-SQL function Written in CLR languageWritten in CLR language

– Decorated with [SqlFunction] attribute in Decorated with [SqlFunction] attribute in codecode

– Assembly loaded into the databaseAssembly loaded into the database– Function defined from assemblyFunction defined from assembly

Limits on functionsLimits on functions– must be in public classmust be in public class– cannot be in nested classcannot be in nested class– method must be public and staticmethod must be public and static

Page 14: SQL Server 2005 The Common Language Runtime (CLR) Integration Presented by Tarek Ghazali IT Technical Specialist Microsoft SQL Server MVP Web Development.

CLR IntegrationCLR Integration User Defined Functions -ExampleUser Defined Functions -Example

public class MyFunctions {

[SqlFunction]public static SqlString

GetLongDate(SqlDateTime DateVal){

// Return the date as a long stringreturn DateVal.Value.ToLongDateString();

}}

Page 15: SQL Server 2005 The Common Language Runtime (CLR) Integration Presented by Tarek Ghazali IT Technical Specialist Microsoft SQL Server MVP Web Development.

CLR IntegrationCLR IntegrationUser Defined FunctionsUser Defined Functions Properties have impact on whether or not computed Properties have impact on whether or not computed

column that use these functions can be indexed.column that use these functions can be indexed.– IsDeterministic = true IsDeterministic = true (it always produces the same output values given the same (it always produces the same output values given the same

input values and the same database state.)input values and the same database state.)– DataAccessDataAccess

DataAccessKind.None: Does not access data.DataAccessKind.None: Does not access data. DataAccessKind.Read: Only reads data.DataAccessKind.Read: Only reads data.

– SystemDataAccess 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 } IsPrecise = { true | false } (that indicates whether the routine involves imprecise (that indicates whether the routine involves imprecise

computations such as floating point operations. )computations such as floating point operations. )

Page 16: SQL Server 2005 The Common Language Runtime (CLR) Integration Presented by Tarek Ghazali IT Technical Specialist Microsoft SQL Server MVP Web Development.

CLR IntegrationCLR Integration.Net Stored Procedures (1).Net Stored Procedures (1)

Capable of doing everything a T-Capable of doing everything a T-SQL proc can do.SQL proc can do.

Uses a Shared method (static in Uses a Shared method (static in C#)C#)

Pass parameters both waysPass parameters both ways– OUTPUT parameters should be byref OUTPUT parameters should be byref

(ref in C#)(ref in C#) Return multiple result setsReturn multiple result sets

Page 17: SQL Server 2005 The Common Language Runtime (CLR) Integration Presented by Tarek Ghazali IT Technical Specialist Microsoft SQL Server MVP Web Development.

CLR IntegrationCLR Integration.Net Stored Proc Can Return (2).Net Stored Proc Can Return (2)

Numeric return codeNumeric return code Count of rows affected by the Count of rows affected by the

commandcommand Scalar valueScalar value Single rowSingle row One or more multi row result setsOne or more multi row result sets A stream of XMLA stream of XML

Page 18: SQL Server 2005 The Common Language Runtime (CLR) Integration Presented by Tarek Ghazali IT Technical Specialist Microsoft SQL Server MVP Web Development.

CLR IntegrationCLR IntegrationStored ProcedureStored Procedurepublic 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);

}}

Page 19: SQL Server 2005 The Common Language Runtime (CLR) Integration Presented by Tarek Ghazali IT Technical Specialist Microsoft SQL Server MVP Web Development.

CLR IntegrationCLR IntegrationCreate Sql Server Proc.Create Sql Server Proc.

Syntax :Syntax :create procedure ProcNamecreate procedure ProcNameas external name as external name

<assemblyname>.<classname>.<met<assemblyname>.<classname>.<methodname>hodname>

Example :Example :create procedure GetContactsName as create procedure GetContactsName as

external name external name assemblyname.assemblyname.ContactCode. GetContactNames

Page 20: SQL Server 2005 The Common Language Runtime (CLR) Integration Presented by Tarek Ghazali IT Technical Specialist Microsoft SQL Server MVP Web Development.

CLR IntegrationCLR IntegrationTriggersTriggers

public class ContactCode {

[SqlTrigger(Name="ContactUpdTrg", Target="Person.Contact", Event="FOR UPDATE")]

public static void ChangeEmail(){SqlTriggerContext trg =

SqlContext.GetTriggerContext();

Page 21: SQL Server 2005 The Common Language Runtime (CLR) Integration Presented by Tarek Ghazali IT Technical Specialist Microsoft SQL Server MVP Web Development.

DEMODEMO

Page 22: SQL Server 2005 The Common Language Runtime (CLR) Integration Presented by Tarek Ghazali IT Technical Specialist Microsoft SQL Server MVP Web Development.

CLR IntegrationCLR IntegrationWhen to use T-SQLWhen to use T-SQL

T-SQL better used for data accessT-SQL better used for data access– All pre-SQL Server 2005 code is written in T-All pre-SQL Server 2005 code is written in T-

SQLSQL– SQL Server 2005 adds exception handling SQL Server 2005 adds exception handling

to T-SQLto T-SQL T-SQL can be faster for data accessT-SQL can be faster for data access

– Direct access to SQL Server's internal Direct access to SQL Server's internal buffersbuffers

– Rich, data-centric library of functionsRich, data-centric library of functions– No conversion of typesNo conversion of types

Page 23: SQL Server 2005 The Common Language Runtime (CLR) Integration Presented by Tarek Ghazali IT Technical Specialist Microsoft SQL Server MVP Web Development.

CLR IntegrationCLR IntegrationFeature Comparison with T-Feature Comparison with T-SQLSQL

T-SQLT-SQL CLRCLR

User User Defined Defined FunctionsFunctions

XX XX

Stored Stored ProceduresProcedures

XX XX

TriggersTriggers XX XX

User User Defined Defined TypesTypes

XX

AggregatesAggregates XX

Page 24: SQL Server 2005 The Common Language Runtime (CLR) Integration Presented by Tarek Ghazali IT Technical Specialist Microsoft SQL Server MVP Web Development.

CLR IntegrationCLR Integration Best uses of SQLCLRBest uses of SQLCLR Computational functions are always fasterComputational functions are always faster Streaming table valued functionsStreaming table valued functions User defined aggregatesUser defined aggregates

– Orders magnitude faster than server or client Orders magnitude faster than server or client cursor solutionscursor solutions

Scalar functionsScalar functions– Function body is compiled to native codeFunction body is compiled to native code

Use managed code for:Use managed code for:– Procedures that feature complex logicProcedures that feature complex logic– Access to the .NET Framework class libraryAccess to the .NET Framework class library– CPU intensive functions CPU intensive functions

Page 25: SQL Server 2005 The Common Language Runtime (CLR) Integration Presented by Tarek Ghazali IT Technical Specialist Microsoft SQL Server MVP Web Development.

SQLCLR GuidanceSQLCLR GuidanceMid Tier vs. Data TierMid Tier vs. Data Tier

SQLCLR support does not mean SQLCLR support does not mean move all business logic to servermove all business logic to server

Candidates for moving to serverCandidates for moving to server– Centralized data validationCentralized data validation– Process large amount of data while Process large amount of data while

needing a small portion of it for needing a small portion of it for application useapplication use

Page 26: SQL Server 2005 The Common Language Runtime (CLR) Integration Presented by Tarek Ghazali IT Technical Specialist Microsoft SQL Server MVP Web Development.

Resources & QuestionsResources & Questions

Microsoft Resources:Microsoft Resources:– msdn.microsoft.com/sqlservermsdn.microsoft.com/sqlserver//– www.microsoft.com/sql/communitywww.microsoft.com/sql/community

Contact me: Contact me: – [email protected]@sqlmvp.com– www.sqlmvp.comwww.sqlmvp.com (will be available (will be available

soon)soon) Download Presentation :Download Presentation :

– www.lebdev.netwww.lebdev.netThanks.


Recommended