Tải bản đầy đủ (.pdf) (1,127 trang)

Oracle PL SQL by example 5th

Bạn đang xem bản rút gọn của tài liệu. Xem và tải ngay bản đầy đủ của tài liệu tại đây (18.32 MB, 1,127 trang )


AboutThiseBook
ePUBisanopen,industry-standardformatforeBooks.However,supportofePUBand
itsmanyfeaturesvariesacrossreadingdevicesandapplications.Useyourdeviceorapp
settingstocustomizethepresentationtoyourliking.Settingsthatyoucancustomizeoften
includefont,fontsize,singleordoublecolumn,landscapeorportraitmode,andfigures
thatyoucanclickortaptoenlarge.Foradditionalinformationaboutthesettingsand
featuresonyourreadingdeviceorapp,visitthedevicemanufacturer’sWebsite.
Manytitlesincludeprogrammingcodeorconfigurationexamples.Tooptimizethe
presentationoftheseelements,viewtheeBookinsingle-column,landscapemodeand
adjustthefontsizetothesmallestsetting.Inadditiontopresentingcodeand
configurationsinthereflowabletextformat,wehaveincludedimagesofthecodethat
mimicthepresentationfoundintheprintbook;therefore,wherethereflowableformat
maycompromisethepresentationofthecodelisting,youwillseea“Clickheretoview
codeimage”link.Clickthelinktoviewtheprint-fidelitycodeimage.Toreturntothe
previouspageviewed,clicktheBackbuttononyourdeviceorapp.


Oracle®PL/SQLbyExample
FifthEdition
BenjaminRosenzweig
ElenaRakhimov

UpperSaddleRiver,NJ•Boston•Indianapolis•SanFrancisco
NewYork•Toronto•Montreal•London•Munich•Paris•Madrid
Capetown•Sydney•Tokyo•Singapore•MexicoCity


Manyofthedesignationsusedbymanufacturersandsellerstodistinguishtheirproducts
areclaimedastrademarks.Wherethosedesignationsappearinthisbook,andthe
publisherwasawareofatrademarkclaim,thedesignationshavebeenprintedwithinitial


capitallettersorinallcapitals.
Theauthorsandpublisherhavetakencareinthepreparationofthisbook,butmakeno
expressedorimpliedwarrantyofanykindandassumenoresponsibilityforerrorsor
omissions.Noliabilityisassumedforincidentalorconsequentialdamagesinconnection
withorarisingoutoftheuseoftheinformationorprogramscontainedherein.
Forinformationaboutbuyingthistitleinbulkquantities,orforspecialsalesopportunities
(whichmayincludeelectronicversions;customcoverdesigns;andcontentparticularto
yourbusiness,traininggoals,marketingfocus,orbrandinginterests),pleasecontactour
corporatesalesdepartmentator(800)382-3419.
Forgovernmentsalesinquiries,pleasecontact
ForquestionsaboutsalesoutsidetheU.S.,pleasecontact
VisitusontheWeb:informit.com/ph
LibraryofCongressCataloging-in-PublicationData
Rosenzweig,Benjamin.
OraclePL/SQ®byexample/BenjaminRosenzweig,ElenaRakhimov.—Fifthedition.
pagescm
Includesindex.
ISBN978-0-13-379678-0(pbk.:alk.paper)—ISBN0-13-379678-7(pbk.:alk.paper)
1.PL/SQL(Computerprogramlanguage)2.Oracle(Computerfile)3.Relational
databases.
I.Rakhimov,ElenaSilvestrova.II.Title.
QA76.73.P258R682015
005.75’6—
dc232014045792
Copyright©2015PearsonEducation,Inc.
Allrightsreserved.PrintedintheUnitedStatesofAmerica.Thispublicationisprotected
bycopyright,andpermissionmustbeobtainedfromthepublisherpriortoanyprohibited
reproduction,storageinaretrievalsystem,ortransmissioninanyformorbyanymeans,
electronic,mechanical,photocopying,recording,orlikewise.Toobtainpermissiontouse
materialfromthiswork,pleasesubmitawrittenrequesttoPearsonEducation,Inc.,

PermissionsDepartment,OneLakeStreet,UpperSaddleRiver,NewJersey07458,oryou
mayfaxyourrequestto(201)236-3290.
ISBN-13:978-0-13-379678-0
ISBN-10:0-13-379678-7
TextprintedintheUnitedStatesonrecycledpaperatRRDonnelleyinCrawfordsville,
Indiana.
Firstprinting,February2015


Tomyparents,RosieandSandyRosenzweig,
fortheirloveandsupport
—BenjaminRosenzweig
Tomyfamily,fortheirexcitementandencouragement
—ElenaRakhimov


