Tải bản đầy đủ - 0 (trang)
Chapter 12. SQL Server CLR Integration

Chapter 12. SQL Server CLR Integration

Tải bản đầy đủ - 0trang

hostedCLRisreferredtoasaCLRroutine.

PriortoSQLServer2005,themainwaythatSQLServerwas

extendedwasusingextendedstoredproceduresthatletyou

createexternalroutinesusingprogramminglanguagessuchas

C.Extendedstoredproceduresareusedlikeregularstored

procedures,however,theycanhaveperformanceproblems

suchasmemoryleaksandcancausetheservertobecome

unreliable.CLRintegrationletsyouextendSQLServerwiththe

safetyandreliabilityofT-SQLandwiththeflexibilityof

extendedstoredprocedures.

Managedcodeusescodeaccesssecurity(CAS)tocontrolwhat

operationsassembliescanperform.CASsecuresthecode

runningwithinSQLServerandpreventsthecodefrom

adverselyaffectingtheoperatingsystemorthedatabase

server.Generally,youshoulduseT-SQLwhenthecodeinthe

routinesprimarilyperformsdataaccess.CLRroutinesarebest

forCPU-intensivecalculationsandforsupportingcomplexlogic

thatwouldotherwisebedifficulttoimplementusingT-SQL.The

componentsneededtodevelopCLRroutinesareinstalledwith

SQLServer2005andlater.

AlthoughtheseversionsofSQLServershipwiththe.NET

FrameworkandcommandlinecompilersforC#andVB.NET,as

wellasBusinessIntelligenceStudiothatletsyoubuildAnalysis

ServicesandReportingServicesprojectsusingthesameIDEas

VisualStudio,youneedtoinstallVisualStudio2005orlaterto

createandcompileCLRroutinesusingtheVisualStudioIDE.

CLRintegrationisturnedoffbydefault.Usethesp_configure

systemstoredproceduretoenableCLRintegration,asshown

here:











sp_configure'clrenabled',1

GO

RECONFIGURE

GO



Theclrenabledserverconfigurationoptionspecifieswhether

.NETassembliescanberunbySQLServer(0=donotallow;1

=allow).Thechangetakeseffectimmediatelyafter

sp_configureandRECONFIGUREareexecuted—theserverdoes

notneedtoberestarted.YouneedALTERSETTINGS

permissionsattheserverleveltoenableCLRintegration.

Alternatively,youcanusetheSQLServerSurfaceArea

ConfigurationtooltocontrolwhetherCLRintegrationisenabled.

SQLServerCLRintegrationletsyoubuilddatabaseobjects

using.NETlanguages.Oncea.NETFrameworkassemblyis

registeredwithSQLServer,youcancreateCLRroutinesthat

canbeusedanywhereaT-SQLequivalentroutinecanbeused.

Table12-1describesthetypesofCLRroutinesyoucanbuild.

Thesolutionsinthischaptershowyouhowtobuildeachof

thesetypesofSQLServerCLRroutines.

Table12-1.TypesofCLRroutines

Database .NET

Description

object

Framework

assembly

type

Scalarvalued

function



Publicstatic AUDFthatreturnsasinglevalue.

method



Tablevalued

function



Publicstatic AUDFthatreturnsatableasthe

method

resultset.



Stored

Publicstatic Aroutinethatreturnstabularresult

procedure method

setsandmessagestotheclient,

invokesDDLandDMLstatements,

andreturnsoutputparameters.

Userdefined



Classor

structure



AUDAfunctionthatoperateson

valuesinasetofrowsandreturnsa



aggregate

function

Userdefined

type



scalar.

Classor

structure



Complexdatatypescompletewith

methodsthatextendthescalartype

systeminSQLServer.



Triggers

Publicstatic Atypeofstoredprocedurethat

(DMLand method

automaticallyrunswhenaDMLor

DDL)

DDLeventoccurs.



SQLServer2005introducednewT-SQLstatementstocreate

andmanage.NETassembliesandUDTs,andenhancesotherTSQLstatementstocreateandmanagefunctions,stored

procedures,triggers,andUDAfunctionscreatedfromCLR

assemblies.ThesestatementsarebrieflydescribedinTable122.

Table12-2.NewandchangedT-SQLstatementsto

supportCLRintegration

Scope



DDL

statement



New.NET Description

T-SQL

statement



.NET

CREATE

Framework ASSEMBLY

assembly



Yes



LoadsassemblyintoSQL

Server.



ALTER

ASSEMBLY



Yes



Changesaloaded

assembly.



DROP

ASSEMBLY



Yes



Unloadsanassembly

fromSQLServer.



Userdefined

aggregate

function



CREATE

Yes

AGGREGATE



CreatesaUDAfunction

inaSQLServer

databasefromaUDA

functionimplementedas



