Tải bản đầy đủ

Apress SQL server 2000 stored procedures handbook sep 2008 ISBN 1590592875

SQLServer2000StoredProcedures
Handbook
ISBN:1590592875
byTonyBain,LouisDavidson,
RobinDewsonandChuck
Hawkins
Apress©2003(288pages)
Thishandbookshowshowtowritefasterand
morerobuststoredproceduresandfunctions,
learneffective,real-worldsolutionstoproblems
facedbydatabasedevelopers,designers,and
administrators,andmastertopicssuchas
optimizinganddebugging.
TableofContents
SQLServer2000StoredProceduresHandbook
Introduction
Chapter1 - StoredProceduresOverview
Chapter2 - OptimizingandDebugging
Chapter3 - Concurrency,Cursors,andTransactions
CommonPracticeswithStored
Chapter4 Procedures

Chapter5 - SystemStoredProcedures
Chapter6 - UserDefinedFunctions
Chapter7 - Triggers
Chapter8 - Security
Support,Errata,and
AppendixA http://forums.apress.com
Index


ListofFigures
ListofExamples


BackCover
StoredproceduresarecompiledT-SQLstatementsthat
resideonthedatabase.Theyarethecornerstonesof
successfuldatamanipulation,anddata-handling
operationsofeverycomplexitymakeuseofthem.This
bookisanin-depthguidetoakeyareaofdatabase
development.
Thisbooktacklesreal-worldproblemsfacedby
developerswhenworkingwithstoredprocedures,
showingyouhowtosolvetheseproblems,avoidthe
commonpitfalls,andproducefaster,morerobust
storedprocedures.Putsimply:ifyouwanttowrite
betterstoredprocedures,thenthisisthebookforyou.
AbouttheAuthors
TonyBainisthefounderofTonyBain&Associates.He
hasworkedwithSQLServerforthelast6years,and
heispassionateaboutalldatabasetechnologies,
especiallywhentheyrelatetoenterpriseavailability
andscalability.TonycurrentlyholdstheMicrosoft
CertifiedSystemEngineer,MicrosoftCertifiedSolution
Developer,andMicrosoftCertifiedDatabase
Administratorcertifications.
LouisDavidsonhasbeenintheITindustryfor10years
asacorporatedatabasedeveloperandarchitect.Heis
currentlyadatabaseadministratorforCompass
TechnologyManagement,supportingtheChristian
BroadcastingNetworkandNorthStarStudiosin
Nashville,Tennessee.


RobinDewsonhasbeenhookedonprogrammingever
sinceheboughthisfirstcomputerin1980,aSinclair
ZX80.HisfirstmainapplicationofhisownwasaVisual
FoxProapplicationthatcouldbeusedtorunaFantasy
Leaguesystem.Itwasatthispointhemetupwitha
greathelpinhisPCdevelopmentlife,JonSilverat
StepOneTechnologies,whereinreturnfortraining,he
helpedJonwithsomeotherVisualFoxProapplications.
Fromthere,realizingthatthemarketplaceforVisual
FoxProwaslimited,hedecidedtolearnVisualBasic
andSQLServer.
ChuckHawkinsisaseniorconsultantanddatabase
administratorinVirginiaBeach,Virginia.Heworksfor
CompassTechnologyManagement,wherehemanages
thedailyupsanddownsofmultipleserversforseveral
largeministries.HehasextensiveexperienceinT-SQL
programming,replication,performancetuning,
developermanagement,androutineserver
management.ChuckhasspokenattheProfessional
AssociationforSQLServerconferencesintheUnited
StatesandtheUK.Hehascontributedcolumnsto
severalmagazinesandwasacontributingauthorto
ProfessionalSQLServer2000DatabaseDesign.