Contents
Preface
Acknowledgments
AbouttheAuthors
IntroductiontoPL/SQLNewFeaturesinOracle12c
Invoker’sRightsFunctionsCanBeResult-Cached
MorePL/SQL-OnlyDataTypesCanCrossthePL/SQL-to-SQLInterface
Clause
ACCESSIBLEBYClause
FETCHFIRSTClause
RolesCanBeGrantedtoPL/SQLPackagesandStand-AloneSubprograms
MoreDataTypesHavetheSameMaximumSizeinSQLandPL/SQL
DatabaseTriggersonPluggableDatabases
LIBRARYCanBeDefinedasaDIRECTORYObjectandwitha

CREDENTIALClause
ImplicitStatementResults
BEQUEATHCURRENT_USERViews
INHERITPRIVILEGESandINHERITANYPRIVILEGESPrivileges
InvisibleColumns
Objects,NotTypes,AreEditionedorNoneditioned
PL/SQLFunctionsThatRunFasterinSQL
PredefinedInquiryDirectives$$PLSQL_UNIT_OWNERand
$$PLSQL_UNIT_TYPE
CompilationParameterPLSQL_DEBUGIsDeprecated
Chapter1PL/SQLConcepts
Lab1.1:PL/SQLArchitecture
PL/SQLArchitecture
PL/SQLBlockStructure
HowPL/SQLGetsExecuted
Lab1.2:PL/SQLDevelopmentEnvironment
GettingStartedwithSQLDeveloper
GettingStartedwithSQL*Plus


ExecutingPL/SQLScripts
Lab1.3:PL/SQL:TheBasics
DBMS_OUTPUT.PUT_LINEStatement
SubstitutionVariableFeature
Summary
Chapter2PL/SQLLanguageFundamentals
Lab2.1:PL/SQLProgrammingFundamentals
PL/SQLLanguageComponents
PL/SQLVariables
PL/SQLReservedWords

IdentifiersinPL/SQL
AnchoredDataTypes
DeclareandInitializeVariables
ScopeofaBlock,NestedBlocks,andLabels
Summary
Chapter3SQLinPL/SQL
Lab3.1:DMLStatementsinPL/SQL
InitializeVariableswithSELECTINTO
UsingtheSELECTINTOSyntaxforVariableInitialization
UsingDMLinaPL/SQLBlock
UsingaSequenceinaPL/SQLBlock
Lab3.2:TransactionControlinPL/SQL
UsingCOMMIT,ROLLBACK,andSAVEPOINT
PuttingTogetherDMLandTransactionControl
Summary
Chapter4ConditionalControl:IFStatements
Lab4.1:IFStatements
IF-THENStatements
IF-THEN-ELSEStatement
Lab4.2:ELSIFStatements
Lab4.3:NestedIFStatements
Summary


Chapter5ConditionalControl:CASEStatements
Lab5.1:CASEStatements
CASEStatements
SearchedCASEStatements
Lab5.2:CASEExpressions
Lab5.3:NULLIFandCOALESCEFunctions

NULLIFFunction
COALESCEFunction
Summary
Chapter6IterativeControl:PartI
Lab6.1:SimpleLoops
EXITStatement
EXITWHENStatement
Lab6.2:WHILELoops
UsingWHILELoops
PrematureTerminationoftheWHILELoop
Lab6.3:NumericFORLoops
UsingtheINOptionintheLoop
UsingtheREVERSEOptionintheLoop
PrematureTerminationoftheNumericFORLoop
Summary
Chapter7IterativeControl:PartII
Lab7.1:CONTINUEStatement
UsingCONTINUEStatement
CONTINUEWHENStatement
Lab7.2:NestedLoops
UsingNestedLoops
UsingLoopLabels
Summary
Chapter8ErrorHandlingandBuilt-inExceptions
Lab8.1:HandlingErrors
Lab8.2:Built-inExceptions


Summary
Chapter9Exceptions

Lab9.1:ExceptionScope
Lab9.2:User-DefinedExceptions
Lab9.3:ExceptionPropagation
Re-raisingExceptions
Summary
Chapter10Exceptions:AdvancedConcepts
Lab10.1:RAISE_APPLICATION_ERROR
Lab10.2:EXCEPTION_INITPragma
Lab10.3:SQLCODEandSQLERRM
Summary
Chapter11IntroductiontoCursors
Lab11.1:TypesofCursors
MakingUseofanImplicitCursor
MakingUseofanExplicitCursor
Lab11.2:CursorLoop
ProcessinganExplicitCursor
MakingUseofaUser-DefinedRecord
MakingUseofCursorAttributes
Lab11.3:CursorFORLOOPs
MakingUseofCursorFORLOOPs
Lab11.4:NestedCursors
ProcessingNestedCursors
Summary
Chapter12AdvancedCursors
Lab12.1:ParameterizedCursors
CursorswithParameters
Lab12.2:ComplexNestedCursors
Lab12.3:FORUPDATEandWHERECURRENTCursors
FORUPDATECursor
FORUPDATEOFinaCursor



