Tải bản đầy đủ - 0 (trang)
Chapter 13. Managing SQL Server CLR Executables

Chapter 13. Managing SQL Server CLR Executables

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

Introduction

SQLServerCLRexecutablesareprobablythemostwidely

anticipatedandpossiblythemostwidelymisunderstoodofthe

newVisualStudioandSQLServer2005features.Overthelast

fewyears(longbeforethefinalreleaseofSQLServer2005),

everydeveloperonthissideofthegalaxywasexposedto

magazinearticles,technicalconferencesessions,andstreet

performersthatdetailedhowthe.NETFramework'sCommon

LanguageRuntime(CLR)wastobeincorporatedintoSQL

Server.Asthesessionsextolled,forthefirsttime,stored

procedures,triggers,functions,user-defineddatatypes,and

aggregatescouldbewritteninanon-T-SQLlanguage.Based

solelyontheenthusiasmofthepresenters,somedevelopers

leftthesessionsearlysothattheycouldgetbackhometorip

outalloftheirexistingstoredproceduresandreplacethemwith

C#code.Weallhavebeencleaningupthemesseversince.

Onamoreconservativenote,Iwrotemyshareofthiscontent

inanattempttoreturnsanitytothesepresentationsand

portraythenewCLRcodingfeatureinamorerealistic,downto-earthlight.Itseemsthatothers(andtoomanyfrom

Microsoft)couldnotdampentheirunbridledenthusiasmfor

storedprocedureswritteninC#orVisualBasic.NET.Those

leavingtheseMicrosoftsessionswerestillconvincedthis

technologycouldsolvealloftheworld'sproblems,including

globalwarmingandthewarintheMideastbasedonthecurrent

stateoftheplanet,Idon'tthinkit'sworking.

AsI'mabouttodemonstrate,CLRexecutablescan'tlower

oceanlevelsandtheyaren'tagoodsubstituteforyourrun-ofthemillstoredproceduresandT-SQLfunctions.Thischapter

tellsyouwhy.Don'tgetmewrongthereareexcellentreasonsto

leveragethepowerandperformanceofthe.NETFramework

andCLRexecutables,butyou'llfindthatnotallsituationscall

forthem.Inthischapter,I'lldiscussthehows,whys,andwhens



ofthisnewSQLServerCLRexecutabletechnology.Forthose

caseswhereCLRexecutablesmakesense,I'llshowyouhowto

design,code,debug,anddeployanumberofexecutables.All

alongtheway,I'llcompareperformanceamongvarious

approachesandshowyousituationswhereaCLRstored

procedureorfunctioncanmakeapositivedifferenceandthose

whereitjustgetsintheway.We'llseehowDBAscancontrol

thisnewfeature(toanextent)andhowdevelopersmustgain

thetrustandrightsfromDBAstogetaccesstothetechnology.



CanVisualBasic.NETDevelopersPlay?

Aseniordata-accessmanageratMicrosoftoncesuggestedthat

CLRexecutableswerenotreallyfor"VisualBasic"

programmersheimpliedthisnewtechnologywastoocomplex

forthemtograsp.I(andothers)tookumbrageatthisremark

andnearlyrushedthestagewithdrawnweapons.Wemadeit

abundantlycleartothis"expert"thatmanyVisualBasic

developerswerefullycapableofdealingwiththemostcomplex

issuesMicrosoftcouldthrowatthem.Thatsaid,Ialsoagreed

thatsomedevelopers(regardlessoftheirlanguageofchoice)

werenotreadytodivehead-longintothecomplexitiesofSQL

ServerCLRexecutables.Iunderstandthatmanyapplication

developersarenotSQLServerawareorcompetentDBAs.Yes,I

expectthatthediscussionsinthischapterarepossiblysomeof

themostcomplexintheentirebook.Isuggestyoureadit

anywayregardlessofyourskilllevelespeciallyifyouplantouse

SQLServerCLRexecutablesanytimeinthefuture.Inaddition,

afterhavingreadthischapter,Iexpectthatvirtuallyany

developerwillhaveenoughinformationtoreallyscrewuptheir

productionSQLServer.



WhatRoleCanVisualStudioPlay?



ForreasonsIfullyunderstand(butdonotexcuse),many

magazinearticlesandMSDNhelptopicsonthisnewtechnology

actasifVisualStudio2005doesnotexist.Theywalkthrough

thefairlylaboriousprocessofcode,testinganddeployingthe

CLRexecutablesviacommand-lineandSQLEnterpriseStudio

queries.Theymustthinkit'smoremachotonotusethetools