SQLServer2000StoredProceduresHandbook
TonyBain
LouisDavidson
RobinDewson
ChuckHawkins
Apress™
Copyright©2003TonyBain,LouisDavidson,RobinDewson,andChuck
Hawkins
Allrightsreserved.Nopartofthisworkmaybereproducedortransmitted
inanyformorbyanymeans,electronicormechanical,including
photocopying,recording,orbyanyinformationstorageorretrieval
system,withoutthepriorwrittenpermissionofthecopyrightownerand
thepublisher.
(pbk):
1-59059-287-5
2345678910
Trademarkednamesmayappearinthisbook.Ratherthanusea
trademarksymbolwitheveryoccurrenceofatrademarkedname,weuse
thenamesonlyinaneditorialfashionandtothebenefitofthetrademark
owner,withnointentionofinfringementofthetrademark.
DistributedtothebooktradeintheUnitedStatesbySpringer-VerlagNew
York,Inc.,175FifthAvenue,NewYork,NY,10010andoutsidetheUnited
StatesbySpringer-VerlagGmbH&Co.KG,Tiergartenstr.17,69112
Heidelberg,Germany.
IntheUnitedStates:phone1-800-SPRINGER,emailorders@springerny.com,orvisithttp://www.springer-ny.com.OutsidetheUnitedStates:
fax+496221345229,emailorders@springer.de,orvisit
http://www.springer.de.
Forinformationontranslations,pleasecontactApressdirectlyat2560


NinthStreet,Suite219,Berkeley,CA94710.Phone510-549-5930,fax
510-549-5939,emailinfo@apress.com,orvisithttp://www.apress.com.
Theinformationinthisbookisdistributedonan"asis"basis,without
warranty.Althougheveryprecautionhasbeentakeninthepreparationof
thiswork,neithertheauthor(s)norApressshallhaveanyliabilitytoany
personorentitywithrespecttoanylossordamagecausedorallegedto
becauseddirectlyorindirectlybytheinformationcontainedinthiswork.
Thesourcecodeforthisbookisavailabletoreadersat
http://www.apress.comintheDownloadssection.Youwillneedtoanswer
questionspertainingtothisbookinordertosuccessfullydownloadthe
code.
Credits
EditorialBoard
DanAppleman
CraigBerry
GaryCornell
TonyDavis
StevenRycroft
JulianSkinner
MartinStreicher
JimSumser
KarenWatterson
GavinWray
JohnZukowski
ManagingEditor
LouayFatoohi
CommissioningEditor
DouglasPaterson
Indexer
AndrewCriddle
TechnicalEditors


ArunNair
VeenaNair
TechnicalReviewers
MikeAhern
ScottAllen
NataliaBortniker
CristianDarie
LouisDavidson
MikeFaulkinbury
BrianKnight
JohnBoydNolan
MorganSkinner
SakhrYouness
ProductionCoordinator
SarahHall
ProofReader
DevLunsford
CoverDesign
KurtKrames
ProjectManagers
SafiullaShakir
CharlotteSmith
AbouttheAuthors
TonyBain
TonyBainisthefounderofTonyBain&Associatesandhehasworked
withSQLServerforthelast6lastyears.Tonyispassionateaboutall
databasetechnologiesespeciallywhentheyrelatetoenterprise
availabilityandscalability.
Tonyspendsalotofhistimewritingandpresentingdatabasetopicsand
hecurrentlyhasMicrosoftCertifiedSystemEngineer,MicrosoftCertified


SolutionDeveloper,andMicrosoftCertifiedDatabaseAdministrator
certification.
ThankstoLinda,Laura,Stephanie,andWilliamfortheircontinued
supportandthanksalsotoCraigWalkerwhoisa.NETlegend!
LouisDavidson
LouisDavidsonhasbeeninthetechnologyindustryfortenyears,asa
corporatedatabasedeveloperandarchitect.Currently,heisservingasa
DatabaseAdministratorforCompassTechnologyManagementintheir
NashvilleDataCentersupportingtheChristianBroadcastingNetwork
andNorthStarStudiosinNashville,TN.
Davidsonhasabachelor'sdegreefromtheUniversityofTennesseeat
Chattanoogaincomputersciencewithaminorinmathematics(though
theminorinmathematicsismoreofanindicationtohowmuchmathUTC
requiredtogettheCSdegree,ratherthananygreatloveorskillinthe
subject).
Themajorityofhisexperience,withslightdeviationsintoVisualBasic,
hasbeenspentwithMicrosoftSQLServerfromversion1.0tothelatest
versionthatisinBeta.Louis'primaryareasofexpertiseareindatabase
architectureandcodinginTransact-SQL,andhehaswrittennumerous
storedproceduresandtriggersthroughouttheyears,thoughheseldom
hastheneedanymorewiththecodegenerationtoolshehasdeveloped
togenerateobjects,withonlyafewproceduresandtriggerstocodefrom
thegroundup.
Louishaspublished"ProfessionalSQLServer2000DatabaseDesign,"
alsobyApress.Thebookfollowsthecompletearcofdevelopinga
databasethroughrequirements,architecture,anddesign.Hehasalso
beenanactivevolunteerwithSQLPASSasapresenteranda
chairpersonintheirspecialinterestgroups.Ithasbeensaidthatinhis
ridiculouslysmallamountofsparetime,hetendstoplayalotofNintendo
(gottosavethatdarnPrincess,shewentoffandwascapturedbythe
sillydragon,again!)andwatchagreatdealoftelevision.Mostnotably,
hisfavoritesareoldEnglishprograms(theAvengers,TheSaint,Monty
Python,andBlackaddertonameafew).Quiteoften,thissparetimeis