WHERECURRENTOFinaCursor
Summary
Chapter13Triggers
Lab13.1:WhatTriggersAre
DatabaseTrigger
BEFORETriggers
AFTERTriggers
AutonomousTransaction
Lab13.2:TypesofTriggers
RowandStatementTriggers
INSTEADOFTriggers
Summary
Chapter14MutatingTablesandCompoundTriggers
Lab14.1:MutatingTables
WhatIsaMutatingTable?
ResolvingMutatingTableIssues
Lab14.2:CompoundTriggers
WhatIsaCompoundTrigger?
ResolvingMutatingTableIssueswithCompoundTriggers
Summary
Chapter15Collections
Lab15.1:PL/SQLTables
AssociativeArrays
NestedTables
CollectionMethods
Lab15.2:Varrays
Lab15.3:MultilevelCollections
Summary

Chapter16Records
Lab16.1:RecordTypes
Table-BasedandCursor-BasedRecords
User-DefinedRecords


RecordCompatibility
Lab16.2:NestedRecords
Lab16.3:CollectionsofRecords
Summary
Chapter17NativeDynamicSQL
Lab17.1:EXECUTEIMMEDIATEStatements
UsingtheEXECUTEIMMEDIATEStatement
HowtoAvoidCommonORAErrorsWhenUsingEXECUTE
IMMEDIATE
Lab17.2:OPEN-FOR,FETCH,andCLOSEStatements
OpeningCursor
FetchingfromaCursor
ClosingaCursor
Summary
Chapter18BulkSQL
Lab18.1:FORALLStatements
UsingFORALLStatements
SAVEEXCEPTIONSOption
INDICESOFOption
VALUESOFOption
Lab18.2:TheBULKCOLLECTClause
Lab18.3:BindingCollectionsinSQLStatements
BindingCollectionswithEXECUTEIMMEDIATEStatements
BindingCollectionswithOPEN-FOR,FETCH,andCLOSEStatements

Summary
Chapter19Procedures
BenefitsofModularCode
BlockStructure
AnonymousBlocks
Lab19.1:CreatingProcedures
PuttingProcedureCreationSyntaxintoPractice
QueryingtheDataDictionaryforInformationonProcedures


Lab19.2:PassingParametersINandOUTofProcedures
UsingINandOUTParameterswithProcedures
Summary
Chapter20Functions
Lab20.1:CreatingFunctions
CreatingStoredFunctions
MakingUseofFunctions
Lab20.2:UsingFunctionsinSQLStatements
InvokingFunctionsinSQLStatements
WritingComplexFunctions
Lab20.3:OptimizingFunctionExecutioninSQL
DefiningaFunctionUsingtheWITHClause
CreatingaFunctionwiththeUDFPragma
Summary
Chapter21Packages
Lab21.1:CreatingPackages
CreatingPackageSpecifications
CreatingPackageBodies
CallingStoredPackages
CreatingPrivateObjects

Lab21.2:CursorVariables
Lab21.3:ExtendingthePackage
ExtendingthePackagewithAdditionalProcedures
Lab21.4:PackageInstantiationandInitialization
CreatingPackageVariablesDuringInitialization
Lab21.5:SERIALLY_REUSABLEPackages
UsingtheSERIALLY_REUSABLEPragma
Summary
Chapter22StoredCode
Lab22.1:GatheringInformationaboutStoredCode
GettingStoredCodeInformationfromtheDataDictionary
OverloadingModules


Summary
Chapter23ObjectTypesinOracle
Lab23.1:ObjectTypes
CreatingObjectTypes
UsingObjectTypeswithCollections
Lab23.2:ObjectTypeMethods
ConstructorMethods
MemberMethods
StaticMethods
ComparingObjects
Summary
Chapter24Oracle-SuppliedPackages
Lab24.1:ExtendingFunctionalitywithOracle-SuppliedPackages
AccessingFileswithinPL/SQLwithUTL_FILE
SchedulingJobswithDBMS_JOB
GeneratinganExplainPlanwithDBMS_XPLAN

GeneratingImplicitStatementResultswithDBMS_SQL
Lab24.2:ErrorReportingwithOracle-SuppliedPackages
UsingtheDBMS_UTILITYPackageforErrorReporting
UsingtheUTL_CALL_STACKPackageforErrorReporting
Summary
Chapter25OptimizingPL/SQL
Lab25.1:PL/SQLTuningTools
PL/SQLProfilerAPI
TraceAPI
PL/SQLHierarchicalProfiler
Lab25.2:PL/SQLOptimizationLevels
Lab25.3:SubprogramInlining
Summary
AppendixAPL/SQLFormattingGuide
Case
WhiteSpace