Microsofthasmadeavailable.Isuspectthatthosewritingthese

articlesworkstrictlywithSQLServeranddon'tlower

themselvestoworkwithVisualStudio.Ironically,itturnsout

thatVisualStudio2005haseliminatedmuchofthegriefweall

facewhenworkingwithCLRexecutables.Itactuallymakes

developmenteasierevendangerouslyeasy.I'llbesuretoshow

youtheeasyandsafeways.

JustonemorepointonVisualStudio2005.SinceIwrotethis

chapter,I'vespentcountlesshoursworkingwiththedesign,

coding,deployment,anddebuggingstepsneededtocreateover

adozenCLRexecutables.Yes,VisualStudio2005worksbetter

thaneverbefore.GiventhatI'veworkedwiththeearliest(prepublic)versionsofYukonandWhidbey,I'vealsospentcountless

hourstryingtohelpMicrosoftmaketheseproductsworkwell

together.Theend-resultisprettygoodbutjustthat.Iendured

anynumberofincidentswhereVisualStudio2005lockedup,

gotstuckinthemud,orrolledoverintheditchsmokingwith

itswheelsintheair,tossinghoursofcodingintotheditchasit

crashed.No,VisualStudio2005isfarfromperfect,buteven

withtheseproblems,itwasreallyprettyeasytocreatemost

CLRexecutables.ThisdoesnotincludeUser-Definedtypes

(UDTs),asVisualStudiodoesnotknowhowtoletonedebuga

CLRUDTwithoutreinstallingitfirstwhichisnotanoptiondueto

dependencyissues.Yes,Microsoftisstillworkingonthese

issues.Let'shopetheyfigurethemoutsoonhopefullywithout

reinventingthewheel(again)s.



IMHO

Makingiteasyfordevelopersofallskilllevelstoscrewuptheir



productionserverswithill-conceivedCLRexecutablesisnot

suchagoodidea.



EvolvingCLRExecutablesTechnology

InearliersversionsofSQLServer,developers,DBAs,andcodegeneratortoolscodedstoredprocedures,triggers,functions,

andotherobjectsinT-SQLandjustT-SQL.However,ifyour

skillsaresharpenough,youcandevelopandcallanExtended

StoredProcedure(ESP)writteninCorC++.Notmany

developerschoosetotaketheESProute,asitrequiresa

thoroughunderstandingofOpenDataServices(ODS),COM,

andothercomplex(andpotentiallydestructive)technology.Not

onlythat,butdevelopersneedtogettheirDBAtosignoffon

theiruse,andDBAsarenaturallyhesitanttodoso.That's

becauseiftheESPcodescrewsup,itcan(easily)bringdown

theserverorworse[1],andyou'llneedsomeonetotakethe

blame.

[1]ForanexcellentarticleonExtendedStoredProcedures,checkoutthisarticlebyKevinCox,publishedby

29thStreetPress(1997):www.windowsitlibrary.com/Content/77/20/1.html#1



ESPsdidnotgainmuchtractionbackinthelate1990s,when

theywerefirstdiscussedtheywereseenastoohardtocode

andmaintainandfartoodangerous.UnderstandthatanESP

couldkillSQLServerinaheartbeat.It'skindalikejugglingwith

chainsawscooltowatchuntilsomethinggoeswrong.Asa

result,ESPswereusedveryselectivelytoaddresssomeofthe

mostCPU-intensivetasksthosewellbeyondthereachofT-SQL.

Forexample,ESPswereimplementedtoperformcomplex

geometry,trigonometry,orstatisticalcalculations;exposelowlevelWindowsAPIfunctionality;performothercomplexCPUintensiveoperations;orjustprovidefunctionalitythatT-SQL

couldnotperformwithoutassistanceoralotofcode.Overthe

years,theSQLServerteamexposedanumberofsystemESPs

forusebytheSQLServertoolsandspecialDBAfunctions.

OneproblemwithusingESPsisthatSQLServermust(by

definition)fullytrustthecodethereisno"partial-trust"or



"sorta-trust"option."Trust"functionalityisfirstenabledwith

SQLServer2005.Becauseyouuseunmanagedcodetocreate

ESPsandtheyruninthesameaddressspaceasSQLServer,a

probleminanextendedstoredprocedurecoulddamageSQL

Serverinfact,itcouldblue-screenthesystem.Notgood.Now

whowasitthatsaidweshoulduseESPs?

AreCLRexecutablesanysaferthantheESPproceduresthey

replace?No,notnecessarily.IftheCLRexecutablehastobe

markedas"Unsafe",itcandojustasmuchdamageasanESP