aclassina.NET

Frameworkassembly.



Userdefined

type



Stored

procedure



DROP

Yes

AGGREGATE



Theassemblycontaining

theclassmustfirstbe

registeredinSQLServer

withtheCREATE

ASSEMBLYT-SQL

statement.



CREATE

TYPE



No



CreatesaUDTinaSQL

Serverdatabasefroma

typeimplementedasa

classorstructureina

.NETFramework

assembly.Theassembly

containingtheclassor

structuremustfirstbe

registeredinSQLServer

withtheCREATE

ASSEMBLYT-SQL

statement.



DROPTYPE



No



RemovesaUDTfroma

SQLServerdatabase.



CREATE

No

PROCEDURE



Createsastored

procedureinaSQL

Serverdatabasefroma

CLRstoredprocedure

implementedasa

methodina.NET

Frameworkassembly.

Theassemblycontaining

themethodmustfirstbe

registeredinSQLServer

withtheCREATE

ASSEMBLYT-SQL



statement.



Userdefined

function

(scalarvaluedor

tablevalued)



Trigger



ALTER

No

PROCEDURE



Changesastored

procedurepreviously

createdwiththeCREATE

PROCEDURET-SQL

statement.



DROP

No

PROCEDURE



Removesastored

procedurefromaSQL

Serverdatabase.



CREATE

FUNCTION



No



CreatesaUDFinaSQL

Serverdatabasefroma

CLRUDFimplemented

asamethodina.NET

Frameworkassembly.

Theassemblycontaining

themethodmustfirstbe

registeredinSQLServer

withtheCREATE

ASSEMBLYT-SQL

statement.



ALTER

FUNCTION



No



ChangesaUDF

previouslycreatedwith

theCREATEFUNCTIONTSQLstatement.



DROP

FUNCTION



No



RemovesaUDFfroma

SQLServerdatabase.



CREATE

TRIGGER



No



CreatesaDMLorDDL

triggerinaSQLServer

databasefromaCLR

triggerimplementedasa

methodina.NET

Frameworkassembly.



Theassemblycontaining

themethodmustfirstbe

registeredinSQLServer

withtheCREATE

ASSEMBLYT-SQL

statement.

ALTER

TRIGGER



No



Changesatrigger

previouslycreatedwith

theCREATETRIGGERTSQLstatement.



DROP

TRIGGER



No



Removesatriggerfrom

aSQLServerdatabase.



FormoreinformationaboutassemblyorCLRroutine

management,seeSQLServerBooksOnline.



12.1.1.ADO.NETIn-ProcessExtensions

SupportingCLRProgramming

ADO.NEThasfourmainin-processfunctionalextensionsthat

areusedwhenprogramming.NETFrameworkroutines.The

SqlContextobjectprovidesaccesstocon-textinformation,toa

SqlPipeobjectforsendingresultstotheclient,andtoa

SqlTriggerContextobjectthatprovidesinformationaboutthe

operationthatcausedatriggertofire.Thefourth—the

SqlDataRecordobject—returnstothecalleracustomresultset

fromastoredprocedure.Thesefourextensionsarediscussedin

thefollowingsubsections.



12.1.1.1.SqlContextobject

ManagedcodeisinvokedintheserverwheneveraCLRroutine

isexecuted.Coderunningontheserverexecutesinthecontext

ofthecallerconnection,sotheCLRcodeneedsaccesstothe



callercontext.TheSqlContextclassintheMicrosoft.

SqlServer.Servernamespaceabstractsthecontextofthe

callerandprovidesaccesstothecontextcomponentsthrough

itspublicstaticproperties,describedinTable12-3.

Table12-3.SqlContextpublicproperties

Property



Returntype



Description



IsAvailable



bool



Indicateswhethertheco

executingisrunninginsi

SQLServer.If

membersofSqlContext

beaccessed.If

otherpropertieswillthro

InvalidOperationExcep

whenaccessed,andany

attemptstoopena

connectionusingthecon

connection=true

intheconnectionstring



Pipe



SqlPipe



Apathformessagesand

resultsetstoflowtothe

client.



TriggerContext



SqlTriggerContext



Providesaccessto

informationaboutthe

operationthatcauseda

orDDLtriggertofire.Al

providesamapofthe

updatedcolumns.Youca

retrieveTriggerContext

onlywithinaCLRtrigger



WindowsIdentity System.Security.

Providesaccesstoan

Principal.WindowsIdentity impersonationtoken

representingtheWindow

identityofthecallerifth



clientthatinitiatedexecu

ofthestoredprocedure

functionconnectedtoSQ

Serverusingintegrated

authentication.

returnedifthecallerwas

authenticatedusingSQL

Serverauthenticationan

thecodecannotimperso

thecaller.



TheSQLServerprocess

accountisthecontextfo