NamingConventions
Comments
OtherSuggestions
AppendixBStudentDatabaseSchema
TableandColumnDescriptions
Index


Preface
Oracle®PL/SQLbyExample,FifthEdition,presentstheOraclePL/SQLprogramming
languageinauniqueandhighlyeffectiveformat.ItchallengesyoutolearnOracle
PL/SQLbyusingitratherthanbysimplyreadingaboutit.

Justasagrammarworkbookwouldteachyouaboutnounsandverbsbyfirstshowing
youexamplesandthenaskingyoutowritesentences,Oracle®PL/SQLbyExample
teachesyouaboutcursors,loops,procedures,triggers,andsoonbyfirstshowingyou
examplesandthenaskingyoutocreatetheseobjectsyourself.

WhoThisBookIsFor
Thisbookisintendedforanyonewhoneedsaquickbutdetailedintroductionto
programmingwithOracle’sPL/SQLlanguage.Theidealreadersarethosewithsome
relationaldatabaseexperience,withsomeOracleexperience,specificallywithSQL,
SQL*Plus,andSQLDeveloper,butwithlittleornoexperiencewithPL/SQLorwithmost
otherprogramminglanguages.
Thecontentofthisbookisbasedprimarilyonthematerialthatwastaughtinan
IntroductiontoPL/SQLclassatColumbiaUniversity’sComputerTechnologyand
Applications(CTA)programinNewYorkCity.Thestudentbodywasratherdiverse,in
thatthereweresomestudentswhohadyearsofexperiencewithinformationtechnology
(IT)andprogramming,butnoexperiencewithOraclePL/SQL,andthentherewerethose
withabsolutelynoexperienceinITorprogramming.Thecontentofthebook,likethe
class,isbalancedtomeettheneedsofbothextremes.Theadditionalexercisesavailable
throughthecompanionwebsitecanbeusedaslabsandhomeworkassignmentsto
accompanythelecturesinsuchaPL/SQLcourse.

HowThisBookIsOrganized
TheintentofthisworkbookistoteachyouaboutOraclePL/SQLbyexplaininga
programmingconceptoraparticularPL/SQLfeatureandthenillustrateitfurtherby
meansofexamples.Oftentimes,asthetopicisdiscussedmoreindepth,theseexamples
wouldbechangedtoillustratenewlycoveredmaterial.Inaddition,mostofthechaptersof
thisbookhaveAdditionalExercisessectionsavailablethroughthecompanionwebsite.
Theseexercisesallowyoutotestthedepthofyourunderstandingofthenewmaterial.
Thebasicstructureofeachchapterisasfollows:
Objectives

Introduction
Lab
Lab…
Summary
TheObjectivessectionliststopicscoveredinthechapter.Basicallyasingleobjective
correspondstoasingleLab.


TheIntroductionoffersashortoverviewoftheconceptsandfeaturescoveredinthe
chapter.
EachLabcoversasingleobjectivelistedintheObjectivessectionofthechapter.In
someinstancestheobjectiveisdividedevenfurtherintothesmallerindividualtopicsin
theLab.Theneachsuchtopicisexplainedandillustratedwiththehelpofexamplesand
correspondingoutputs.Notethatasmuchaspossible,eachexampleisprovidedinits
entiretysothatacompletecodesampleisreadilyavailable.
AttheendofeachchapteryouwillfindaSummarysection,whichprovidesabrief
conclusionofthematerialdiscussedinthechapter.Inaddition,theBytheWayportion
willstatewhetheraparticularchapterhasanAdditionalExercisessectionavailableonthe
companionwebsite.

AbouttheCompanionWebsite
ThecompanionWebsiteislocatedatinformit.com/title/0133796787.Hereyouwillfind
threeveryimportantthings:
FilesrequiredtocreateandinstalltheSTUDENTschema.
Filesthatcontainexamplescriptsusedinthebookchapters.
AdditionalExerciseschapters,whichhavetwoparts:
•AQuestionsandAnswerspartwhereyouareaskedaboutthematerialpresented
inaparticularchapteralongwithsuggestedanswerstothesequestions.
Oftentimes,youareaskedtomodifyascriptbasedonsomerequirementsand
explainthedifferenceintheoutputcausedbythesemodifications.Notethatthis

partisalsoorganizedintoLabssimilartoitscorrespondingchapterinthebook.
•ATryitYourselfpartwhereyouareaskedtocreatescriptsbasedonthe
requirementsprovided.ThispartisdifferentfromtheQuestionsandAnswerspart
inthattherearenoscriptssuppliedwiththequestions.Instead,youwillneedto
createscriptsintheirentirety.
BytheWay
Youneedtovisitthecompanionwebsite,downloadthestudentschema,and
installitinyourdatabasepriortousingthisbookifyouwouldliketheability
toexecutethescriptsprovidedinthechaptersandonthesite.

