Date post: | 27-Dec-2015 |
Category: |
Documents |
Upload: | shanon-mcdonald |
View: | 231 times |
Download: | 4 times |
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.
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
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
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
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
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
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, …
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
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
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 }
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)
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
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
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();
}}
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. )
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
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
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);
}}
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
CLR IntegrationCLR IntegrationTriggersTriggers
public class ContactCode {
[SqlTrigger(Name="ContactUpdTrg", Target="Person.Contact", Event="FOR UPDATE")]
public static void ChangeEmail(){SqlTriggerContext trg =
SqlContext.GetTriggerContext();
DEMODEMO
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
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
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
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
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.