CLRcodeinvokedinside

SQLServer.The

impersonationtokenisu

toletthecodeperform

actionsusingtheidentity

thecallerinsteadofthe

identityoftheprocess

account.



Onlyassembliesmarked

EXTERNAL_ACCESS

permissioncanaccessth

WindowsIdentity



Youobtainanin-processconnectionusingthenewconnection

contextconnectionstringkeyword.Forexample:





SqlConnectionconn=newSqlConnection("contextconnect



12.1.1.2.SqlPipeobject

UsetheSqlPipeobjecttosendmessagesandresultsetsfrom



aCLRstoredproceduretothecallingclient.TheSqlPipeobject

cannotbedirectlyinstantiated.YouobtaintheSqlPipeobject

usingthePipepropertyoftheSqlContextobjectwithinthe

bodyofaCLRroutine.TheSqlPipeclasshasthepublic

propertiesandmethodsdescribedinTable12-4.

Table12-4.SqlPipepublicpropertyandmethods

Property



Description



IsSendingResults



Indicateswhetherthepipeisinthe

processofsendingaresultset,blocking

itfromuse.



Method

ExecuteAndSend() Executesacommandspecifiedasa

SqlCommandobjectargument.Theresults

aresentdirectlybacktotheclient.

Send()



Threeoverloadssendoneofthefollowing

totheclient:

string(informationalmessage—

equivalenttoT-SQLPRINT

statement)

SqlDataRecordobject(single-row

resultset)

SqlDataReaderobject(multiple-row

resultset)



SendResultsEnd() Markstheendofacustomresultset

fromastoredprocedureinitiatedbythe

SendResultsStart()method.Setsthe

SqlPipeobjectbacktoastatewhere

othermethodscanbecalledonit.This

methodcanbecalledonlyafter



SendResultsStart()iscalled.

SendResultsRow() Sendsarowofdatacontainedina

SqlDataRecordobjecttotheclient.This

methodcanbecalledonlyafter

SendResultsStart()iscalled.Eachrow

mustconformtotheSqlDataRecord

argumentdescribingtherowthatis

suppliedtotheSendResultsStart()

method.

SendResultsStart( Marksthestartofacustomresultset

)

fromastoredprocedure.Thismethod

takesaSqlDataRecordargumentto

constructthemetadatathatdescribes

theresultset.Allrowsintheresultset

subsequentlysenttotheclientusingthe

SendResultsRow()methodmust

conformtothismetadata.



12.1.1.3.SqlTriggerContextobject

TheSqlTriggerContextclassprovidescontextinformation

abouttheCLRDMLorDDLtrigger.TheSqlTriggerContext

objectcannotbedirectlyinstantiated.Youobtainthe

SqlTriggerobjectusingtheTriggerContextpropertyofthe

SqlContextobjectwithinthebodyofaCLRtrigger.The

SqlTriggerContextclasshasthepublicpropertiesand

methodsdescribedinTable12-5.

Table12-5.SqlTriggerContextpublicpropertiesand

method

Property



Description



ColumnCount



Thenumberofcolumnspotentially

affectedbytheUPDATEoperationthat



causedtheDMLtriggertofire.

EventData



ASqlXmlobjectcontainingXMLdescribing

thetriggeringoperationforaDDLtrigger.



TriggerAction



Thetypeofactionthatcausedthetrigger

tofire.ThisisoneoftheTriggerAction

enumerationvalues.



Method

IsUpdatedColumn( Indicateswhetheracolumnspecifiedby

)

itsordinalwasmodifiedbytheUPDATE

operationthatcausedtheDMLtriggerto

fire.



12.1.1.4.SqlDataRecordobject

TheSqlDataRecordclassrepresentsasinglerowofdata

togetherwithitsmetadata.Theclassallowsstoredprocedures

toreturncustomresultsetstotheclientusingtheSend()or

SendResultsRow()methodsoftheSqlPipeobject.

YouinstantiateaSqlDataRecordobjectbypassingtothe

constructoraSqlMetaDataobjectarraythatcontainsan

elementofmetadataforeachcolumnintherow.Each

SqlMetaDataobjectdefinesacolumnname,columntype,and

possiblyothercolumnattributes.Forexample,thefollowing

codedefinesaSqlDataRecordcontainingtwocolumns:











SqlMetaData[]md=newSqlMetaData[2];

md[0]=newSqlMetaData("intCol",SqlDbType.Int);

md[1]=newSqlMetaData("stringCol",SqlDbType.NVarChar

SqlDataRecordrow=newSqlDataRecord(md);



TheSqlDataRecordclasshasaccessormethodsthatletyouget



Tài liệu bạn tìm kiếm đã sẵn sàng tải về

Chapter 12. SQL Server CLR Integration

Tải bản đầy đủ ngay(0 tr)

×