WhatYouWillNeed
Therearesoftwareprogramsaswellasknowledgerequirementsnecessarytocompletethe
Labsinthisbook.Notethatsomefeaturescoveredthroughoutthebookareapplicableto
Oracle12conly.However,youwillbeabletorunagreatmajorityoftheexamplesand
completeAdditionalExercisesandTryitYourselfsectionsbyusingthefollowing
products:
Oracle11gorhigher


SQLDeveloperorSQL*Plus11gorhigher
AccesstotheInternet
YoucanuseeitherOraclePersonalEditionorOracleEnterpriseEditiontoexecutethe
examplesinthisbook.IfyouuseOracleEnterpriseEdition,itcanberunningonaremote
serverorlocallyonyourownmachine.ItisrecommendedthatyouuseOracle11gor
Oracle12cinordertoperformalloramajorityoftheexamplesinthisbook.Whena
featurewillonlyworkinthelatestversionofOracledatabase,thebookwillstateso
explicitly.Additionally,youshouldhaveaccesstoandbefamiliarwithSQLDeveloperor
SQL*Plus.
YouhaveanumberofoptionsforhowtoeditandrunscriptsinSQLDeveloperorfrom
SQL*Plus.Therearealsomanythird-partyprogramstoeditanddebugPL/SQLcode.

Both,SQLDeveloperandSQL*Plusareusedthroughoutthisbook,sincethesearetwo
Oracle-providedtoolsandcomeaspartoftheOracleinstallation.
BytheWay
Chapter1hasaLabtitledPL/SQLDevelopmentEnvironmentthatdescribes
howtogetstartedwithSQLDeveloperandSQL*Plus.However,agreat
majorityoftheexamplesusedinthebookwereexecutedinSQLDeveloper.

AbouttheSampleSchema
TheSTUDENTschemacontainstablesandotherobjectsmeanttokeepinformationabout
aregistrationandenrollmentsystemforafictitiousuniversity.Therearetentablesinthe
systemthatstoredataaboutstudents,courses,instructors,andsoon.Inadditiontostoring
contactinformation(addressesandtelephonenumbers)forstudentsandinstructors,and
descriptiveinformationaboutcourses(costsandprerequisites),theschemaalsokeeps
trackofthesectionsforparticularcourses,andthesectionsinwhichstudentshave
enrolled.
TheSECTIONtableisoneofthemostimportanttablesintheschemabecauseitstores
dataabouttheindividualsectionsthathavebeencreatedforeachcourse.Eachsection
recordalsostoresinformationaboutwhereandwhenthesectionwillmeetandwhich
instructorwillteachthesection.TheSECTIONtableisrelatedtotheCOURSEand
INSTRUCTORtables.
TheENROLLMENTtableisequallyimportantbecauseitkeepstrackofwhichstudents
haveenrolledinwhichsections.Eachenrollmentrecordalsostoresinformationaboutthe
student’sgradeandenrollmentdate.TheenrollmenttableisrelatedtotheSTUDENTand
SECTIONtables.
TheSTUDENTschemaalsohasanumberofothertablesthatmanagegradingforeach
studentineachsection.
ThedetailedstructureoftheSTUDENTschemaisdescribedinAppendixB,Student
DatabaseSchema.



Acknowledgments
BenRosenzweig:IwouldliketothankmycoauthorElenaRakhimovforbeinga
wonderfulandknowledgeablecolleaguetoworkwith.IwouldalsoliketothankDouglas
Schererforgivingmetheopportunitytoworkonthisbookaswellasforproviding
constantsupportandassistancethroughtheentirewritingprocess.Iamindebtedtothe
teamatPrenticeHall,whichincludesGregDoench,MichelleHousley,andespecially
SonglinQiuforherdetailededits.Finally,Iwouldliketothankthemanyfriendsand
family,especiallyEdwardClarinandEdwardKnopping,forhelpingmethroughthelong
processofputtingthewholebooktogether,whichincludedmanylatenightsand
weekends.
ElenaRakhimov:Mycontributiontothisbookreflectsthehelpandadviceofmany
people.IamparticularlyindebtedtomycoauthorBenRosenzweigformakingthisproject
arewardingandenjoyableexperience.ManythankstoGregDoench,MichelleHousley,
andespeciallySonglinQiuforhermeticulouseditingskills,andmanyothersatPrentice
Hallwhodiligentlyworkedtobringthisbooktomarket.ThankstoMichaelRinomhota
forhisinvaluableexpertiseinsettinguptheOracleenvironmentandDanHotkaforhis
valuablecommentsandsuggestions.Mostimportantly,tomyfamily,whoseexcitement,
enthusiasm,inspiration,andsupportencouragedmetoworkhardtotheveryend,and
wereexceededonlybytheirlove.