executable.



Tip

MicrosoftwrotesignificantpartsofSQLServer2005usingCLR

languagessuchasmanagedC++,C#,andVisualBasic.NET.



Microsoft'sESPReplacement

InSQLsServer2005,T-SQLisstillthelanguageofchoicefor

server-sideexecutables,butyoucanalsoimplementmanyof

theseexecutableobjectsinC#andVisualBasic.NET,and

whatever.NETFrameworkCLRlanguagesMicrosoftchoosesto

add.Inanutshell,SQLServer2005exposes.NETFramework

functionalitybyincorporatingtheabilitytoexecuteCLRcode

fromwithintheSQLServeraddressspace.Thisgives

developerstheoptionto:

WriteSQLServerexecutablecodesuchasstored

procedures,functions,andtriggersinCLR-basedC#or

VisualBasic.NET,andinvokethosestoredproceduresjust



asT-SQLstoredproceduresareexecuted

WriteCLR-baseduser-defineddatatypes(UDTs)and

aggregates,andusethemandtheirassociatedcodeto

defineyourtablesandbusinessrules

ExecuteCLRcodeinthreedefinedlevelsoftrust"SAFE"

(completelyuntrusted),"EXTERNAL_ACCESS"(partially

trusted),and"UNSAFE"(completelytrusted)[2]

[2]Thesecharacterizationsofthetrustlevelmightseembackward,buttheyaren't.Seethefurther

discussionlaterinthischapter.



WritereplacementsforESPsthatperformthesame

operations,but(potentially)moresafelyandwithdirect

accesstothelatestSQLServerdatatypes

Therealquestionis:ShouldyouuseCLRexecutables?Ifyou

rememberJurassicPark(1993)andJeffGoldbloom's

character'sspeechtoMr.Hammond:

Yeah,butyourscientistsweresopreoccupiedwith

whetherornottheycould,theydidn'tstoptothinkifthey

should.[3]

[3]QuotedfromthemovieJurassicPark.â1993,UniversalStudios.



No,Idon'tthinkthatCLRexecutablesarereincarnationsof

carnivorousvelociraptorsorlumberingbrontosaurusesin