alsospentwithhisnotebookcomputerwritingsomethingpertainingto
SQL.
RobinDewson
RobinhascomealongwaysincetheearlyheadydaysoftheSinclair
ZX80/81andSpectrum.Hewasfirstintroducedtocomputersatan
exhibitioninGlasgowwherehesawaCommodorePetmanipulatea
robotandheknewinstantlythatcomputerswastherouteforhim.
UnfortunatelythatrouteinitiallytookhimintoIBMmainframes.
However,hefeelsthatthisisacrucialkeystoneinhisoverallapproachto
computingandwithoutthishewouldnotbewhereheistoday.Well,that,
ScottishCollegeofTextiles,hisfamilyandofcoursemany,manybottles
ofIrnBru(whoneedscaffeine?).RobinmovedtoworkingwithPCs
nearly10yearsagowithFoxBASEandhasmovedfromtherethrough
VisualFoxPro,VisualBasic,Sybase,andofcourseSQLServer..Robin
canbecontactedatrobin@fat-belly.com.
TherearemanypeopleonceagainthatIwouldliketothankfor
differentreasons.AllthoseatWroxthroughouttheyearsbut
especiallyCilmara,Douglas,Cath,Helen,James,andChrisfor
differentreasons,butthanks!AndyatPinballManiaforkeepingmy
pinballmachinesworking,CharlieandDebbieatSeaPallingin
Norfolkforbeingtwogreatfriendsandbrilliantwithmychildrenin
theirarcade,PhillJupitus,Phil(2112rules!)Wilding,GideonCoe,Liz
Kershaw,andAndrewCollinsattheBBC's6Music,
(http://www.bbc.co.uk/6music)fortheexcellentmusicandhumorto
keepmegoingatwork,allmytradersatLehmansbutespecially
Anthony"Jock"Jawadforhisstaunchsupport,andmygoodfriend
JackMason.Ofcoursespecialthanksthoughtomymumanddad
forsortingoutthisgreatlifeforme,mysisterCarolandherfamily,
Eleanor,Erin,andLucasoutinAustraliabutmostofallmywifeJulie
whogoesthroughhellwitheachbookIwrite.Iamafraidthiswas
"notanotherone".ButyoucannowgoandenjoytheDonny
Osmondconcert.Alsomy3longsufferingkids,Scott,Cameron,and
Ellen.Let'sgoandseeamovie.


UptheBlues.(http://www.bedfordrugby.co.uk)
ChuckHawkins
ChuckisaseniorconsultantanddatabaseadministratorinVirginia
Beach,Virginia.WorkingforCompassTechnologyManagement,he
currentlymanagesthedailyupsanddownsofmultipleserversfor
severallargeministries.HehasextensiveexperienceinT-SQL
programming,replication,performancetuning,developermanagement,
androutineservermanagement.
ChuckhasspokenatProfessionalAssociationforSQLServer
conferencesinChicago,London,Denver,andSeattle.Hehas
contributedcolumnstoseveralmagazinesandwasacontributingauthor
forLouisDavidson's"ProfessionalSQLServer2000DatabaseDesign,"
nowpublishedbyApress.Priortohislifeasacomputingprofessional,
ChucktaughtEnglishinJapanforfiveyears.
ChuckishappilymarriedtoKathyandadoptedKristinafromRussiafive
yearsagoonChristmasDay.Whennotworkingwithdatabases,helikes
toplaywithKristina,runlongdistances,andread"FirstThings"journal.
YoucangetintouchwithChuckatchuck@sqlserver.cc.


Introduction
Aswellasbeingusedforfundamentaldatabaseadministration,stored
proceduresarethecornerstoneofanykindofdatabasesolution.Mastery
ofstoredproceduresisimperativetoaccessandmodifyyourdatainthe
mosteffectiveway,aswellastokeepyourdatabasesecureand
performingwell.Thisbookisamustonyourroadtothatmastery.
Thisbookisdedicatedtostoredproceduresandthesurroundingaspects
ofSQLServer2000thataffecttheiroperation.Inhereyouwillfindmany
usefultips,facts,andtechniquesthatwillhelpyoutogetthemostfrom
yourstoredprocedures.Whetheryouareaccessingdatafromaclient
application,performingdatabaseadministrationwithsystemstored
procedures,orevenusingextendedstoredprocedurestoworkwithother
partsoftheoperatingsystem,youwillhopefullyfindinformationthatwill
makeyoureviewyourowndealingswithstoredprocedures,andensure
thecontinuousimprovementofyourdatabasesolutions.


WhoIsThisBookFor?
SQLServer2000administratorsanddesignerswillbenefitfromthis
book,aswillexperiencedSQLServer2000developerswhoarealready
familiarwiththebasicconceptsofstoredprocedures.


BookOutline
Belowisadetailedoutlineofwhatthisbookcovers,chapterbychapter.

Chapter1–StoredProcedureOverview
Webeginbyexaminingwhatconstitutesastoredprocedureanddiscuss
differenttypesofstoredprocedures.Thenwewilllookatthedifference
betweensystemstoredproceduresanduserstoredprocedures,creating
anddesigningstoredprocedures,usingparametersandbestpractices,
flowcontrolstatements,recursion,andreturnvalues.

Chapter2–OptimizingandDebugging
Inthischapter,wewilldiscussoptimizingSQLServer'sstored
procedures.Here,ourfocuswillnotbeonoptimizingtheSQLstatements
themselves,butinstead,howSQLstatementscanbeoptimizedwithin
thecontextofastoredprocedure.Wewillalsodiscusserrorhandling,
signalingerrorconditions,anddebuggingstoredprocedures.

Chapter3–Cursors,Transactions,andConcurrency
Initially,thesearethreetopicsthatmightseemunrelated;however,upon
deeperdiscussion,wewilldiscoverthattheyarerelated.Cursorsare
mechanismstocodenon-set-basedoperationsintoT-SQLstatements.In
general,theiruseisconsideredbadpractice,butcanbeusefulwhen
buildingstoredproceduresifusedproperly.Inthischapterwewilllookat
accessingthemfromcodeandtheirtypicaluses.Transactionsareused
togrouptogethersimilaroperationsintooneatomiclogicaloperation,
andwewilllookatlookatsimple,nested,anddistributedtransactions,
andtheirusefromstoredprocedures.Concurrencyisrelatedtomultitaskingofoperations.Indatabases,weareconcernedwiththenumberof
queriesthatcanbeexecutedatthesametime,especiallymakinguseof
thesameresourcesanddata.Wewilllookatlocks,whicharethe
markersusedbySQLServertodecidewhetherthecommandscanbe
executedconcurrentlyornot,andalsodiscussmethodstomaximize
concurrencybyusingprogrammingschemestolimitSQLlocking


betweenread-onlyandread-writesessions.

Chapter4–TypicalUsesofStoredProcedures
Inthischapter,wewillfocusonthepurposesofstoredprocedureswithin
ourapplications,suchasencapsulatinglogic,improvingapplication
performance,easingadministration,abstractingtheunderlyingbase
tablesawayfromdevelopers,simplifyingcodeupdates,andimproving
databasesecurityanddatavalidation.

Chapter5–SystemStoredProcedures
Inthischapterwewilllookatsystemstoredprocedures,andtheir
implementationbyMicrosoft.Wewillalsolookatsomeofthe
undocumentedfunctionalitiesprovidedwithSQLServer,whichMicrosoft
usestomakecertainsystemstoredprocedureswork.Alongtheway,
we'llbegivingyoutipsandtricksonwhentouse(andonavoiding)their
quiteuseful,butobviously‘unsupported’,undocumentedfunctionalities.
IfyoumanageaSQLServerasapartofyourday-to-daytasks,youwill
findthischapterhelpful.There'sasectiononminingsystemstored
proceduresthatwillbeespeciallyusefultothoseinvolvedinT-SQL
coding.

Chapter6–UserDefinedFunctions
Userdefinedfunctions,knownmorecommonlyasUDFs,areroutines
calledfromT-SQLcodetoreturneitherasinglevalueorarowset,
providingthedeveloperwiththeabilitytocreatetheirowncustomized
functions,whichcanthenbeusedfromotherpartsoftheirT-SQLcode.
UDFshavesomefeaturesthatarecommontostoredproceduresbut
thereareanumberofrestrictions,aswell.Inthischapter,wewillbegin
bylookingatwhataUDFactuallyis,andthenmoveontolookatthe
differenttypesofUDFs,buildingandcallingfunctionsthatreturndifferent
typesofdata,usingschemabindingwithUDFs,andhowUDFsdiffer
fromstoredprocedures.


Chapter7–Triggers
Triggersarebestusedforenforcingbusinessrulesaswellasperforming
validationordatamodifications,whenothermethodsarenotsufficient.
Triggersaretypicallyusedintwoareas:creatingauditrecordsand
reflectingchangestocrucialbusinesstables,andvalidatingchanges
againstasetofbusinessrulescodedinT-SQL.Inthischapterwewill
lookatperformanceconsiderationswhenworkingwithtriggers,the
differenttypesoftriggers,transactionsandtriggers,andrecursive
triggers.

Chapter8–Security
Inthischapterwewillfirstanalyzesecuritythreatsandthecoresecurity
requirementofSQLServer–allowingdataaccessonlytoexplicitly
authorizedusers.Then,wewilllookattheproperimplementationof
storedproceduresforadequatelycounteringthesethreats.Finally,we
willexaminesomegeneralmethodsforsecuringourSQLServer
implementation,givingspecialemphasisonSQLServerstored
proceduresandthesystemstoredproceduresthatMicrosoftshipswith
SQLServer.


Chapter1:StoredProceduresOverview


Overview
WelcometotheSQLServer2000StoredProcedureshandbook.Here,
wewillcoverthedifferenttypesofstoredproceduresusedinSQLServer
2000andtheirusage.Wewillalsoexaminetheworkingofstored
procedures,thepotentiallytrickyareas,andhowtoavoidthem.
Accessingandmanipulatingdatawithinadatabaseisafairly
straightforwardoperation.Wecanbuildacompleteworkingapplication
withfoursimplecommands–SELECT,INSERT,DELETE,andUPDATE,
andperformalltherequiredtasks.Theskillinworkingwithdatabases
liesinbeingabletonotjustworkwiththesecommands,butalso
completeeachunitofworkefficiently.
Toachieveefficiency,adevelopermustconsideranumberoffactors
duringdevelopment.However,wewillconcentrateonrunningT-SQL
fromwithinstoredprocedures,inthisbook.Storedprocedurescantake
differentformsofdesignandimplementation,butthebasicsofthecode
aresimilar.Inthischapter,wewillexaminewhatconstitutesastored
procedureanddiscussdifferenttypes.Wewillcover:
Thedifferencebetweensystemstoredproceduresanduser
storedprocedures
Creatinganddesigningstoredprocedures
Usingparametersandbestpractices
Flowcontrolstatements
Recursion
Returnvalues


WhatisaStoredProcedure?
IfarepetitiveT-SQLtaskhastobeexecutedwithinanapplication,then
thebestrepositoryforitisaprogramcalledastoredprocedure,stored
inSQLServer.StoringthecodeinsidetheSQLServerobjectgivesus
manyadvantages,like:
Securityduetoencryption
Performancegainsduetocompilation
Beingabletoholdthecodeinacentralrepository:
AlteringthecodeinSQLServerwithoutreplicatingin
severaldifferentprograms
Beingabletokeepstatisticsonthecodetokeepit
optimized
Reductionintheamountofdatapassedoveranetworkby
keepingthecodeontheserver
Hidingtherawdatabyallowingonlystoredprocedurestogain
accesstothedata
Youmayhaveexecutedsomead-hocqueriesfortaskslikeinserting
data,queryinginformationinothersystems,orcreatingnewdatabase
objectssuchastables.Allthesetaskscanbeplacedwithinastored
procedure,sothatanydevelopercanrunthesamecodewithouthaving
torecreatetheT-SQLcommands.Also,generalisingthecodeforall
valuesmakesitgenericandreusable.
Storedproceduresaremorethanjusttoolsforperformingrepetitive
tasks.Theycanensuretheintegrityofdata(throughstandalonestored
proceduresortriggers),behaveassubroutinesforperformingpartofa
taskthatcanbecalledfromseveralroutines(knownasuser-defined
functions),orevenactasSQLServerroutinesforeveryonetouse.
Therearetwomaintypesofstoredprocedure–systemstored


proceduresanduser-definedstoredprocedures.Wewillseehowthese
differ,inthenextsection.Wealsohaveextendedstoredproceduresthat
canresideaseithersystemoruser-definedtypes.Extendedstored
proceduresgivefunctionalitythatisnotnecessarilycontainedwithinSQL
Server,likeallowingDOScommandstorunandworkingwithe-mail.Itis
alsopossibletocreateyourownextendedstoredprocedures.Thisbook
doesn'tcoverbuildingextendedstoredprocedures,asthesearewritten
usingC++libraries.

SystemStoredProcedures
AlthoughthereisanenginethatrunsmuchofSQLServer,anumberof
storedproceduressurroundthis.Thesearecalledwhileworkingwith
EnterpriseManager,orthroughaquerytool,suchasQueryAnalyzer.
TheseproceduresareinstalledwithSQLServer,andhence,wedon't
havetocreatethem.
Everytimeweaddormodifyatable,makeabackupplan,orperformany
otheradministrativefunctionfromwithinEnterpriseManager,weactually
callastoredprocedurespecificallywrittentocompletethedesiredaction.
Thesestoredproceduresareknownassystemstoredprocedures,which
arefunctionsthatenhancethebasicfunctionalityofSQLServeritself,
eitherbyextendingthefunctionalityofanexistingsystemstored
procedureorbycreatingnewfunctionalitythatenhancesthebasicsof
whatisalreadythere.
Forexample,thesp_whosystemstoredprocedurewilllistconnections
toSQLServer,includingallthesystemrunningprocesses,butifyoudo
notwanttoseethosesystemprocesses,youcanwriteanew
sp_whousersystemstoredprocedurebasedonsp_whobytaking
sp_whoasabasis,andcreatethenewprocedurefromthat.
Systemstoredproceduresareprefixedbysp_,soitisnotadvisableto
usesp_foranyofthestoredproceduresthatwecreate,unlessthey
formapartofourSQLServerinstallation.Creatingastoredprocedure
prefixedwithsp_andplacingitinthemasterdatabasewillmakeit
availabletoanydatabasewithouttheneedtoprefixthestoredprocedure


withthenameofthedatabase.
Letsclarifythiswithanexample.Ifwetakethesp_whostored
procedure,callitsp_mywho,storeitinthemasterdatabase,andmove
toanotherdatabasesuchasnorthwind,wecanstillexecute
sp_mywho,ratherthanhavingtospecifytheprocedureinthefully
qualifiedmannerasmaster.dbo.sp_mywho.
AlthoughSQLServercomeswithmanyusefulandrelevantsystem
storedproceduresbuiltin,thereisalwaysroomforimprovement.Wewill
discusshowwecanharnessthefullcapablitiesofSQLServerby
inspectingtheseandimprovetheusabilityofSQLServerbycreatingour
own,inChapter5.
Important Ifyouwanttoextendthefunctionalityofanexisting
systemstoredprocedure,donotaltertheexisting
procedure–createyourownversioninstead.
Ifwecreateourownsystemstoredprocedurethenwewillneedtoplace
themwithinallinstallationsofSQLServer(aninstanceofSQLServeris
aseparateinstallation,andhenceaseparateentity)inourorganization,
toensureconsistency.Thereareseveralreasonsfordoingthis.For
example,itispossibletocreatedevelopment,testing,andproduction
installationsascompletelyseparateentities.Wemayfindthe
developmentandtestinstanceononemachine,andtheproduction
instanceonadifferentone.
Wecanseethattherearethreeinstancesdefinedinthefollowing
screenshot–aDevelopmentinstance,aLiveinstance,andaLocal
instance.TheDevelopmentandLocalinstancesresideonthesame
computer,whiletheLiveinstanceisonaremotecomputer.Therefore,
eachinstancewouldhaveitsownstoredprocedurestoperformthe
administrativetasks:


Systemstoredproceduresresideinthemasterdatabaseorthemodel
databaseforeachinstanceinstalled.Everystoredprocedureresidingin
themodeldatabasewillbeplacedintoanydatabasethatwecreate
withinourSQLServerinstance,bydefault.
Important EachinstanceofSQLServer,evenifthereareseveral
instancesonthesamemachine,wouldhaveitsownset
ofstoredprocedures.
Whenwecreateanewdatabase,itisbasedonthemodeldatabase.
Therefore,anynewsystemoruserstoredproceduresaddedtothe
modeldatabasewillalsobeplacedintoeachnewdatabasethatwe
create.
Itisraretocreatesystemproceduresthatarespecifictoonedatabase.
Generally,theyareimplementedasuserstoredprocedures.Now,let's
takealookatthemandseehowthesedifferfromsystemstored
procedures.

UserStoredProcedures


Auserstoredprocedureisanyprogramthatisstoredandcompiled
withinSQLServer(butnotinthemasterdatabase)andprefixedwith
sp_.Userstoredprocedurescanbecategorizedintothreedistincttypes
–userstoredprocedures,triggers,anduserdefinedfunctions.Eachof
thesetypeshasitsfeatures,uses,limitations,anddifferences.
1. Userdefinedstoredproceduresprovideaninterfacetoasetof
processingwithouttheneedfortheendusertoknowthe
structureofthetables,thebusinesslogicoftheorganization,or
themathematicsinvolved,toproducetheendresult.Theyalso
provideasecuremethod,whichalongwithothersecurity
measures,canresultinadatabasewheredataisprotected
frommaliciousoraccidentalmodifications.
2. Atriggerisastoredprocedurewhichfireswhenaspecified
tableactiontakesplace.Youarealsolimitedtocertaincode
thatyoucanplaceinatrigger,asyoushouldnotreturnany
datafromatrigger.WewillseemoreofthisinChapter7.
3. Auserdefinedfunctionisastoredprocedurewhichcantake
parameters,butonlyreturnoneitemofinformation,eithera
scalarvalueoratableofdata.


CreatingStoredProcedures
Thecreationprocessdependsonwhatwewantittodo–wecaneither
buildthewholeprocedureimmediately,orbuildtheT-SQLfirst(formore
complexsolutions),checkitsperformance,andfinally,placeitinastored
procedure.BothwaysrequireustowraptheT-SQLcodewiththesame
CREATEPROCEDUREcommand.
Nowlet'stakealookatthesyntaxforcreatingastoredprocedure:

CREATEPROCEDUREprocedurename[parameter1datatype[length
parameter2...]
AS
BEGIN
...
END

Anexampleofasimplestoredprocedurefollows,wheretwonumbers
arepassedinandthemidpointofthetwonumbersislisted:
CREATEPROCEDUREut_MidPoint@LowerNumberint,@HigherNumbe
AS
BEGIN

DECLARE@Midint
IF@LowerNumber>@HigherNumber
RAISERROR('Youhaveenteredyournumbersthewrongway

SET@Mid=((@HigherNumber-@LowerNumber)/2)+@LowerN
SELECT@Mid
END
Atthetimeofcreation,SQLServertakesourcodeandparsesitforany
syntacticalerrors.Columnnamesandvariablesarecheckedfor
existenceatcompilation.Eveniftheydon'texist,anytemporarytables
createdwithinthestoredprocedurewillalsopassthecompilationstage.
Thisisknownasdeferrednameresolution.Itcanbeanassetora
drawback,aswecancreatetemporarytablesthatexistforthelifetimeof


thestoredprocedureexecutiononly,whichisdesirable,butifwedefinea
temporarytableandgetsomethingwronglateron,suchasacolumn
name,thenthecompilationwillnotpickupthiserror.
WhileexecutingtheCREATEPROCEDUREstatement,errorswillbe
reported.Onceitiscompiled,thedetailsofthestoredprocedureare
storedinthreesystemtablesintheconcerneddatabase:
sysobjects
Thistablecontainsarowforeachobjectthatiscreatedwithinthe
database.Ifyouwanttotrackanobjectinthedatabase,youcan
usethisasthemainroot.Apartfromtheobjectnameandtype,
thistablealsokeepstrackoftheobject'sownerandtimeof
creation.Thiscanbeusefulincrosscheckingthecontentsofour
sourcecontrolsystemwithourdatabase.
sysdepends
Thistablestoresdependencyinformationaboutobjects.For
example,whenastoredprocedure,view,ortriggeriscreated,
therecanbereferencestoothertables,views,orprocedures
withinit.Thesereferencesareknownasdependencies.Ifoneof
thedependentobjectsalters,wemayneedtorecompilethe
storedprocedure.Forexample,ifwealteranindexonatable,we
shouldrecompileeverydependentobject.
syscomments
ThisholdstheoriginalSQLdefinitionstatementsofthestored
procedure.Italsoholdsdetailsofviews,rules,defaults,triggers,
CHECKconstraints,andDEFAULTconstraints.
Itispossibletointerrogatethesedata.BylookingforrowswithaPinthe
sysobjectstable,wecanobtainallthestoredprocedures.Fromthat,
wecanfindoutwhenthestoredprocedurewascreated,andalsomove
tothesyscommentstablebyusingtheIDtoretrievedetailedinformation
abouttheprocedureitself,like,ifitisencryptedornot.
Thesetablesaresafeonlyforinterrogation,althoughdetailswithinthem
canalwayschangebetweenSQLServerreleases.Oneofthebest


methodstoensurethatthecodestoredinyoursourcecontrolsystem
matchesthatwithinyourdatabaseistocheckifthedatesandtimes
matchorarewithinafewsecondsofeachother.
Important Althoughwehavementionedthesetables,westrongly
advisethatyoushouldneveralteranyinformationin
thesetablesdirectly.

PerformanceConsideration
Whenastoredprocedureiscreated,itpassesthroughseveralsteps.
Firstofall,theT-SQLisparsedandresolved,savedtothedisk,and
storedinSQLServer.Thefirsttimetheprocedureisexecuted,the
procedureisretrievedandoptimized,onthebasisofanydataqueries
andvaluespassedthroughparameters.SQLServerwillinspectthecode
andtrytousethebestindexesonthetables,whicharereferencedby
checkingthestatisticsthatareheldforthosetables.
ThequeryplanisthencachedwithinSQLServer,readyforanyfurther
executions.SQLServerwillalwaysusethisplan,providingitdoesn't
retiretheplan.Thus,theperformancegainofstoredprocedurescomes
fromcompiledcachedplans.

NetworkConsideration
YoumayconsiderpassingT-SQLstatementstoinsertarowintoatable,
withveryfewcharacters.However,creatingastoredprocedureand
passingonlythenameofthestoredprocedure,parameters,andtheir
valuesreducesthecharactersneeded.Wecanseetheextraoverhead
imposedbytheT-SQLstatementsonournetworkbymultiplyingthis
differencebythenumberofcallsbeingmade.Thiscanbeasignificant
issue,especiallyifweareusingitovertheInternet.
Comparethenexttwostatementswitheachother:
INSERTINTOEmployeeTerritories(EmployeeID,TerritoryID)
VALUES(3,12345)


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

Tải bản đầy đủ ngay

×

×