AbouttheAuthors
BenjaminRosenzweigisaSeniorProjectManageratMisysFinancialSoftware,where
hehasworkedsince2002.Priortothathewasaprincipalconsultantformorethanthree
yearsatOracleCorporationintheCustomDevelopmentDepartment.Hiscomputer
experiencerangesfromcreatinganelectronicTibetan–EnglishDictionaryinKathmandu,
Nepal,tosupportingpresentationcentersatGoldmanSachsandmanagingatrading
systematTIAA-CREF.BenjaminhasbeenaninstructorattheColumbiaUniversity
ComputerTechnologyandApplicationprograminNewYorkCitysince1998.In2002he
wasawardedthe“OutstandingTeachingAward”fromtheChairandDirectoroftheCTA

program.HeholdsaB.A.fromReedCollegeandacertificateindatabasedevelopment
anddesignfromColumbiaUniversity.HispreviousbookswithPrenticeHallareOracle
FormsDeveloper:TheCompleteVideoCourse(2000),andOracleWebApplication
ProgrammingforPL/SQLDevelopers(2003).
ElenaRakhimovhasover20yearsofexperienceindatabasearchitectureand
developmentinawidespectrumofenterpriseandbusinessenvironmentsrangingfrom
non-profitorganizationstoWallStreettohercurrentpositionwithaprominentsoftware
companywheresheheadsupthedatabaseteam.Herdeterminationtostay“hands-on”
notwithstanding,Elenamanagedtoexcelintheacademicarenahavingtaughtrelational
databaseprogrammingatColumbiaUniversity’shighlyesteemedComputerTechnology
andApplicationsprogram.ShewaseducatedindatabaseanalysisanddesignatColumbia
UniversityandinappliedmathematicsatBakuStateUniversityinAzerbaijan.She
currentlyresidesinVancouver,Canada.


IntroductiontoPL/SQLNewFeaturesinOracle
12c
Oracle12chasintroducedanumberofnewfeaturesandimprovementsforPL/SQL.This
introductionbrieflydescribesfeaturesnotcoveredinthisbookandpointsyoutospecific
chaptersforfeaturesthatarewithinthescopeofthisbook.Thelistoffeaturesdescribed
hereisalsoavailableinthe“ChangesinThisReleaseforOracleDatabasePL/SQL
LanguageReference”sectionofthePL/SQLLanguageReferencemanualofferedaspart
ofOracle’sonlinehelp.
ThenewPL/SQLfeaturesandenhancementsareasfollows:
Invoker’srightsfunctionscanberesult-cached
MorePL/SQL-onlydatatypescancrossthePL/SQL-to-SQLinterfaceclause
ACCESSIBLEBYclause
FETCHFIRSTclause
RolescanbegrantedtoPL/SQLpackagesandstand-alonesubprograms
MoredatatypeshavethesamemaximumsizeinSQLandPL/SQL

Databasetriggersonpluggabledatabases
LIBRARYcanbedefinedasDIRECTORYobjectandwithCREDENTIALclause
Implicitstatementresults
BEQUEATHCURRENT_USERviews
INHERITPRIVILEGESandINHERITANYPRIVILEGESprivileges
Invisiblecolumns
Objects,nottypes,areeditionedornoneditioned
PL/SQLfunctionsthatrunfasterinSQL
Predefinedinquirydirectives$$PLSQL_UNIT_OWNERand
$$PLSQL_UNIT_TYPE
CompilationparameterPLSQL_DEBUGisdeprecated

Invoker’sRightsFunctionsCanBeResult-Cached
WhenastoredsubprogramiscreatedinOracleproducts,itmaybecreatedaseithera
definerrights(DR)unitoraninvokerrights(IR)unit.ADRunitwouldexecutewiththe
permissionsofitsowner,whereasanIRunitwouldexecutewiththepermissionsofauser
whoinvokedthatparticularunit.Bydefault,astoredsubprogramiscreatedasaDRunit
unlessexplicitlyspecifiedotherwise.WhetheraparticularunitisconsideredaDRorIR
unitiscontrolledbytheAUTHIDproperty,whichmaybesettoeitherDEFINER(default)
orCURRENT_USER.