disguise,butthistechnologyisaradicaldeparturefromwellknownandwell-understoodT-SQLandshouldbetreated(like

anynewtechnologythatI'mjustlearning)withagoodmeasure

ofrespect.Ialsohopeyouhavedoublyredundanthigh-tension

fencesplacedstrategicallyaroundyourserverjustincase.







WhereDoCLRExecutablesMakeSense?

ConsiderthatthecodeSQLServerexecutesforeachconnection

isonlyoneofmanyjobs/tasks/threadstheserverisexpected

toexecute.SQLServerisandalwayshasbeena"database"

serverdesignedtolocateandstoredatamanagedbyremote

clientseveniftheyareonthesamesystem.Generally,themore

codeSQLServerhastoexecute,thefeweroperationsofall

kindsitcanexecuteinagivenlengthoftime.SQLServerhas

alsobeenahostforitsownbrandofexecutablesfromthe

earliestversions,SQLServerhassupportedT-SQLstored

procedures.

Sure,therearesometasksthatmakesensetoexecuteonthe

serverespeciallywhentheoperationsrequiredirect(and

proximitous)accesstothedata.Forexample,ifyouexecutea

querythatreturnsallairportsclosetoaspecifiedhotelbased

onGPScoordinates,you'llprobablyendupperformingquitea

fewgeometricequationsthatareabitdifficultforT-SQLcode.

Youmighttrytomoveallofthepertinentdatatotheclientand

performthecalculationsinanapplicationandsomeapplications

takethisapproach.However,theexpenseofmovingtoomany

rowsoverthewiretoadistantclientcanbeprohibitively

expensive.MytestsshowthatGPSdistancecalculationsarean

idealcandidateforanon-T-SQLcodefunctionyes,aCLR

function.However,whenworkingwithsetsofdata(suchas

thosereturnedbyaSELECTstatement),callingouttoaCLR

functionfromwithinSQLServercanactuallyhurtperformance.

T-SQLandSQLServerworkcloselytogethertoleverageSQL

Server'sextensivecachesystemstomakesurerelevantand

frequentlyaccesseddataisleftwithineasy(andproximitous)

reachinmemory.

Otherfactorsplayaroleaswell:



DoestheCLRcodeleveragetheabilitytoperformrecursive

orcomplexoperationsthatcannotbedonetosufficient

accuracy(oratall)inT-SQL?

Isthecodebeingexecutedalreadycompiled,ormustitbe

interpretedorcompiledbeforefirstuse?Thisappliesto

boththeT-SQLandCLRroutines.Isthisaone-time

performanceexpenseorapricethatmustbepaidoneach

execution?

DofeaturesbuiltintotheCLRlanguageordataaccess

paradigmaddressproblemsthatcan'tbeeasilyordirectly

solvedinT-SQL?

AreyouusingaCLRroutinebecauseyou'renotthatfamiliar

withT-SQL,orviceversa?

DoesittakemoretimetocalltheCLRroutinethanitwould

tosimplyexecuteapotentiallyslowerT-SQLroutine?In

otherwords,isSQLServerspendingmoretime

transitioningtoandfromtheCLRfunctionthanactually

executingthecode?

CantheCLRcodebewrittenandimplementedwithout

havingtoresortto"fullytrusted"securitymodewherethe

CLRobjectcandoanything?CantheCLRcodefunctionin

an"untrusted"or"partiallytrusted"environment?

Doesyourdevelopmentteamknowhowtowrite,test,

debug,andultimatelysupportCLRcodewellenoughto

implementtheproceduresandotherobjectsneeded?Are

youpreparedtosupportthiscodeindefinitely,ormustyou

bringinconsultantstorepairortuneit?

HaveyourDBAandmanagementteamboughtinonuseof



CLRandthepotentialsecurityissuesitraises?Arethey

preparedtosupporttheuseofCLRcodeindefinitely?Note

thatit'stoughtogobackonceCLRexecutablesare

enabledit'san"allornothing"switchontheserverinstance.

Itappliestoalldatabasesontheserverinstance.

WhenimplementingCLRUser-Definedtypes(UDTs),are

youawareoftheinabilityofthetoolstoautomatically

change,alter,ordroptypesandpreserveexistingdata?Do

youandtheDBAunderstandthemaintenanceimpactof

CLRUDTs?



WhatKindofExecutablesCanorShouldBe

Built?

TogetanideaofwhereCLRcodeispossible,let'sbrieflyoutline

thebasictypesandprovidesomeinsightintohowtheywork,

howthey'redifferent,andhowtheycanbeexpectedtobehave

ontheserver.



CLRStoredProcedures

ACLRstoredprocedurecanaccept(virtually)anynumberof

inputparametersandreturn(virtually)anynumberofOUTPUT

parameters,aninteger(SqlInt32)RETURNvalue,andzeroor

(virtually)anynumberofresultsets(including0toNrowsets).

Intheory,CLRstoredprocedurescanbeusedanywhereaTSQLstoredprocedurecanbeused,including"normal"database

ormaster-basedstoredprocedures,DMLtriggers,orDDL

triggers.AswithT-SQLtriggers,thespecialvirtualINSERTED

andDELETEDtablesareexposed.



CLRFunctions



Likeastoredprocedure,aCLRfunctioncanacceptanynumber

ofinputparameters,butitcannotreturnOUTPUTparametersor

resultsetsonlyaRETURNvaluevariablethatcanbe(almost)

anytype,includingtable-typevariablesorXML.Intheory,CLR

functionscanbeusedanywhereaT-SQLfunctioncanbeused,

sotheycanbecalledfromstoredprocedures,usedinT-SQL

expressions,orcalledfromorotherfunctions.



CLRUser-Definedtypes

ACLRUser-Definedtype(UDT)isawaytobuildanobject

that'sstoredinplaceofaSQLServersystemtypeinaSQL

Servercolumn.UnlikeaT-SQLUDTthat'ssimplyanaliasto

anotherbasetype,aCLRUDTisacomposedofmanyindividual

dataelements.Forexample,youcouldcreatea"Currency"type

thatstorednotonlythemonetaryvalue,butalsotheunit(U.S.

dollars,Britishpounds,Japaneseyen,eurodollar),the

monetarysymbol($,Ê,Ơ,),theexchangerate,thebase

currencyandanyotherpertinentinformation.Considerthatas

thecomplexityoftheUDTincreases,itsusefulnessand

performancedecreaseexponentially.



IMHO

ConsiderthatasthecomplexityoftheUDTincreases,its

usefulnessandperformancedecreaseexponentially.



KeepinmindthatacolumndefinitionconfiguredwithaCLR

UDTcan'tbeeasilyremovedorchanged,aswithsystemdata

typedcolumns.AllreferencesanddependenciestotheUDT

mustbepurgedfromalltablesandproceduresthatreferenceit

beforeitcanbealtered.



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

Chapter 13. Managing SQL Server CLR Executables

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

×