PriortoOracle12c,functionscreatedwiththeinvokerrightsclause(AUTHID
CURRENT_USER)couldnotberesult-cached.TocreateafunctionasanIRunit,the
AUTHIDclausemustbeaddedtothefunctionspecification.
Aresult-cachedfunctionisafunctionwhoseparametervaluesandresultarestoredin
thecache.Asaconsequence,whensuchafunctionisinvokedwiththesameparameter
values,itsresultisretrievedfromthecacheinsteadofbeingcomputedagain.Toenablea
functionforresult-caching,theRESULT_CACHEclausemustbeaddedtothefunction
specification.Thisisdemonstratedbythefollowingexample(theinvokerrightsclause

andresult-cachingarehighlightedinbold).
ForExampleResult-CachingFunctionsCreatedwithInvoker’sRights
Clickheretoviewcodeimage
CREATEORREPLACEFUNCTIONget_student_rec(p_student_idINNUMBER)
RETURNSTUDENT%ROWTYPE
AUTHIDCURRENT_USER
RESULT_CACHERELIES_ON(student)
IS
v_student_recSTUDENT%ROWTYPE;
BEGIN
SELECT*
INTOv_student_rec
FROMstudent
WHEREstudent_id=p_student_id;
RETURNv_student_rec;
EXCEPTION
WHENno_data_found
THEN
RETURNNULL;
ENDget_student_rec;
/
—Executenewlycreatedfunction
DECLARE
v_student_recSTUDENT%ROWTYPE;
BEGIN
v_student_rec:=get_student_rec(p_student_id=>230);
END;

NotethatifthestudentrecordforstudentID230isintheresultcachealready,thenthe
functionwillreturnthestudentrecordfromtheresultcache.Intheoppositecase,the

studentrecordwillbeselectedfromtheSTUDENTtableandaddedtothecacheforfuture
use.BecausetheresultcacheofthefunctionreliesontheSTUDENTtable,anychanges
appliedandcommittedontheSTUDENTtablewillinvalidateallcachedresultsforthe
get_student_recfunction.


MorePL/SQL-OnlyDataTypesCanCrossthePL/SQL-toSQLInterfaceClause
Inthisrelease,OraclehasextendedsupportofPL/SQL-onlydatatypestodynamicSQL
andclientprograms(OCIorJDBC).Forexample,youcanbindcollectionsvariables
whenusingtheEXECUTEIMMEDIATEstatementortheOPENFOR,FETCH,and
CLOSEstatements.ThistopiciscoveredingreaterdetailinLab18.3,BindingCollections
inSQLStatements,inChapter18.

ACCESSIBLEBYClause
AnoptionalACCESSIBLEBYclauseenablesyoutospecifyalistofPL/SQLunitsthat
mayaccessthePL/SQLunitbeingcreatedormodified.TheACCESSIBLEBYclauseis
typicallyaddedtothemoduleheader—forexample,tothefunctionorprocedureheader.
EachunitlistedintheACCESSIBLEBYclauseiscalledanaccessor,andtheclause
itselfisalsocalledawhitelist.Thisisdemonstratedinthefollowingexample(the
ACCESSIBLEBYclauseisshowninbold).
ForExampleProcedureCreatedwiththeACCESSIBLEBYClause
Clickheretoviewcodeimage
CREATEORREPLACEPROCEDUREtest_proc1
ACCESSIBLEBY(TEST_PROC2)
AS
BEGIN
DBMS_OUTPUT.PUT_LINE(‘TEST_PROC1’);
ENDtest_proc1;
/
CREATEORREPLACEPROCEDUREtest_proc2

AS
BEGIN
DBMS_OUTPUT.PUT_LINE(‘TEST_PROC2’);
test_proc1;
ENDtest_proc2;
/
—ExecuteTEST_PROC2
BEGIN
test_proc2;
END;
/
TEST_PROC2
TEST_PROC1
—ExecuteTEST_PROC1directly
BEGIN
test_proc1;
END;
/
ORA-06550:line2,column4:
PLS-00904:insufficientprivilegetoaccessobjectTEST_PROC1
ORA-06550:line2,column4:


PL/SQL:Statementignored

Inthisexample,therearetwoprocedures,test_proc1andtest_proc2,and
test_proc1iscreatedwiththeACCESSIBLEBYclause.Asaconsequence,
test_proc1maybeaccessedbytest_proc2only.Thisisdemonstratedbytwo
anonymousPL/SQLblocks.Thefirstblockexecutestest_proc2successfully.The
secondblockattemptstoexecutetest_proc1directlyand,asaresult,causesanerror.

Notethatbothprocedureswerecreatedwithinasingleschema(STUDENT),andthat
bothPL/SQLblockswereexecutedinthesinglesessionbytheschemaowner
(STUDENT).

FETCHFIRSTClause
TheFETCHFIRSTclauseisanewoptionalfeaturethatistypicallyusedwiththe“TopN”queriesasillustratedbythefollowingexample.TheENROLLMENTtableusedinthis
examplecontainsstudentregistrationdata.Eachstudentisidentifiedbyauniquestudent
IDandmayberegisteredformultiplecourses.TheFETCHFIRSTclauseisshownin
bold.
ForExampleUsingFETCHFIRSTClausewith“Top-N”Query
Clickheretoviewcodeimage
—SamplestudentIDsfromtheENROLLMENTtable
SELECTstudent_id
FROMenrollment;
STUDENT_ID
–––102
102
103
104
105
106
106
107
108
109
109
110
110

—“Top-N”queryreturnsstudentIDsforthe5studentsthatregisteredfor

themost
—courses
SELECTstudent_id,COUNT(*)courses
FROMenrollment
GROUPBYstudent_id
ORDERBYcoursesdesc
FETCHFIRST5ROWSONLY;
STUDENT_IDCOURSES
–––-––-


2144
1244
2323
2153
1843

NotethatFETCHFIRSTclausemayalsobeusedinconjunctionwiththeBULK
COLLECTINTOclauseasdemonstratedhere.TheFETCHFIRSTclauseisshownin
bold.
ForExampleUsingFETCHFIRSTClausewithBULKCOLLECTINTOClause
Clickheretoviewcodeimage
DECLARE
TYPEstudent_name_tabISTABLEOFVARCHAR2(100)INDEXBYPLS_INTEGER;
student_namesstudent_name_tab;
BEGIN
—Fetchingfirst20studentnamesonly
SELECTfirst_name||’‘||last_name
BULKCOLLECTINTOstudent_names
FROMstudent

FETCHFIRST20ROWSONLY;
DBMS_OUTPUT.PUT_LINE(‘Thereare‘||student_names.COUNT||’students’);
END;
/
Thereare20students

RolesCanBeGrantedtoPL/SQLPackagesandStandAloneSubprograms
StartingwithOracle12c,youareabletograntrolestoPL/SQLpackagesandstand-alone
subprograms.NotethatgrantingaroletoaPL/SQLpackageorstand-alonesubprogram
doesnotalteritscompilation.Instead,itaffectshowprivilegesrequiredbytheSQL
statementsthatareissuedbythePL/SQLunitatruntimearechecked.
ConsiderthefollowingexamplewheretheREADroleisgrantedtothefunction
get_student_name.
ForExampleGrantingREADRoletotheget_student_nameFunction
Clickheretoviewcodeimage
GRANTREADTOFUNCTIONget_student_name;


MoreDataTypesHavetheSameMaximumSizeinSQLand
PL/SQL
PriortoOracle12c,somedatatypeshaddifferentmaximumsizesinSQLandinPL/SQL.
Forexample,inSQLthemaximumsizeofNVARCHAR2was4000bytes,whereasin
PL/SQLitwas32,767bytes.StartingwithOracle12c,themaximumsizesofthe
VARCHAR2,NVARCHAR2,andRAWdatatypeshavebeenextendedto32,767forboth
SQLandPL/SQL.ToseethesemaximumsizesinSQL,theinitializationparameter
MAX_STRING_SIZEmustbesettoEXTENDED.

DatabaseTriggersonPluggableDatabases
Thepluggabledatabase(PDB)isoneofthecomponentsofOracle’smultitenant
architecture.Typicallyitisaportablecollectionofschemasandotherdatabaseobjects.

StartingwithOracle12c,youareabletocreateeventtriggersonPDBs.Detailed
informationontriggersisprovidedinChapters13and14.NotethatPDBsareoutsidethe
scopeofthisbook,butdetailedinformationonthemmaybefoundinOracle’sonline
AdministrationGuide.

LIBRARYCanBeDefinedasaDIRECTORYObjectandwith
aCREDENTIALClause
ALIBRARYisaschemaobjectassociatedwithasharedlibraryofanoperatingsystem.It
iscreatedwiththehelpoftheCREATEORREPLACELIBRARYstatement.A
DIRECTORYisalsoanobjectthatmapsanaliastoanactualdirectoryontheserverfile
system.TheDIRECTORYobjectiscoveredverybrieflyinChapter25aspartoftheinstall
processesforthePL/SQLProfilerAPIandPL/SQLHierarchicalProfiler.IntheOracle
12crelease,aLIBRARYobjectmaybedefinedasaDIRECTORYobjectwithanoptional
CREDENTIALclauseasshownhere.
ForExampleCreatingLIBRARYasDIRECTORYObject
Clickheretoviewcodeimage
CREATEORREPLACELIBRARYmy_libAS‘plsql_code’INmy_dir;

Inthisexample,theLIBRARYobjectmy_libiscreatedasaDIRECTORYobject.The
'plsql_code'isthenameofthedynamiclinklibrary(DDL)intheDIRECTORY
objectmy_dir.Notethatforthislibrarytobecreatedsuccessfully,theDIRECTORY
objectmy_dirmustbecreatedbeforehand.MoreinformationonLIBRARYand
DIRECTORYobjectscanbefoundinOracle’sonlineDatabasePL/SQLLanguage
Reference.


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

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