You are on page 1of 458

Oracle Database 11g: Develop PL/SQL Program Units

Volume I Student uide

l c ra O l, - On l ae rn Uste In e

, em ad .c

D!""#$ %&' (dition &)' September &''" D$*'$+

ra c O

le

.ut/or Lauran Ser/al 0ec/nical %ontributors and 1evie2ers .n3ulaponni .4/agule5s/mi %/ristian 6au2ens %/ristop/ 6urandt 7ar5o %esl3as 8anti %/ang Salome %lement Las4lo %4in5oc45i Ingrid Dela9a,e Steve :riedberg Laura ar4a ;oel oodman <anc, reenberg =anis/ Pa2ar 6rian Pottle 9elen 1obertson 0uli5a Srivastava 0ed >itiu5

%op,rig/t @ &''"A Oracle) .ll rig/ts reserved) Disclaimer 0/is document contains proprietar, inBormation and is protected b, cop,rig/t and ot/er intellectual propert, la2s) 8ou ma, cop, and print t/is document solel, Bor ,our o2n use in an Oracle training course) 0/e document ma, not be modiBied or altered in an, 2a,) (Ccept 2/ere ,our use constitutes DBair useD under cop,rig/t la2A ,ou ma, not useA s/areA do2nloadA uploadA cop,A printA displa,A perBormA reproduceA publis/A licenseA postA transmitA or distribute t/is document in 2/ole or in part 2it/out t/e eCpress aut/ori4ation oB Oracle)

0/e inBormation contained in t/is document is sub3ect to c/ange 2it/out notice) IB ,ou Bind an, problems in t/e documentA please report t/em in 2riting to: Oracle Universit,A +'' Oracle Par52a,A 1ed2ood S/oresA %aliBornia "!'$+ US.) 0/is document is not 2arranted to be errorEBree) 1estricted 1ig/ts <otice IB t/is documentation is delivered to t/e United States overnment or an,one using t/e documentation on be/alB oB t/e United States overnmentA t/e Bollo2ing notice is applicable: U)S) OV(1<=(<0 1I 90S 0/e U)S) overnmentFs rig/ts to useA modiB,A reproduceA releaseA perBormA displa,A or disclose t/ese training materials are restricted b, t/e terms oB t/e applicable Oracle license agreement and/or t/e applicable U)S) overnment contract) 0rademar5 <otice Oracle is a registered trademar5 oB Oracle %orporation and/or its aBBiliates) Ot/er names ma, be trademar5s oB t/eir respective o2ners)

(ditors .ri3it /os/ 1a3 ?umar Publis/ers Pavit/ran .d5a S/er,l Domingue

l c ra O l, - On le In l ae rn Uste e

, em ad .c

ra c O

%ontents

Introduction Lesson Ob3ectives IE& Lesson .genda IE* %ourse Ob3ectives IE! Suggested %ourse .genda IE+ Lesson .genda IEG 0/e 9uman 1esources H91I Sc/ema 0/at Is Used in 0/is %ourse IE# %lass .ccount InBormation IE" .ppendiCes Used in 0/is %ourse IE1' PL/SQL Development (nvironments IE11 >/at Is Oracle SQL DeveloperJ IE1& %oding PL/SQL in SQLKPlus IE1* %oding PL/SQL in Oracle ;Developer IE1! (nabling Output oB a PL/SQL 6loc5 IE1+ Lesson .genda IE1$ Oracle 11g SQL and PL/SQL Documentation IE1G .dditional 1esources IE1# Summar, IE1" Practice I Overvie2: etting Started IE&'

l
1

%reating Procedures Ob3ectives 1E& Lesson .genda 1E* %reating a =odulari4ed Subprogram Design 1E! %reating a La,ered Subprogram Design 1E+ =odulari4ing Development 2it/ PL/SQL 6loc5s 1E$ .non,mous 6loc5s: Overvie2 1EG PL/SQL 1unEtime .rc/itecture 1E# >/at .re PL/SQL SubprogramsJ 1E" 0/e 6eneBits oB Using PL/SQL Subprograms 1E1' DiBBerences 6et2een .non,mous 6loc5s and Subprograms 1E11 Lesson .genda 1E1& >/at .re ProceduresJ 1E1* %reating Procedures: Overvie2 1E1! %reating Procedures 2it/ t/e SQL %1(.0( O1 1(PL.%( Statement 1E1+ %reating Procedures Using SQL Developer 1E1$

c ra O l, - On

, em ad .c

ra c O

le

l ae rn Uste

iii

In

%ompiling Procedures and Displa,ing %ompilation (rrors in SQL Developer 1E1G %orrecting %ompilation (rrors in SQL Developer 1E1# <aming %onventions oB PL/SQL Structures Used in 0/is %ourse 1E1" >/at .re Parameters and Parameter =odesJ 1E&' :ormal and .ctual Parameters 1E&1 Procedural Parameter =odes 1E&& %omparing t/e Parameter =odes 1E&* Using t/e I< Parameter =ode: (Cample 1E&!

Using t/e OU0 Parameter =ode: (Cample 1E&+ Using t/e I< OU0 Parameter =ode: (Cample 1E&$ Vie2ing t/e OU0 Parameters: Using t/e D6=SLOU0PU0)PU0LLI<( Subroutine 1E&G Vie2ing OU0 Parameters: Using SQLKPlus 9ost Variables 1E&# .vailable <otations Bor Passing .ctual Parameters 1E&" Passing .ctual Parameters: %reating t/e addLdept Procedure 1E*' Passing .ctual Parameters: (Camples 1E*1 Using t/e D(:.UL0 Option Bor t/e Parameters 1E*& %alling Procedures 1E*! %alling Procedures Using SQL Developer 1E*+ Lesson .genda 1E*$ 9andled (Cceptions 1E*G 9andled (Cceptions: (Cample 1E*# (Cceptions <ot 9andled 1E*" (Cceptions <ot 9andled: (Cample 1E!' 1emoving Procedures: Using t/e D1OP SQL Statement or SQL Developer 1E!1 Vie2ing Procedure InBormation Using t/e Data Dictionar, Vie2s 1E!& Vie2ing Procedures InBormation Using SQL Developer 1E!* Qui4 1E!! Summar, 1E!+ Practice 1 Overvie2: %reatingA %ompilingA and %alling Procedures 1E!$

&

ra c O

%reating :unctions and Debugging Subprograms Ob3ectives &E& Lesson .genda &E* Overvie2 oB Stored :unctions &E! %reating :unctions &E+ 0/e DiBBerence 6et2een Procedures and :unctions &E$ %reating and 1unning :unctions: Overvie2 &EG %reating and Invo5ing a Stored :unction Using t/e %1(.0( :U<%0IO< Statement: (Cample &E#

c ra O l, - On

, em ad .c

le

l ae rn Uste
iv

In

Using DiBBerent =et/ods Bor (Cecuting :unctions &E" %reating and %ompiling :unctions Using SQL Developer &E11 (Cecuting :unctions Using SQL Developer &E1& .dvantages oB UserEDeBined :unctions in SQL Statements &E1* Using a :unction in a SQL (Cpression: (Cample &E1! %alling UserEDeBined :unctions in SQL Statements &E1+ 1estrictions >/en %alling :unctions Brom SQL (Cpressions &E1$ %ontrolling Side (BBects >/en %alling :unctions Brom SQL (Cpressions &E1G 1estrictions on %alling :unctions Brom SQL: (Cample &E1# <amed and =iCed <otation Brom SQL &E1" <amed and =iCed <otation Brom SQL: (Cample &E&' 1emoving :unctions: Using t/e D1OP SQL Statement or SQL Developer &E&1 Vie2ing :unctions Using Data Dictionar, Vie2s &E&& Vie2ing :unctions InBormation Using SQL Developer &E&* Qui4 &E&! Practice &E1: Overvie2 &E&+ Lesson .genda &E&$ Debugging PL/SQL Subprograms Using t/e SQL Developer Debugger &E&G Debugging a Subprogram: Overvie2 &E&# 0/e Procedure or :unction %ode (diting 0ab &E&" 0/e Procedure or :unction 0ab 0oolbar &E*' 0/e Debugging M Log 0ab 0oolbar &E*1 .dditional 0abs &E** Debugging a Procedure (Cample: %reating a <e2 empLlist Procedure &E*!

Debugging a Procedure (Cample: %reating a <e2 getLlocation :unction &E*+ Setting 6rea5points and %ompiling empLlist Bor Debug =ode &E*$ %ompiling t/e getLlocation :unction Bor Debug =ode &E*G Debugging empLlist: Step Into H:GI t/e %ode &E*" Vie2ing t/e Data &E!1 =odiB,ing t/e Variables >/ile Debugging t/e %ode &E!& Debugging empLlist: Step Over t/e %ode &E!* Debugging empLlist: Step Out oB t/e %ode HS/iBt N :GI &E!! Debugging empLlist: 1un to %ursor H:!I &E!+ Debugging empLlist: Step to (nd oB =et/od &E!$ Debugging a Subprogram 1emotel,: Overvie2 &E!G Practice &E& Overvie2: Introduction to t/e SQL Developer Debugger &E!# Summar, &E!"

Debugging empLlist and (ntering Values Bor t/e P=.O1O>S Parameter &E*#

c ra O l, - On

, em ad .c

ra c O

le

l ae rn Uste

In

%reating Pac5ages Ob3ectives *E& Lesson .genda *E* >/at .re PL/SQL Pac5agesJ *E! .dvantages oB Using Pac5ages *E+ %omponents oB a PL/SQL Pac5age *EG Internal and (Cternal Visibilit, oB a Pac5ageFs %omponents *E# Developing PL/SQL Pac5ages: Overvie2 *E" Lesson .genda *E1' %reating t/e Pac5age SpeciBication: Using t/e %1(.0( P.%?. ( Statement *E11 %reating t/e Pac5age SpeciBication: Using SQL Developer *E1& %reating t/e Pac5age 6od,: Using SQL Developer *E1* (Cample oB a Pac5age SpeciBication: commLp5g *E1! %reating t/e Pac5age 6od, *E1+ (Cample oB a Pac5age 6od,: commLp5g *E1$ Invo5ing t/e Pac5age Subprograms: (Camples *E1G Invo5ing t/e Pac5age Subprograms: Using SQL Developer *E1# %reating and Using 6odiless Pac5ages *E1" 1emoving Pac5ages: Using SQL Developer or t/e SQL D1OP Statement *E&' Vie2ing Pac5ages Using t/e Data Dictionar, *E&1 Vie2ing Pac5ages Using SQL Developer *E&& uidelines Bor >riting Pac5ages *E&* Qui4 *E&! Summar, *E&+ Practice * Overvie2: %reating and Using Pac5ages *E&$

l
! >or5ing 2it/ Pac5ages Ob3ectives !E& Lesson .genda !E* Overloading Subprograms in PL/SQL !E! Overloading Procedures (Cample: %reating t/e Pac5age SpeciBication !E$ Overloading Procedures (Cample: %reating t/e Pac5age 6od, !EG Overloading and t/e S0.<D.1D Pac5age !E# Illegal Procedure 1eBerence !E" Using :or2ard Declarations to Solve Illegal Procedure 1eBerence !E1' Initiali4ing Pac5ages !E11 Using Pac5age :unctions in SQL !E1& %ontrolling Side (BBects oB PL/SQL Subprograms !E1* Pac5age :unction in SQL: (Cample !E1!

c ra O l, - On

, em ad .c

ra c O

le

l ae rn Uste
vi

In

Lesson .genda !E1+ Persistent State oB Pac5ages !E1$ Persistent State oB Pac5age Variables: (Cample !E1# Persistent State oB a Pac5age %ursor: (Cample !E1" (Cecuting t/e %U1SLP? Pac5age !E&1 Using .ssociative .rra,s in Pac5ages !E&& Qui4 !E&* Summar, !E&! Practice !: Overvie2 !E&+

Using OracleESupplied Pac5ages in .pplication Development Ob3ectives +E& Lesson .genda +E* Using OracleESupplied Pac5ages +E! (Camples oB Some OracleESupplied Pac5ages +E+ Lesson .genda +E$ 9o2 t/e D6=SLOU0PU0 Pac5age >or5s +EG

Using t/e U0LL:IL( Pac5age to Interact 2it/ Operating S,stem :iles +E# Some oB t/e U0LL:IL( Procedures and :unctions +E" :ile Processing Using t/e U0LL:IL( Pac5age: Overvie2 +E1' :OP(< and ISLOP(< :unctions: (Cample +E1& Using U0LL:IL(: (Cample +E1! >/at Is t/e U0LL=.IL Pac5ageJ +E1$ Summar, oB U0LL=.IL Subprograms +E1# Installing and Using U0LL=.IL +E1" 0/e S(<D Procedure S,ntaC +E&'

Using t/e .vailable Declared (Cceptions in t/e U0LL:IL( Pac5age +E11

Setting Up and Using t/e U0LL=.IL: Overvie2 +E1G

0/e S(<DL.00.%9L1.> Procedure +E&1 Sending (mail 2it/ a 6inar, .ttac/ment: (Cample +E&& 0/e S(<DL.00.%9LV.1%9.1& Procedure +E&! Sending (mail 2it/ a 0eCt .ttac/ment: (Cample +E&+ Qui4 +E&G Summar, +E&# Practice +: Overvie2 +E&"

c ra O l, - On

, em ad .c

ra c O

Using D,namic SQL Ob3ectives $E& Lesson .genda $E* (Cecution :lo2 oB SQL $E!

le

l ae rn Uste

vii

In

>or5ing 2it/ D,namic SQL $E+ Using D,namic SQL $E$ <ative D,namic SQL H<DSI $EG Using t/e (O(%U0( I==(DI.0( Statement $E# .vailable =et/ods Bor Using <DS $E" D,namic SQL 2it/ a DDL Statement: (Camples $E11 D,namic SQL 2it/ D=L Statements $E1& D,namic SQL 2it/ a SingleE1o2 Quer,: (Cample $E1* (Cecuting a PL/SQL .non,mous 6loc5 D,namicall, $E1! Using <ative D,namic SQL to %ompile PL/SQL %ode $E1+ Lesson .genda $E1$ Using t/e D6=SLSQL Pac5age $E1G

Using t/e D6=SLSQL Pac5age Subprograms $E1# Using D6=SLSQL 2it/ a D=L Statement: Deleting 1o2s $E&' Using D6=SLSQL 2it/ a Parameteri4ed D=L Statement $E&1 Qui4 $E&& Summar, $E&* Practice $ Overvie2: Using <ative D,namic SQL $E&!

Design %onsiderations Bor PL/SQL %ode Ob3ectives GE& Lesson .genda GE* Standardi4ing %onstants and (Cceptions GE! Standardi4ing (Cceptions GE+ Standardi4ing (Cception 9andling GE$ Standardi4ing %onstants GEG Local Subprograms GE# DeBinerFs 1ig/ts Versus Invo5erFs 1ig/ts GE" SpeciB,ing Invo5erFs 1ig/ts: Setting .U09ID to %U11(<0LUS(1 GE1' .utonomous 0ransactions GE11 :eatures oB .utonomous 0ransactions GE1& Using .utonomous 0ransactions: (Cample GE1* Lesson .genda GE1+ Using t/e <O%OP8 9int GE1$

(BBects oB t/e <O%OP8 9int GE1G

c ra O l, - On

, em ad .c

>/en Does t/e PL/SQL %ompiler Ignore t/e <O%OP8 9intJ GE1#

ra c O

Using t/e P.1.LL(LL(<.6L( 9int GE1" Using t/e %rossESession PL/SQL :unction 1esult %ac/e GE&' (nabling 1esultE%ac/ing Bor a :unction GE&1 Declaring and DeBining a 1esultE%ac/ed :unction: (Cample GE&&

le

l ae rn Uste
viii

In

Using t/e D(0(1=I<IS0I% %lause 2it/ :unctions GE&! Lesson .genda GE&+ Using t/e 1(0U1<I< %lause GE&$ Using 6ul5 6inding GE&G 6ul5 6inding: S,ntaC and ?e,2ords GE&# 6ul5 6inding :O1.LL: (Cample GE*'

Using 6UL? %OLL(%0 I<0O 2it/ Queries GE*& Using 6UL? %OLL(%0 I<0O 2it/ %ursors GE** Using 6UL? %OLL(%0 I<0O 2it/ a 1(0U1<I< %lause GE*! Using 6ul5 6inds in Sparse %ollections GE*+ Using 6ul5 6ind 2it/ IndeC .rra, GE*# Qui4 GE*" Summar, GE!' Practice G: Overvie2 GE!1

%reating 0riggers Ob3ectives #E& >/at .re 0riggersJ #E* DeBining 0riggers #E! 0rigger (vent 0,pes #E+ .pplication and Database 0riggers #E$ 6usiness .pplication Scenarios Bor Implementing 0riggers #EG .vailable 0rigger 0,pes #E# 0rigger (vent 0,pes and 6od, #E" %reating D=L 0riggers Using t/e %1(.0( 01I (1 Statement #E1' SpeciB,ing t/e 0rigger :iring H0imingI #E11 StatementELevel 0riggers Versus 1o2ELevel 0riggers #E1& %reating D=L 0riggers Using SQL Developer #E1* 0riggerE:iring SePuence: SingleE1o2 =anipulation #E1! 0riggerE:iring SePuence: =ultiro2 =anipulation #E1+ %reating a D=L Statement 0rigger (Cample: S(%U1(L(=P #E1$

0esting 0rigger S(%U1(L(=P Using %onditional Predicates %reating a D=L 1o2 0rigger Using OLD and <(> QualiBiers

c ra O l, - On
#E1G #E1# #E1" #E&'

, em ad .c

Using OLD and <(> QualiBiers: (Cample #E&1

ra c O

Using OLD and <(> QualiBiers: (Cample t/e Using .UDI0L(=P 0able #E&& Using t/e >9(< %lause to :ire a 1o2 0rigger 6ased on a %ondition #E&* Summar, oB t/e 0rigger (Cecution =odel #E&! Implementing an Integrit, %onstraint 2it/ an .Bter 0rigger #E&+

le

l ae rn Uste

iC

In

I<S0(.D O: 0riggers #E&$ %reating an I<S0(.D O: 0rigger: (Cample #E&G %reating an I<S0(.D O: 0rigger to PerBorm D=L on %ompleC Vie2s #E&# 0/e Status oB a 0rigger #E*' %reating a Disabled 0rigger #E*1 =anaging 0riggers Using t/e .L0(1 and D1OP SQL Statements #E*& =anaging 0riggers Using SQL Developer #E** 0esting 0riggers #E*! Vie2ing 0rigger InBormation #E*+ Using US(1L01I (1S #E*$ Qui4 #E*G Summar, #E*# Practice # Overvie2: %reating Statement and 1o2 0riggers #E*"

"

%reating %ompoundA DDLA and (vent Database 0riggers Ob3ectives "E& >/at Is a %ompound 0riggerJ "E* >or5ing 2it/ %ompound 0riggers "E! 0/e 6eneBits oB Using a %ompound 0rigger "E+ 0imingEPoint Sections oB a 0able %ompound 0rigger "E$ %ompound 0rigger Structure Bor 0ables "EG %ompound 0rigger Structure Bor Vie2s "E# %ompound 0rigger 1estrictions "E" 0rigger 1estrictions on =utating 0ables "E1' =utating 0able: (Cample "E11 Using a %ompound 0rigger to 1esolve t/e =utating 0able (rror "E1* %reating 0riggers on DDL Statements "E1+ %reating DatabaseE(vent 0riggers "E1$ %reating 0riggers on S,stem (vents "E1G LO O< and LO O:: 0riggers: (Cample "E1#

%.LL Statements in 0riggers "E1" 6eneBits oB DatabaseE(vent 0riggers "E&' S,stem Privileges 1ePuired to =anage 0riggers "E&1 uidelines Bor Designing 0riggers "E&& Qui4 "E&* Summar, "E&! Practice ": Overvie2 "E&+

c ra O l, - On

, em ad .c

ra c O

le In

l ae rn Uste
C

1' Using t/e PL/SQL %ompiler Ob3ectives 1'E& Lesson .genda 1'E* Initiali4ation Parameters Bor PL/SQL %ompilation 1'E! Using t/e Initiali4ation Parameters Bor PL/SQL %ompilation 1'E+ 0/e %ompiler Settings 1'EG Displa,ing t/e PL/SQL Initiali4ation Parameters 1'E# Displa,ing and Setting t/e PL/SQL Initiali4ation Parameters 1'E" %/anging PL/SQL Initiali4ation Parameters: (Cample 1'E1' Lesson .genda 1'E11 Overvie2 oB PL/SQL %ompileE0ime >arnings Bor Subprograms 1'E1& 6eneBits oB %ompiler >arnings1'E1! %ategories oB PL/SQL %ompileE0ime >arning =essages 1'E1+ Setting t/e >arning =essages Levels 1'E1$ Setting %ompiler >arning Levels: Using PLSQLL>.1<I< S 1'E1G

Setting %ompiler >arning Levels: Using PLSQLL>.1<I< SA (Camples 1'E1# Setting %ompiler >arning Levels: Using PLSQLL>.1<I< S in SQL Developer 1'E1" Vie2ing t/e %urrent Setting oB PLSQLL>.1<I< S 1'E&' Vie2ing t/e %ompiler >arnings: Using SQL DeveloperA SQLKPlusA or Data Dictionar, Vie2s 1'E&1 SQLKPlus >arning =essages: (Cample 1'E&& uidelines Bor Using PLSQLL>.1<I< S 1'E&* Lesson .genda 1'E&! Setting %ompiler >arning Levels: Using t/e D6=SL>.1<I< Pac5age 1'E&+

Using t/e D6=SL>.1<I< Pac5age Subprograms 1'E&G

0/e D6=SL>.1<I< Procedures: S,ntaCA ParametersA and .llo2ed Values 1'E&# 0/e D6=SL>.1<I< Procedures: (Cample 1'E&"

0/e D6=SL>.1<I< :unctions: S,ntaCA ParametersA and .llo2ed Values 1'E*' 0/e D6=SL>.1<I< :unctions: (Cample 1'E*1 Using D6=SL>.1<I< : (Cample 1'E*& Using t/e PL> '$''" >arning =essage 1'E*! 0/e PL> '$''" >arning: (Cample 1'E*+ Qui4 1'E*$ Summar, 1'E*G Practice 1': Overvie2 1'E*#

c ra O l, - On

, em ad .c

ra c O

le

l ae rn Uste

Ci

In

11 =anaging PL/SQL %ode Ob3ectives 11E& Lesson .genda 11E* >/at Is %onditional %ompilationJ 11E! 9o2 Does %onditional %ompilation >or5J 11E+ Using Selection Directives 11E$ Using PredeBined and UserEDeBined InPuir, Directives 11EG 0/e PLSQLL%%:L. S Parameter and t/e InPuir, Directive 11E#

Displa,ing t/e PLSQLL%%:L. S Initiali4ation Parameter Setting 11E" 0/e PLSQLL%%:L. S Parameter and t/e InPuir, Directive: (Cample 11E1' Using %onditional %ompilation (rror Directives to 1aise UserEDeBined (rrors 11E11 Using Static (Cpressions 2it/ %onditional %ompilation 11E1& 0/e D6=SLD6LV(1SIO< Pac5age: 6oolean %onstants 11E1* 0/e D6=SLD6LV(1SIO< Pac5age %onstants 11E1! Using %onditional %ompilation 2it/ Database Versions: (Cample 11E1+ Using D6=SLP1(P1O%(SSO1 Procedures to Print or 1etrieve Source 0eCt 11E1G Lesson .genda 11E1# >/at Is ObBuscationJ 11E1" 6eneBits oB ObBuscating 11E&' >/atFs <e2 in D,namic ObBuscating Since Oracle 1'gJ 11E&1 <onobBuscated PL/SQL %ode: (Cample 11E&& ObBuscated PL/SQL %ode: (Cample 11E&* D,namic ObBuscation: (Cample 11E&! 0/e PL/SQL >rapper Utilit, 11E&+ 1unning t/e >rapper Utilit, 11E&$ 1esults oB >rapping 11E&G uidelines Bor >rapping 11E&# D6=SLDDL Pac5age Versus t/e >rap Utilit, 11E&" Qui4 11E*' Summar, 11E*1 Practice 11: Overvie2 11E*&

ra c O

1& =anaging Dependencies Ob3ectives 1&E& Overvie2 oB Sc/ema Ob3ect Dependencies 1&E* Dependencies 1&E! Direct Local Dependencies 1&E+

c ra O l, - On

, em ad .c

le

l ae rn Uste
Cii

In

Quer,ing Direct Ob3ect Dependencies: Using t/e US(1LD(P(<D(<%I(S Vie2 1&E$ Quer,ing an Ob3ectFs Status 1&EG Invalidation oB Dependent Ob3ects 1&E# Sc/ema Ob3ect %/ange 0/at Invalidates Some Dependents: (Cample 1&E" Displa,ing Direct and Indirect Dependencies 1&E11 Displa,ing Dependencies Using t/e D(P01(( Vie2 1&E1& =ore Precise Dependenc, =etadata in Oracle Database 11g 1&E1* :ineE rained Dependenc, =anagement 1&E1! :ineE rained Dependenc, =anagement: (Cample 1 1&E1+ :ineE rained Dependenc, =anagement: (Cample & 1&E1G %/anges to S,non,m Dependencies 1&E1# =aintaining Valid PL/SQL Program Units and Vie2s 1&E1" .not/er Scenario oB Local Dependencies 1&E&' uidelines Bor 1educing Invalidation 1&E&1 Ob3ect 1evalidation 1&E&& 1emote Dependencies 1&E&* %oncepts oB 1emote Dependencies 1&E&! Setting t/e 1(=O0(LD(P(<D(<%I(SL=OD( Parameter 1&E&+ 1emote Procedure 6 %ompiles at #:'' .= 1&E&$ Local Procedure . %ompiles at ":'' .= 1&E&G (Cecute Procedure . 1&E&# 1emote Procedure 6 1ecompiled at 11:'' .= 1&E&" (Cecute Procedure . 1&E*' Signature =ode 1&E*1 1ecompiling a PL/SQL Program Unit 1&E*& UnsuccessBul 1ecompilation 1&E** SuccessBul 1ecompilation 1&E*! 1ecompiling Procedures 1&E*+ Pac5ages and Dependencies: Subprogram 1eBerences t/e Pac5age 1&E*$ Pac5ages and Dependencies: Pac5age Subprogram 1eBerences Procedure 1&E*G Qui4 1&E*# Summar, 1&E*" Practice 1& Overvie2: =anaging Dependencies in 8our Sc/ema 1&E!'

c ra O l, - On
.ppendiC .: Practices and Solutions

, em ad .c

ra c O

.ppendiC .P: .dditional Practices and Solutions .ppendiC 6: 0able Descriptions

le

l ae rn Uste

Ciii

In

.ppendiC %: Using SQL Developer Ob3ectives %E& >/at Is Oracle SQL DeveloperJ %E* SpeciBications oB SQL Developer %E! SQL Developer 1)+ InterBace %E+ %reating a Database %onnection %EG 6ro2sing Database Ob3ects %E1' Displa,ing t/e 0able Structure %E11 6ro2sing :iles %E1& %reating a Sc/ema Ob3ect %E1* %reating a <e2 0able: (Cample %E1! Using t/e SQL >or5s/eet %E1+ (Cecuting SQL Statements %E1# Saving SQL Scripts %E1" (Cecuting Saved Script :iles: =et/od 1 %E&' (Cecuting Saved Script :iles: =et/od & %E&1 :ormatting t/e SQL %ode %E&& Using Snippets %E&* Using Snippets: (Cample %E&! Debugging Procedures and :unctions %E&+ Database 1eporting %E&$ %reating a UserEDeBined 1eport %E&G Searc/ (ngines and (Cternal 0ools %E&# Setting PreBerences %E&" 1esetting t/e SQL Developer La,out %E*' Summar, %E*1

l
.ppendiC D: Using SQLKPlus Ob3ectives DE& SQL and SQLKPlus Interaction DE* SQL Statements Versus SQLKPlus %ommands DE! Overvie2 oB SQLKPlus DE+ Logging In to SQLKPlus DE$ Displa,ing t/e 0able Structure DEG SQLKPlus (diting %ommands DE" Using LIS0A nA and .PP(<D DE11

c ra O l, - On

, em ad .c

ra c O

le In

Using t/e %9.< ( %ommand DE1& SQLKPlus :ile %ommands DE1* Using t/e S.V( and S0.10 %ommands DE1!

l ae rn Uste
Civ

S(1V(1OU0PU0 %ommand DE1+ Using t/e SQLKPlus SPOOL %ommand DE1$ Using t/e .U0O01.%( %ommand DE1G Summar, DE1# .ppendiC (: Using ;Developer Ob3ectives (E& Oracle ;Developer (E* Database <avigator (E! %reating a %onnection (E+ 6ro2sing Database Ob3ects (E$ (Cecuting SQL Statements (EG %reating Program Units (E# %ompiling (E" 1unning a Program Unit (E1' Dropping a Program Unit (E11 Structure >indo2 (E1& (ditor >indo2 (E1* .pplication <avigator (E1! Deplo,ing ;ava Stored Procedures (E1+ Publis/ing ;ava to PL/SQL (E1$ 9o2 %an I Learn =ore .bout ;Developer 11g J (E1G Summar, (E1#

.ppendiC :: 1evie2 oB PL/SQL Ob3ectives :E& 6loc5 Structure Bor .non,mous PL/SQL 6loc5s :E* Declaring PL/SQL Variables :E! Declaring Variables 2it/ t/e Q08P( .ttribute: (Camples :E+ %reating a PL/SQL 1ecord :E$ Q1O>08P( .ttribute: (Camples :EG %reating a PL/SQL 0able :E# S(L(%0 Statements in PL/SQL: (Cample :E" Inserting Data: (Cample :E1' Updating Data: (Cample :E11 Deleting Data: (Cample :E1& %ontrolling 0ransactions 2it/ t/e %O==I0 and 1OLL6.%? Statements :E1*

c ra O l, - On

, em ad .c

ra c O

I:A 09(<A and (LSI: Statements: (Cample :E1! 6asic Loop: (Cample :E1+ :O1 Loop: (Cample :E1$

le

l ae rn Uste

Cv

In

>9IL( Loop: (Cample :E1G SQL Implicit %ursor .ttributes :E1# %ontrolling (Cplicit %ursors :E1" %ontrolling (Cplicit %ursors: Declaring t/e %ursor :E&' %ontrolling (Cplicit %ursors: Opening t/e %ursor :E&1 %ontrolling (Cplicit %ursors: :etc/ing Data Brom t/e %ursor :E&& %ontrolling (Cplicit %ursors: %losing t/e %ursor :E&* (Cplicit %ursor .ttributes :E&! %ursor :O1 Loops: (Cample :E&+

:O1 UPD.0( %lause: (Cample :E&$ >9(1( %U11(<0 O: %lause: (Cample :E&G 0rapping PredeBined Oracle Server (rrors :E&# 0rapping PredeBined Oracle Server (rrors: (Cample :E&" <onEPredeBined (rror :E*' UserEDeBined (Cceptions: (Cample :E*1 1.IS(L.PPLI%.0IO<L(11O1 Procedure :E*& Summar, :E*!

.ppendiC : Studies Bor Implementing 0riggers Ob3ectives E& %ontrolling Securit, >it/in t/e Server E* %ontrolling Securit, 2it/ a Database 0rigger E! (nBorcing Data Integrit, >it/in t/e Server E+ Protecting Data Integrit, 2it/ a 0rigger E$ (nBorcing 1eBerential Integrit, >it/in t/e Server EG Protecting 1eBerential Integrit, 2it/ a 0rigger E# 1eplicating a 0able >it/in t/e Server E" 1eplicating a 0able 2it/ a 0rigger E1' %omputing Derived Data >it/in t/e Server E11 %omputing Derived Values 2it/ a 0rigger E1& Logging (vents 2it/ a 0rigger E1* Summar, E1+

l e

.ppendiC 9: Using t/e D6=SLS%9(DUL(1 and 90P Pac5ages Ob3ectives 9E& enerating >eb Pages 2it/ t/e 90P Pac5age 9E* Using t/e 90P Pac5age Procedures 9E! %reating an 90=L :ile 2it/ SQLKPlus 9E+ 0/e D6=SLS%9(DUL(1 Pac5age 9E$ %reating a ;ob 9E#

c ra O l, - On

, em ad .c

ra c O

le

l ae rn Uste
Cvi

In

%reating a ;ob 2it/ Inline Parameters 9E" %reating a ;ob Using a Program 9E1' %reating a ;ob Bor a Program 2it/ .rguments 9E11 %reating a ;ob Using a Sc/edule 9E1& Setting t/e 1epeat Interval Bor a ;ob 9E1* %reating a ;ob Using a <amed Program and Sc/edule 9E1! =anaging ;obs 9E1+ Data Dictionar, Vie2s 9E1$ Summar, 9E1G

l c ra O l, - On ra c O le In l ae rn Uste e

, em ad .c

Cvii

l c ra O l, - On ra c O le In l ae rn Uste
Cviii

, em ad .c

Introduction

%op,rig/t @ &''"A Oracle) .ll rig/ts reserved)

l c ra O l, - On ra c O le In l ae rn Uste e

, em ad .c

Lesson Ob3ectives
.Bter completing t/is lessonA ,ou s/ould be able to do t/e Bollo2ing: Discuss t/e goals oB t/e course IdentiB, t/e available environments t/at can be used in t/is course Describe t/e database sc/ema and tables t/at are used in t/e course List t/e available documentation and resources

%op,rig/t @ &''"A Oracle) .ll rig/ts reserved)

Lesson .im PL/SQL supports man, program constructs) In t/is lessonA ,ou revie2 program units in t/e Borm oB anon,mous bloc5sA and ,ou are introduced to named PL/SQL bloc5s) <amed PL/SQL bloc5s are also reBerred to as subprograms) <amed PL/SQL bloc5s include procedures and Bunctions) 0/e tables Brom t/e 9uman 1esources H91I sc/ema H2/ic/ is used Bor t/e practices in t/is courseI are brieBl, discussed) 0/e development tools Bor 2ritingA testingA and debugging PL/SQL are listed)

c ra O l, - On

, em ad .c

ra c O

le In

l ae rn Uste

Oracle Database 11g: Develop PL/SQL Program Units I E &

Lesson .genda
%ourse ob3ectives and course agenda 0/e sc/ema and appendiCes used in t/is course and t/e available PL/SQL development environments in t/is course Oracle 11g documentation and additional resources

%op,rig/t @ &''"A Oracle) .ll rig/ts reserved)

l c ra O l, - On ra c O le In l ae rn Uste e

, em ad .c

Oracle Database 11g: Develop PL/SQL Program Units I E *

%ourse Ob3ectives
.Bter completing t/is courseA ,ou s/ould be able to do t/e Bollo2ing: %reateA eCecuteA and maintain:
M Procedures and Bunctions 2it/ OU0 parameters M Pac5age constructs M Database triggers

=anage PL/SQL subprograms and triggers Use a subset oB OracleEsupplied pac5ages to generate screen and Bile output IdentiB, various tec/niPues t/at impact ,our PL/SQL code design considerations Use t/e PL/SQL compilerA manage PL/SQL codeA and manage dependencies

%op,rig/t @ &''"A Oracle) .ll rig/ts reserved)

%ourse Ob3ectives 8ou can develop modulari4ed applications 2it/ database procedures b, using database ob3ects suc/ as t/e Bollo2ing: Procedures and Bunctions Pac5ages Database triggers =odular applications improve: :unctionalit, Securit, Overall perBormance

c ra O l, - On

, em ad .c

ra c O

le In

l ae rn Uste

Oracle Database 11g: Develop PL/SQL Program Units I E !

Suggested %ourse .genda


Da, 1: Lesson I: Introduction Lesson 1: %reating Procedures Lesson &: %reating :unctions Lesson *: %reating Pac5ages Lesson !: >or5ing 2it/ Pac5ages Da, &: Lesson +: Using OracleESupplied Pac5ages in .pplication Development Lesson $: Using D,namic SQL Lesson G: Design %onsiderations Bor PL/SQL %ode Lesson #: %reating 0riggers

%op,rig/t @ &''"A Oracle) .ll rig/ts reserved)

l c ra O l, - On ra c O le In l ae rn Uste e

, em ad .c

Oracle Database 11g: Develop PL/SQL Program Units I E +

Suggested %ourse .genda


Da, *: Lesson ": %reating %ompoundA DDLA and (vent Database 0riggers Lesson 1': Using t/e PL/SQL %ompiler Lesson 11: =anaging PL/SQL %ode Lesson 1&: =anaging Dependencies

%op,rig/t @ &''"A Oracle) .ll rig/ts reserved)

l c ra O l, - On ra c O le In l ae rn Uste e

, em ad .c

Oracle Database 11g: Develop PL/SQL Program Units I E $

Lesson .genda
%ourse ob3ectives and course agenda 0/e sc/ema and appendiCes used in t/is course and t/e available PL/SQL development environments in t/is course Oracle 11g documentation and additional resources

%op,rig/t @ &''"A Oracle) .ll rig/ts reserved)

l c ra O l, - On ra c O le In l ae rn Uste e

, em ad .c

Oracle Database 11g: Develop PL/SQL Program Units I E G

0/e 9uman 1esources H91I Sc/ema 0/at Is Used in 0/is %ourse

D(P.10=(<0S
departmentLid departmentLname managerLid locationLid

LO%.0IO<S
locationLid streetLaddress postalLcode cit, stateLprovince countr,Lid

;O6L9IS0O18
emplo,eeLid startLdate endLdate 3obLid departmentLid

(=PLO8((S
emplo,eeLid BirstLname lastLname email p/oneLnumber /ireLdate 3obLid salar, commissionLpct managerLid departmentLid

%OU<01I(S
countr,Lid countr,Lname regionLid

3obLid 3obLtitle minLsalar, maCLsalar,

;O6S

1( IO<S

%op,rig/t @ &''"A Oracle) .ll rig/ts reserved)

0/e 9uman 1esources H91I Sc/ema Description 0/e 9uman 1esources H91I sc/ema is part oB Oracle Sample Sc/emas t/at can be installed in an Oracle database) 0/e practice sessions in t/is course use data Brom t/e 91 sc/ema) 0able Descriptions 1( IO<S contains ro2s t/at represent a region suc/ as .mericasA .siaA and so on) %OU<01I(S contains ro2s Bor countriesA eac/ oB 2/ic/ is associated 2it/ a region) LO%.0IO<S contains t/e speciBic address oB a speciBic oBBiceA 2are/ouseA or production site oB a compan, in a particular countr,) D(P.10=(<0S s/o2s details about t/e departments in 2/ic/ emplo,ees 2or5) (ac/ department ma, /ave a relations/ip representing t/e department manager in t/e (=PLO8((S table) (=PLO8((S contains details about eac/ emplo,ee 2or5ing Bor a department) Some emplo,ees ma, not be assigned to an, department) ;O6S contains t/e 3ob t,pes t/at can be /eld b, eac/ emplo,ee) ;O6L9IS0O18 contains t/e 3ob /istor, oB t/e emplo,ees) IB an emplo,ee c/anges departments 2it/in a 3ob or c/anges 3obs 2it/in a departmentA a ne2 ro2 is inserted into t/is table 2it/ t/e old 3ob inBormation oB t/e emplo,ee)

c ra O l, - On

, em ad .c

regionLid regionLname

ra c O

le

l ae rn Uste

Oracle Database 11g: Develop PL/SQL Program Units I E #

In

%lass .ccount InBormation


%loned 91 account IDs are set up Bor ,ou) 8our account IDs are ora$1 or ora$&) 0/e pass2ord matc/es ,our account ID) (ac/ mac/ine is assigned one account) 0/e instructor /as a separate ID)

%op,rig/t @ &''"A Oracle) .ll rig/ts reserved)

<ote: Use eit/er account ID ora$1 or ora$&)

l e

c ra O l, - On ra c O le In l ae rn Uste

, em ad .c

Oracle Database 11g: Develop PL/SQL Program Units I E "

.ppendiCes Used in 0/is %ourse


.ppendiC .: Practices and Solutions .ppendiC .P: .dditional Practices and Solutions .ppendiC 6: 0able Descriptions .ppendiC %: Using SQL Developer .ppendiC D: Using SQLKPlus .ppendiC (: 1evie2 oB ;Developer .ppendiC :: 1evie2 oB PL/SQL .ppendiC : Studies Bor Implementing 0riggers .ppendiC 9: Using t/e D6=SLS%9(DUL(1 and 90P Pac5ages

%op,rig/t @ &''"A Oracle) .ll rig/ts reserved)

l c ra O l, - On ra c O le In l ae rn Uste e

, em ad .c

Oracle Database 11g: Develop PL/SQL Program Units I E 1'

PL/SQL Development (nvironments


0/is course setup provides t/e Bollo2ing tools Bor developing PL/SQL code: Oracle SQL Developer Hused in t/is courseI Oracle SQLKPlus Oracle ;Developer ID(

%op,rig/t @ &''"A Oracle) .ll rig/ts reserved)

PL/SQL Development (nvironments 0/ere are man, tools t/at provide an environment Bor developing PL/SQL code) Oracle provides several tools t/at can be used to 2rite PL/SQL code) Some oB t/e development tools t/at are available Bor use in t/is course are: Oracle SQL Developer: . grap/ical tool Oracle SQLKPlus: . 2indo2 or commandEline application Oracle ;Developer: . 2indo2Ebased integrated development environment HID(I <ote: 0/e code and screen eCamples presented in t/e course notes 2ere generated Brom output in t/e SQL Developer environment)

c ra O l, - On

, em ad .c

ra c O

le In

l ae rn Uste

Oracle Database 11g: Develop PL/SQL Program Units I E 11

>/at Is Oracle SQL DeveloperJ


Oracle SQL Developer is a Bree grap/ical tool t/at en/ances productivit, and simpliBies database development tas5s) 8ou can connect to an, target Oracle database sc/ema using standard Oracle database aut/entication) 8ou use SQL Developer in t/is course) .ppendiC % contains details about using SQL Developer)

SQL Developer
%op,rig/t @ &''"A Oracle) .ll rig/ts reserved)

>/at Is Oracle SQL DeveloperJ Oracle SQL Developer is a Bree grap/ical tool designed to improve ,our productivit, and simpliB, t/e development oB ever,da, database tas5s) >it/ 3ust a Be2 clic5sA ,ou can easil, create and maintain stored proceduresA test SQL statementsA and vie2 optimi4er plans) SQL DeveloperA t/e visual tool Bor database developmentA simpliBies t/e Bollo2ing tas5s: 6ro2sing and managing database ob3ects (Cecuting SQL statements and scripts (diting and debugging PL/SQL statements %reating reports 8ou can connect to an, target Oracle database sc/ema using standard Oracle database aut/entication) >/en connectedA ,ou can perBorm operations on ob3ects in t/e database) <ote: .ppendiC % oB t/is course provides an introduction to using t/e SQL Developer interBace) See t/e appendiC no2 Bor inBormation about creating a database connection and interacting 2it/ data using SQL and PL/SQLA among ot/er topics)

c ra O l, - On

, em ad .c

ra c O

le

l ae rn Uste

Oracle Database 11g: Develop PL/SQL Program Units I E 1&

In

%oding PL/SQL in SQLKPlus

%op,rig/t @ &''"A Oracle) .ll rig/ts reserved)

%oding PL/SQL in SQLKPlus Oracle SQLKPlus is a grap/ical user interBace H UII or commandEline application t/at enables ,ou to submit SQL statements and PL/SQL bloc5s Bor eCecution and receive t/e results in an application or command 2indo2) SQLKPlus is: S/ipped 2it/ t/e database Installed on a client and on t/e database server s,stem .ccessed Brom an icon or t/e command line >/en coding PL/SQL subprograms using SQLKPlusA remember t/e Bollo2ing: 8ou create subprograms b, using t/e %1(.0( SQL statement) 8ou eCecute subprograms b, using eit/er an anon,mous PL/SQL bloc5 or t/e (O(%U0( command) IB ,ou use t/e D6=SLOU0PU0 pac5age procedures to print teCt to t/e screenA ,ou must Birst eCecute t/e S(0 S(1V(1OU0PU0 O< command in ,our session) <ote: :or more inBormation about /o2 to use SQLKPlusA see .ppendiC D)

c ra O l, - On

, em ad .c

ra c O

le

l ae rn Uste

Oracle Database 11g: Develop PL/SQL Program Units I E 1*

In

%oding PL/SQL in Oracle ;Developer

%op,rig/t @ &''"A Oracle) .ll rig/ts reserved)

%oding PL/SQL in Oracle ;Developer Oracle ;Developer allo2s developers to createA editA testA and debug PL/SQL code b, using a sop/isticated UI) Oracle ;Developer is a part oB Oracle Developer Suite and is also available as a separate product) >/en coding PL/SQL in ;DeveloperA consider t/e Bollo2ing: 8ou Birst create a database connection to enable ;Developer to access a database sc/ema o2ner Bor t/e subprograms) 8ou can t/en use ;Developer conteCt menus on t/e Database connection to create a ne2 subprogram construct using t/e builtEin ;Developer %ode (ditor) 8ou invo5e a subprogram b, using a 1un command on t/e conteCt menu Bor t/e named subprogram) 0/e output appears in t/e ;Developer Log =essage 2indo2A as s/o2n in t/e lo2er portion oB t/e screens/ot) <ote: ;Developer provides colorEcoding s,ntaC in t/e ;Developer %ode (ditor and is sensitive to PL/SQL language constructs and statements) :or more inBormation about /o2 to use ;DeveloperA see .ppendiC ()

c ra O l, - On

, em ad .c

ra c O

le

l ae rn Uste

Oracle Database 11g: Develop PL/SQL Program Units I E 1!

In

(nabling Output oB a PL/SQL 6loc5


1) 0o enable output in SQL DeveloperA eCecute t/e Bollo2ing command beBore running t/e PL/SQL bloc5:
S(0 S(1V(1OU0PU0 O<R

&) Use t/e predeBined D6=SLOU0PU0 Oracle pac5age and its procedure to displa, t/e output as Bollo2s:
M D6=SLOU0PU0)PU0LLI<( D6=SLOU0PU0)PU0LLI<(HS0/e :irst <ame oB t/e (mplo,ee is S TT vLBnameIR )))

%op,rig/t @ &''"A Oracle) .ll rig/ts reserved)

(nabling Output oB a PL/SQL 6loc5 In t/e eCample s/o2n in t/e previous slideA a value is stored in t/e vLBname variable) 9o2everA t/e value /as not been printed)

PL/SQL does not /ave builtEin input or output Bunctionalit,) 0/ereBoreA ,ou need to use predeBined Oracle pac5ages Bor input and output) 0o generate outputA ,ou must perBorm t/e Bollo2ing: 1) (Cecute t/e Bollo2ing SQL command:
S(0 S(1V(1OU0PU0 O<

<ote: 0o enable output in SQLKPlusA ,ou must eCplicitl, issue t/e S(0 S(1V(1OU0PU0 O< command) &) In t/e PL/SQL bloc5A use t/e PU0LLI<( procedure oB t/e D6=SLOU0PU0 pac5age to displa, t/e output) Pass t/e value t/at /as to be printed as argument to t/is procedure Has s/o2n in t/e slideI) 0/e procedure t/en outputs t/e argument)

c ra O l, - On

, em ad .c

ra c O

le

l ae rn Uste

Oracle Database 11g: Develop PL/SQL Program Units I E 1+

In

Lesson .genda
%ourse ob3ectives and course agenda 0/e sc/ema and appendices used in t/is course and t/e available PL/SQL development environments in t/is course Oracle 11g documentation and additional resources

%op,rig/t @ &''"A Oracle) .ll rig/ts reserved)

l c ra O l, - On ra c O le In l ae rn Uste e

, em ad .c

Oracle Database 11g: Develop PL/SQL Program Units I E 1$

Oracle 11g SQL and PL/SQL Documentation


Oracle Database <e2 :eatures uide 11g 1elease & H11)&I Oracle Database .dvanced .pplication DeveloperFs uide 11g 1elease & H11)&I Oracle Database PL/SQL Language 1eBerence 11g 1elease & H11)&I Oracle Database 1eBerence 11g 1elease & H11)&I Oracle Database SQL Language 1eBerence 11g 1elease & H11)&I Oracle Database %oncepts 11g 1elease & H11)&I Oracle Database PL/SQL Pac5ages and 0,pes 1eBerence 11g 1elease & H11)&I Oracle Database SQL Developer UserFs uide 1elease 1)+

%op,rig/t @ &''"A Oracle) .ll rig/ts reserved)

Oracle 11g SQL and PL/SQL Documentation <avigate to /ttp://222)oracle)com/pls/db111//omepage and clic5 t/e =aster 6oo5 List lin5 in t/e leBt Brame)

c ra O l, - On

, em ad .c

ra c O

le In

l ae rn Uste

Oracle Database 11g: Develop PL/SQL Program Units I E 1G

.dditional 1esources
:or additional inBormation about t/e ne2 Oracle 11g SQL and PL/SQL ne2 BeaturesA reBer to t/e Bollo2ing: Oracle Database 11g: <e2 :eatures eStudies Oracle b, (Cample HO6(I series: Oracle Database 11g:
M /ttp://222)oracle)com/tec/nolog,/obe/11gr1Ldb/admin/11gr1db)/tml

>/atFs <e2 in PL/SQL in Oracle Database 11g on t/e Oracle 0ec/nolog, <et2or5 HO0<I:
M /ttp://222)oracle)com/tec/nolog,/tec//plLsPl/

%op,rig/t @ &''"A Oracle) .ll rig/ts reserved)

l c ra O l, - On ra c O le In l ae rn Uste e

, em ad .c

Oracle Database 11g: Develop PL/SQL Program Units I E 1#

Summar,
In t/is lessonA ,ou s/ould /ave learned /o2 to: Discuss t/e goals oB t/e course IdentiB, t/e available environments t/at can be used in t/is course Describe t/e database sc/ema and tables t/at are used in t/e course List t/e available documentation and resources

%op,rig/t @ &''"A Oracle) .ll rig/ts reserved)

Summar, 0/e PL/SQL language provides diBBerent program constructs Bor bloc5s oB reusable code) Unnamed or anon,mous PL/SQL bloc5s can be used to invo5e SQL and PL/SQL actionsA proceduresA BunctionsA and pac5age components) <amed PL/SQL bloc5sA ot/er2ise 5no2n as subprogramsA include: Procedures :unctions Pac5age procedures and Bunctions 0riggers Oracle supplies several tools to develop ,our PL/SQL Bunctionalit,) Oracle provides a clientE side or middleEtier PL/SQL runEtime environment Bor Oracle :orms and Oracle 1eportsA and provides a PL/SQL runEtime engine inside t/e Oracle database) Procedures and Bunctions inside t/e database can be invo5ed Brom an, application code t/at can connect to an Oracle database and eCecute PL/SQL code)

c ra O l, - On

, em ad .c

ra c O

le

l ae rn Uste

Oracle Database 11g: Develop PL/SQL Program Units I E 1"

In

Practice I Overvie2: etting Started


0/is practice covers t/e Bollo2ing topics: 1evie2ing t/e available SQL Developer resources Starting SQL Developer and creating a ne2 database connection and bro2sing ,our sc/ema tables Setting some SQL Developer preBerences (Cecuting SQL statements and an anon,mous PL/SQL bloc5 using SQL >or5s/eet .ccessing and boo5mar5ing t/e Oracle Database 11g documentation and ot/er useBul >eb sites

%op,rig/t @ &''"A Oracle) .ll rig/ts reserved)

Practice I: Overvie2 In t/is practiceA ,ou use SQL Developer to eCecute SQL statements to eCamine data in ,our sc/ema) 8ou also create a simple anon,mous bloc5) Optionall,A ,ou can eCperiment b, creating and eCecuting t/e PL/SQL code in SQLKPlus) <ote: .ll 2ritten practices use SQL Developer as t/e development environment) .lt/oug/ it is recommended t/at ,ou use SQL DeveloperA ,ou can also use t/e SQLKPlus or ;Developer environments t/at are available in t/is course)

c ra O l, - On

, em ad .c

ra c O

le In

l ae rn Uste

Oracle Database 11g: Develop PL/SQL Program Units I E &'

%reating Procedures

%op,rig/t @ &''"A Oracle) .ll rig/ts reserved)

l c ra O l, - On ra c O le In l ae rn Uste e

, em ad .c

Ob3ectives
.Bter completing t/is lessonA ,ou s/ould be able to do t/e Bollo2ing: IdentiB, t/e beneBits oB modulari4ed and la,ered subprogram design %reate and call procedures Use Bormal and actual parameters Use positionalA namedA or miCed notation Bor passing parameters IdentiB, t/e available parameterEpassing modes 9andle eCceptions in procedures 1emove a procedure Displa, t/e proceduresF inBormation

%op,rig/t @ &''"A Oracle) .ll rig/ts reserved)

Lesson .im In t/is lessonA ,ou learn to createA eCecuteA and remove procedures 2it/ or 2it/out parameters) Procedures are t/e Boundation oB modular programming in PL/SQL) 0o ma5e procedures more BleCibleA it is important t/at var,ing data is eit/er calculated or passed into a procedure b, using input parameters) %alculated results can be returned to t/e caller oB a procedure b, using OU0 parameters) 0o ma5e ,our programs robustA ,ou s/ould al2a,s manage eCception conditions b, using t/e eCceptionE/andling Beatures oB PL/SQL)

c ra O l, - On

, em ad .c

ra c O

le In

l ae rn Uste

Oracle Database 11g: Develop PL/SQL Program Units 1 E &

Lesson .genda
Using a modulari4ed and la,ered subprogram design and identiB,ing t/e beneBits oB subprograms >or5ing 2it/ procedures:
M M M M %reating and calling procedures IdentiB,ing t/e available parameterEpassing modes Using Bormal and actual parameters Using positionalA namedA or miCed notation

9andling eCceptions in proceduresA removing a procedureA and displa,ing t/e proceduresF inBormation

%op,rig/t @ &''"A Oracle) .ll rig/ts reserved)

l c ra O l, - On ra c O le In l ae rn Uste e

, em ad .c

Oracle Database 11g: Develop PL/SQL Program Units 1 E *

%reating a =odulari4ed Subprogram Design

1
CC CCC CCC CC CCC CCC EEEEE EEE EEE EEEEE EEE EEE CC CCC CCC CC CCC CCC EEEEE EEE EEE

* &
CC CCC CCC CC CCC CCC P P EEEEE EEE EEE EEEEE EEE EEE P EEEEE EEE EEE

=odulari4e code into subprograms) 1) Locate code sePuences repeated more t/an once) &) %reate subprogram P containing t/e repeated code *) =odiB, original code to invo5e t/e ne2 subprogram)

%op,rig/t @ &''"A Oracle) .ll rig/ts reserved)

%reating a =odulari4ed and La,ered Subprogram Design 0/e diagram illustrates t/e principle oB modulari4ation 2it/ subprograms: t/e creation oB smaller manageable pieces oB BleCible and reusable code) :leCibilit, is ac/ieved b, using subprograms 2it/ parametersA 2/ic/ in turn ma5es t/e same code reusable Bor diBBerent input values) 0o modulari4e eCisting codeA perBorm t/e Bollo2ing steps: 1) Locate and identiB, repetitive sePuences oB code) &) =ove t/e repetitive code into a PL/SQL subprogram) *) 1eplace t/e original repetitive code 2it/ calls to t/e ne2 PL/SQL subprogram) :ollo2ing t/is modular and la,ered approac/ can /elp ,ou create code t/at is easier to maintainA particularl, 2/en t/e business rules c/ange) In additionA 5eeping t/e SQL logic simple and Bree oB compleC business logic can beneBit Brom t/e 2or5 oB Oracle Database Optimi4erA 2/ic/ can reuse parsed SQL statements Bor better use oB serverEside resources)

c ra O l, - On

, em ad .c

ra c O

le In

l ae rn Uste

Oracle Database 11g: Develop PL/SQL Program Units 1 E !

%reating a La,ered Subprogram Design


%reate subprogram la,ers Bor ,our application) Data access subprogram la,er 2it/ SQL logic 6usiness logic subprogram la,erA 2/ic/ ma, or ma, not use t/e data access la,er

%op,rig/t @ &''"A Oracle) .ll rig/ts reserved)

%reating a La,ered Subprogram Design 6ecause PL/SQL allo2s SQL statements to be seamlessl, embedded into t/e logicA it is too eas, to /ave SQL statement spread all over t/e code) 9o2everA it is recommended t/at ,ou 5eep t/e SQL logic separate Brom t/e business logicUt/at isA create a la,ered application design 2it/ a minimum oB t2o la,ers: Data access la,er: :or subroutines to access t/e data b, using SQL statements 6usiness logic la,er: :or subprograms to implement t/e business processing rulesA 2/ic/ ma, or ma, not call on t/e data access la,er routines

c ra O l, - On

, em ad .c

ra c O

le In

l ae rn Uste

Oracle Database 11g: Develop PL/SQL Program Units 1 E +

=odulari4ing Development 2it/ PL/SQL 6loc5s


PL/SQL is a bloc5Estructured language) 0/e PL/SQL code bloc5 /elps modulari4e code b, using:
M M M M .non,mous bloc5s Procedures and Bunctions Pac5ages Database triggers

0/e beneBits oB using modular program constructs are:


M M M M (as, maintenance Improved data securit, and integrit, Improved perBormance Improved code clarit,

%op,rig/t @ &''"A Oracle) .ll rig/ts reserved)

=odulari4ing Development 2it/ PL/SQL 6loc5s . subprogram is based on standard PL/SQL structures) It contains a declarative sectionA an eCecutable sectionA and an optional eCceptionE/andling section HBor eCampleA anon,mous bloc5sA proceduresA BunctionsA pac5agesA and triggersI) Subprograms can be compiled and stored in t/e databaseA providing modularit,A eCtensibilit,A reusabilit,A and maintainabilit,) =odulari4ation converts large bloc5s oB code into smaller groups oB code called modules) .Bter modulari4ationA t/e modules can be reused b, t/e same program or s/ared 2it/ ot/er programs) It is easier to maintain and debug code t/at comprises smaller modules t/an it is to maintain code in a single large program) =odules can be easil, eCtended Bor customi4ation b, incorporating more Bunctionalit,A iB rePuiredA 2it/out aBBecting t/e remaining modules oB t/e program) Subprograms provide eas, maintenance because t/e code is located in one place and an, modiBications rePuired to t/e subprogram canA t/ereBoreA be perBormed in t/is single location) Subprograms provide improved data integrit, and securit,) 0/e data ob3ects are accessed t/roug/ t/e subprogramA and a user can invo5e t/e subprogram onl, iB t/e appropriate access privilege is granted to t/e user) <ote: ?no2ing /o2 to develop anon,mous bloc5s is a prerePuisite Bor t/is course) :or detailed inBormation about anon,mous bloc5sA see t/e course titled Oracle 11g: PL/SQL :undamentals)

c ra O l, - On

, em ad .c

ra c O

le

l ae rn Uste

Oracle Database 11g: Develop PL/SQL Program Units 1 E $

In

.non,mous 6loc5s: Overvie2


.non,mous bloc5s: :orm t/e basic PL/SQL bloc5 structure Initiate PL/SQL processing tas5s Brom applications %an be nested 2it/in t/e eCecutable section oB an, PL/SQL bloc5

VD(%L.1(EE Declaration Section HOptionalI variable declarationsR ))) W 6( I<EE (Cecutable Section H=andator,I SQL or PL/SQL statementsR V(O%(P0IO<EE (Cception Section HOptionalI >9(< eCception 09(< statementsR W (<DREE (nd oB 6loc5 H=andator,I

%op,rig/t @ &''"A Oracle) .ll rig/ts reserved)

.non,mous 6loc5s: Overvie2 .non,mous bloc5s are t,picall, used Bor: >riting trigger code Bor Oracle :orms components Initiating calls to proceduresA BunctionsA and pac5age constructs Isolating eCception /andling 2it/in a bloc5 oB code <esting inside ot/er PL/SQL bloc5s Bor managing code Blo2 control 0/e D(%L.1( 5e,2ord is optionalA but it is rePuired iB ,ou declare variablesA constantsA and eCceptions to be used 2it/in t/e PL/SQL bloc5) 6( I< and (<D are mandator, and rePuire at least one statement bet2een t/emA eit/er SQLA PL/SQLA or bot/) 0/e eCception section is optional and is used to /andle errors t/at occur 2it/in t/e scope oB t/e PL/SQL bloc5) (Cceptions can be propagated to t/e caller oB t/e anon,mous bloc5 b, eCcluding an eCception /andler Bor t/e speciBic eCceptionA t/us creating 2/at is 5no2n as an un/andled eCception)

c ra O l, - On

, em ad .c

ra c O

le

l ae rn Uste

Oracle Database 11g: Develop PL/SQL Program Units 1 E G

In

PL/SQL 1unEtime .rc/itecture


PL/SQL bloc5

procedural

Procedural statement eCecutor SQL PL/SQL

PL/SQL (ngine

Oracle Server

SQL statement eCecutor

%op,rig/t @ &''"A Oracle) .ll rig/ts reserved)

PL/SQL 1unEtime .rc/itecture 0/e diagram s/o2s a PL/SQL bloc5 being eCecuted b, t/e PL/SQL engine) 0/e PL/SQL engine resides in: 0/e Oracle database Bor eCecuting stored subprograms 0/e Oracle :orms client 2/en running client/server applicationsA or in t/e Oracle .pplication Server 2/en using Oracle :orms Services to run :orms on t/e >eb Irrespective oB t/e PL/SQL runEtime environmentA t/e basic arc/itecture remains t/e same) 0/ereBoreA all PL/SQL statements are processed in t/e Procedural Statement (CecutorA and all SQL statements must be sent to t/e SQL Statement (Cecutor Bor processing b, t/e Oracle server processes) 0/e SQL environment ma, also invo5e t/e PL/SQL environment Bor eCample 2/en a Bunction is used in a select statement) 0/e PL/SQL engine is a virtual mac/ine t/at resides in memor, and processes t/e PL/SQL mEcode instructions) >/en t/e PL/SQL engine encounters a SQL statementA a conteCt s2itc/ is made to pass t/e SQL statement to t/e Oracle server processes) 0/e PL/SQL engine 2aits Bor t/e SQL statement to complete and Bor t/e results to be returned beBore it continues to process subsePuent statements in t/e PL/SQL bloc5) 0/e Oracle :orms PL/SQL engine runs in t/e client Bor t/e client/server implementationA and in t/e application server Bor t/e :orms Services implementation) In eit/er caseA SQL statements are t,picall, sent over a net2or5 to an Oracle server Bor processing)

c ra O l, - On

, em ad .c

ra c O

le

l ae rn Uste

Oracle Database 11g: Develop PL/SQL Program Units 1 E #

In

>/at .re PL/SQL SubprogramsJ


. PL/SQL subprogram is a named PL/SQL bloc5 t/at can be called 2it/ a set oB parameters) 8ou can declare and deBine a subprogram 2it/in eit/er a PL/SQL bloc5 or anot/er subprogram) . subprogram consists oB a speciBication and a bod,) . subprogram can be a procedure or a Bunction) 0,picall,A ,ou use a procedure to perBorm an action and a Bunction to compute and return a value) Subprograms can be grouped into PL/SQL pac5ages)

%op,rig/t @ &''"A Oracle) .ll rig/ts reserved)

>/at .re PL/SQL SubprogramsJ . PL/SQL subprogram is a named PL/SQL bloc5 t/at can be called 2it/ a set oB parameters) 8ou can declare and deBine a subprogram 2it/in eit/er a PL/SQL bloc5 or anot/er subprogram)

Subprogram Parts . subprogram consists oB a speciBication HspecI and a bod,) 0o declare a subprogramA ,ou must provide t/e specA 2/ic/ includes descriptions oB an, parameters) 0o deBine a subprogramA ,ou must provide bot/ t/e spec and t/e bod,) 8ou can eit/er declare a subprogram Birst and deBine it later in t/e same bloc5 or subprogramA or declare and deBine it at t/e same time) Subprogram 0,pes PL/SQL /as t2o t,pes oB subprograms: procedures and Bunctions) 0,picall,A ,ou use a procedure to perBorm an action and a Bunction to compute and return a value)

c ra O l, - On

, em ad .c

ra c O

. procedure and a Bunction /ave t/e same structureA eCcept t/at onl, a Bunction /as some additional items suc/ as t/e 1(0U1< clause or t/e 1(0U1< statement) 0/e 1(0U1< clause speciBies t/e data t,pe oB t/e return value HrePuiredI) . 1(0U1< statement speciBies t/e return value HrePuiredI) :unctions are covered in more detail in t/e neCt lesson titled X%reating :unctions and Debugging Subprograms)Y Subprograms can be grouped into PL/SQL pac5agesA 2/ic/ ma5e code even more reusable and maintainable) Pac5ages are covered in t/e pac5ages lessons: Lessons * and !)

le

l ae rn Uste

Oracle Database 11g: Develop PL/SQL Program Units 1 E "

In

0/e 6eneBits oB Using PL/SQL Subprograms

(as, maintenance

Improved data securit, and integrit,

Subprograms: Stored procedures and Bunctions

Improved code clarit,

Improved perBormance

%op,rig/t @ &''"A Oracle) .ll rig/ts reserved)

6eneBits oB Subprograms Procedures and Bunctions /ave man, beneBits due to modulari4ing oB code: (as, maintenance is reali4ed because subprograms are located in one place) =odiBications need to be done in onl, one place to aBBect multiple applications and minimi4e eCcessive testing) Improved data securit, can be ac/ieved b, controlling indirect access to database ob3ects Brom nonprivileged users 2it/ securit, privileges) 0/e subprograms are b, deBault eCecuted 2it/ deBinerFs rig/t) 0/e eCecute privilege does not allo2 a calling user direct access to ob3ects t/at are accessible to t/e subprogram) Data integrit, is managed b, /aving related actions perBormed toget/er or not at all) Improved perBormance can be reali4ed Brom reuse oB parsed PL/SQL code t/at becomes available in t/e s/ared SQL area oB t/e server) SubsePuent calls to t/e subprogram avoid parsing t/e code again) 6ecause PL/SQL code is parsed at compile timeA t/e parsing over/ead oB SQL statements is avoided at run time) %ode can be 2ritten to reduce t/e number oB net2or5 calls to t/e databaseA and t/ereBoreA decrease net2or5 traBBic) Improved code clarit, can be attained b, using appropriate names and conventions to describe t/e action oB t/e routinesA t/ereb, reducing t/e need Bor comments and en/ancing t/e clarit, oB t/e code)

c ra O l, - On

, em ad .c

ra c O

le

l ae rn Uste

Oracle Database 11g: Develop PL/SQL Program Units 1 E 1'

In

DiBBerences 6et2een .non,mous 6loc5s and Subprograms


.non,mous 6loc5s
Unnamed PL/SQL bloc5s %ompiled ever, time <ot stored in t/e database %annot be invo5ed b, ot/er applications Do not return values

Subprograms
<amed PL/SQL bloc5s %ompiled onl, once Stored in t/e database <amed andA t/ereBoreA can be invo5ed b, ot/er applications Subprograms called Bunctions must return values) %an ta5e parameters

%annot ta5e parameters

%op,rig/t @ &''"A Oracle) .ll rig/ts reserved)

DiBBerences 6et2een .non,mous 6loc5s and Subprograms 0/e table in t/e slide not onl, s/o2s t/e diBBerences bet2een anon,mous bloc5s and subprogramsA but also /ig/lig/ts t/e general beneBits oB subprograms)

.non,mous bloc5s are not persistent database ob3ects) 0/e, are compiled and eCecuted onl, once) 0/e, are not stored in t/e database Bor reuse) IB ,ou 2ant to reuseA ,ou must rerun t/e script t/at creates t/e anon,mous bloc5A 2/ic/ causes recompilation and eCecution) Procedures and Bunctions are compiled and stored in t/e database in a compiled Borm) 0/e, are recompiled onl, 2/en t/e, are modiBied) 6ecause t/e, are stored in t/e databaseA an, application can ma5e use oB t/ese subprograms based on appropriate permissions) 0/e calling application can pass parameters to t/e procedures iB t/e procedure is designed to accept parameters) Similarl,A a calling application can retrieve a value iB it invo5es a Bunction or a procedure)

c ra O l, - On

, em ad .c

ra c O

le In

l ae rn Uste

Oracle Database 11g: Develop PL/SQL Program Units 1 E 11

Lesson .genda
Using a modulari4ed and la,ered subprogram design and identiB,ing t/e beneBits oB subprograms >or5ing 2it/ procedures:
M M M M %reating and calling procedures IdentiB,ing t/e available parameterEpassing modes Using Bormal and actual parameters Using positionalA namedA or miCed notation

9andling eCceptions in proceduresA removing a procedureA and displa,ing t/e proceduresF inBormation

%op,rig/t @ &''"A Oracle) .ll rig/ts reserved)

l c ra O l, - On ra c O le In l ae rn Uste e

, em ad .c

Oracle Database 11g: Develop PL/SQL Program Units 1 E 1&

>/at .re ProceduresJ


.re a t,pe oB subprogram t/at perBorm an action %an be stored in t/e database as a sc/ema ob3ect Promote reusabilit, and maintainabilit,

Procedures

%op,rig/t @ &''"A Oracle) .ll rig/ts reserved)

DeBinition oB a Procedure . procedure is a named PL/SQL bloc5 t/at can accept parameters Hsometimes reBerred to as argumentsI) enerall,A ,ou use a procedure to perBorm an action) It /as a /eaderA a declaration sectionA an eCecutable sectionA and an optional eCceptionE/andling section) . procedure is invo5ed b, using t/e procedure name in t/e eCecution section oB anot/er PL/SQL bloc5) . procedure is compiled and stored in t/e database as a sc/ema ob3ect) IB ,ou are using t/e procedures 2it/ Oracle :orms and 1eportsA t/en t/e, can be compiled 2it/in t/e Oracle :orms or Oracle 1eports eCecutables) Procedures promote reusabilit, and maintainabilit,) >/en validatedA t/e, can be used in an, number oB applications) IB t/e rePuirements c/angeA onl, t/e procedure needs to be updated)

c ra O l, - On

, em ad .c

ra c O

le In

l ae rn Uste

Oracle Database 11g: Develop PL/SQL Program Units 1 E 1*

%reating Procedures: Overvie2

Vie2 errors/2arnings in SQL Developer

8(S
Use S9O> (11O1S command in SQLKPlus %reate/edit procedure %ompiler 2arnings/errorsJ Vie2 compiler 2arnings/errors

<O
Use US(1/.LL/D6.L (11O1S vie2s

(Cecute procedure

%op,rig/t @ &''"A Oracle) .ll rig/ts reserved)

%reating Procedures: Overvie2 0o develop a procedure using a tool suc/ as SQL DeveloperA perBorm t/e Bollo2ing steps: 1) %reate t/e procedure using SQL DeveloperFs Ob3ect <avigator tree or t/e SQL >or5s/eet area) &) %ompile t/e procedure) 0/e procedure is created in t/e database and gets compiled) 0/e %1(.0( P1O%(DU1( statement creates and stores t/e source code and t/e compiled mE code in t/e database) 0o compile t/e procedureA rig/tEclic5 t/e procedureFs name in t/e Ob3ect <avigator treeA and t/en clic5 %ompile) *) IB compilation errors eCistA t/en t/e mEcode is not stored and ,ou must edit t/e source code to ma5e corrections) 8ou cannot invo5e a procedure t/at contains compilation errors) 8ou can vie2 t/e compilation errors in SQL DeveloperA SQLKPlusA or t/e appropriate data dictionar, vie2s as s/o2n in t/e slide) !) .Bter successBul compilationA eCecute t/e procedure to perBorm t/e desired action) 8ou can run t/e procedure using SQL Developer or use t/e (O(%U0( command in SQLKPlus) <ote: IB compilation errors occurA use a %1(.0( O1 1(PL.%( P1O%(DU1( statement to over2rite t/e eCisting code iB ,ou previousl, used a %1(.0( P1O%(DU1( statement) Ot/er2iseA drop t/e procedure Birst Husing D1OPI and t/en eCecute t/e %1(.0( P1O%(DU1( statement)

c ra O l, - On

, em ad .c

ra c O

le

l ae rn Uste

Oracle Database 11g: Develop PL/SQL Program Units 1 E 1!

In

%reating Procedures 2it/ t/e SQL %1(.0( O1 1(PL.%( Statement


Use t/e %1(.0( clause to create a standEalone procedure t/at is stored in t/e Oracle database) Use t/e O1 1(PL.%( option to over2rite an eCisting procedure)

%1(.0( VO1 1(PL.%(W P1O%(DU1( procedureLname VHparameter1 VmodeW datat,pe1A parameter& VmodeW datat,pe&A )))IW IST.S VlocalLvariableLdeclarationsR )))W 6( I< PL/SQL bloc5 EE actionsR (<D VprocedureLnameWR

%op,rig/t @ &''"A Oracle) .ll rig/ts reserved)

%reating Procedures 2it/ t/e SQL %1(.0( O1 1(PL.%( Statement 8ou can use t/e %1(.0( P1O%(DU1( SQL statement to create standEalone procedures t/at are stored in an Oracle database) . procedure is similar to a miniature program: it perBorms a speciBic action) 8ou speciB, t/e name oB t/e procedureA its parametersA its local variablesA and t/e 6( I<E(<D bloc5 t/at contains its code and /andles an, eCceptions) PL/SQL bloc5s start 2it/ 6( I<A optionall, preceded b, t/e declaration oB local variables) PL/SQL bloc5s end 2it/ eit/er (<D or (<D procedureLname) 0/e 1(PL.%( option indicates t/at iB t/e procedure eCistsA it is dropped and replaced 2it/ t/e ne2 version created b, t/e statement) 0/e 1(PL.%( option does not drop an, oB t/e privileges associated 2it/ t/e procedure) Ot/er S,ntactic (lements parameter1 represents t/e name oB a parameter) 0/e mode option deBines /o2 a parameter is used: I< HdeBaultIA OU0A or I< OU0) datat,pe1 speciBies t/e parameter data t,peA 2it/out an, precision)

c ra O l, - On

, em ad .c

ra c O

le

<ote: Parameters can be considered as local variables) Substitution and /ost HbindI variables cannot be reBerenced an,2/ere in t/e deBinition oB a PL/SQL stored procedure) 0/e O1 1(PL.%( option does not rePuire an, c/ange in ob3ect securit,A as long as ,ou o2n t/e ob3ect and /ave t/e %1(.0( V.<8W P1O%(DU1( privilege)

l ae rn Uste

Oracle Database 11g: Develop PL/SQL Program Units 1 E 1+

In

%reating Procedures Using SQL Developer

%op,rig/t @ &''"A Oracle) .ll rig/ts reserved)

%reating Procedures Using SQL Developer 1) 1ig/tEclic5 t/e Procedures node on t/e %onnections tabbed page) &) Select <e2 Procedure Brom t/e s/ortcut menu) 0/e %reate PL/SQL Procedure dialog boC is displa,ed) SpeciB, t/e inBormation Bor t/e ne2 procedureA and t/en clic5 O? to create t/e subprogram and /ave it displa,ed in t/e (ditor 2indo2A 2/ere ,ou can enter t/e details) 0/e components oB t/e %reate PL/SQL Procedure dialog boC are as Bollo2s: Sc/ema: 0/e database sc/ema in 2/ic/ to create t/e PL/SQL subprogram <ame: 0/e name oB t/e subprogram t/at must be uniPue 2it/in a sc/ema .dd <e2 Source in Lo2ercase: IB t/is option is selectedA ne2 teCt appears in lo2ercase regardless oB t/e case in 2/ic/ ,ou enter it) 0/is option aBBects onl, t/e appearance oB t/e codeA because PL/SQL is not caseEsensitive in its eCecution) Parameters tab: 0o add a parameterA clic5 t/e .dd HNI icon) :or eac/ parameter in t/e procedure to be createdA speciB, t/e parameter nameA data t,peA modeA and optionall, t/e deBault Value) Use t/e 1emove HOI icon and t/e arro2 icons to delete and to move a parameter up or do2n in t/e list respectivel,) DDL tab: 0/is tab contains a readEonl, displa, oB a SQL statement t/at reBlects t/e current deBinition oB t/e subprogram)

c ra O l, - On

, em ad .c

ra c O

le

l ae rn Uste

Oracle Database 11g: Develop PL/SQL Program Units 1 E 1$

In

%ompiling Procedures and Displa,ing %ompilation (rrors in SQL Developer


1
O1

&

%op,rig/t @ &''"A Oracle) .ll rig/ts reserved)

%ompiling Procedures and Displa,ing %ompilation (rrors in SQL Developer 8ou can compile procedures using one oB t/e Bollo2ing t2o met/ods: <avigate to t/e Procedures node in t/e Ob3ect <avigator tree) 1ig/tEclic5 t/e procedureFs nameA and t/en select %ompile Brom t/e s/ortcut menu) 0o vie2 an, compilation messagesA vie2 t/e =essages subtab in t/e %ompiler M Log tab) (dit t/e procedure using t/e (dit icon on t/e procedureFs code toolbar) =a5e t/e necessar, editsA and t/en clic5 t/e %ompile icon on t/e code toolbar) 0o vie2 an, compilation messagesA vie2 t/e =essages subtab in t/e %ompiler M Log tab)

c ra O l, - On

, em ad .c

ra c O

le In

l ae rn Uste

Oracle Database 11g: Develop PL/SQL Program Units 1 E 1G

%orrecting %ompilation (rrors in SQL Developer

1) (dit procedure

&) %orrect error Hadd 5e,2ord ISI

!) 1ecompilation successBul

*) 1ecompile procedure

%op,rig/t @ &''"A Oracle) .ll rig/ts reserved)

%orrecting %ompilation (rrors in SQL Developer 1) (dit t/e procedure using t/e (dit icon on t/e procedureFs code toolbar) . ne2 procedure code tab is opened in 1ead/>rite mode) &) =a5e t/e necessar, corrections) *) %lic5 t/e %ompile icon on t/e code toolbar) !) 0o vie2 an, compilation messagesA vie2 t/e =essages subtab in t/e %ompiler M Log tab) In additionA iB t/e procedure compiled successBull,A t/e red O on t/e procedureFs name in t/e Ob3ect <avigator tree is removed)

c ra O l, - On

, em ad .c

ra c O

le In

l ae rn Uste

Oracle Database 11g: Develop PL/SQL Program Units 1 E 1#

<aming %onventions oB PL/SQL Structures Used in 0/is %ourse


PL/SQL Structure Variable %onstant Subprogram parameter 6ind H/ostI variable %ursor 1ecord 0,pe (Cception :ile /andle %onvention vLvariableLname cLconstantLname pLparameterLname (Cample vLrate cLrate pLid

bLbindLname curLcursorLname recLrecordLname t,peLnameLt,pe eLeCceptionLname BLBileL/andleLname

bLsalar, curLemp recLemp enameLtableLt,pe eLproductsLinvalid BLBile

%op,rig/t @ &''"A Oracle) .ll rig/ts reserved)

<aming %onventions oB PL/SQL Structures Used in 0/is %ourse 0/e slide table displa,s some eCamples oB t/e naming conventions Bor PL/SQL structures t/at are used in t/is course)

c ra O l, - On

, em ad .c

ra c O

le In

l ae rn Uste

Oracle Database 11g: Develop PL/SQL Program Units 1 E 1"

>/at .re Parameters and Parameter =odesJ


.re declared aBter t/e subprogram name in t/e PL/SQL /eader Pass or communicate data bet2een t/e calling environment and t/e subprogram .re used li5e local variables but are dependent on t/eir parameterEpassing mode:
M .n I< parameter mode Ht/e deBaultI provides values Bor a subprogram to process M .n OU0 parameter mode returns a value to t/e caller M .n I< OU0 parameter mode supplies an input valueA 2/ic/ ma, be returned HoutputI as a modiBied value

%op,rig/t @ &''"A Oracle) .ll rig/ts reserved)

>/at .re ParametersJ Parameters are used to transBer data values to and Brom t/e calling environment and t/e procedure Hor subprogramI) Parameters are declared in t/e subprogram /eaderA aBter t/e name and beBore t/e declaration section Bor local variables) Parameters are sub3ect to one oB t/e t/ree parameterEpassing modes: I<A OU0A or I< OU0) .n I< parameter passes a constant value Brom t/e calling environment into t/e procedure) .n OU0 parameter passes a value Brom t/e procedure to t/e calling environment) .n I< OU0 parameter passes a value Brom t/e calling environment to t/e procedure and a possibl, diBBerent value Brom t/e procedure bac5 to t/e calling environment using t/e same parameter)

Parameters can be t/oug/t oB as a special Borm oB local variableA 2/ose input values are initiali4ed b, t/e calling environment 2/en t/e subprogram is calledA and 2/ose output values are returned to t/e calling environment 2/en t/e subprogram returns control to t/e caller)

c ra O l, - On

, em ad .c

ra c O

le

l ae rn Uste

Oracle Database 11g: Develop PL/SQL Program Units 1 E &'

In

:ormal and .ctual Parameters


:ormal parameters: Local variables declared in t/e parameter list oB a subprogram speciBication .ctual parameters Hor argumentsI: Literal valuesA variablesA and eCpressions used in t/e parameter list oB t/e calling subprogram

EE Procedure deBinitionA :ormalLparameters %1(.0( P1O%(DU1( raiseLsalHpLid <U=6(1A pLsal <U=6(1I IS 6( I< ))) (<D raiseLsalR

EE Procedure callingA .ctual parameters HargumentsI vLempLid :Z 1''R raiseLsalHvLempLidA &'''I

%op,rig/t @ &''"A Oracle) .ll rig/ts reserved)

:ormal and .ctual Parameters :ormal parameters are local variables t/at are declared in t/e parameter list oB a subprogram speciBication) In t/e Birst eCampleA in t/e raiseLsal procedureA t/e variable pLid and pL sal identiBiers represent t/e Bormal parameters)

ra c O

0/e actual parameters can be literal valuesA variablesA and eCpressions t/at are provided in t/e parameter list oB a calling subprogram) In t/e second eCampleA a call is made to raiseLsalA 2/ere t/e vLempLid variable provides t/e actual parameter value Bor t/e pLid Bormal parameter and &''' is supplied as t/e actual parameter value Bor pLsal) .ctual parameters: .re associated 2it/ Bormal parameters during t/e subprogram call %an also be eCpressionsA as in t/e Bollo2ing eCample: raiseLsalHvLempLidA raiseN1''IR 0/e Bormal and actual parameters s/ould be oB compatible data t,pes) IB necessar,A beBore assigning t/e valueA PL/SQL converts t/e data t,pe oB t/e actual parameter value to t/at oB t/e Bormal parameter) <ote: .ctual parameters are also reBerred to as actual arguments)

c ra O l, - On

, em ad .c

le

l ae rn Uste

Oracle Database 11g: Develop PL/SQL Program Units 1 E &1

In

Procedural Parameter =odes


Parameter modes are speciBied in t/e Bormal parameter declarationA aBter t/e parameter name and beBore its data t,pe) 0/e I< mode is t/e deBault iB no mode is speciBied)

%1(.0( P1O%(DU1( procLnameHparamLname VmodeW datat,peI )))


=odes

I< HdeBaultI
%alling environment

OU0 I< OU0

%op,rig/t @ &''"A Oracle) .ll rig/ts reserved)

Procedural Parameter =odes >/en ,ou create a procedureA t/e Bormal parameter deBines a variable name 2/ose value is used in t/e eCecutable section oB t/e PL/SQL bloc5) 0/e actual parameter is used 2/en invo5ing t/e procedure to provide input values or receive output results) 0/e parameter mode I< is t/e deBault passing modeUt/at isA iB no mode is speciBied 2it/ a parameter declarationA t/e parameter is considered to be an I< parameter) 0/e parameter modes OU0 and I< OU0 must be eCplicitl, speciBied in t/eir parameter declarations) 0/e datat,pe parameter is speciBied 2it/out a si4e speciBication) It can be speciBied: .s an eCplicit data t,pe Using t/e Q08P( deBinition Using t/e Q1O>08P( deBinition <ote: One or more Bormal parameters can be declaredA eac/ separated b, a comma)

c ra O l, - On

, em ad .c
Procedure

ra c O

le

l ae rn Uste

Oracle Database 11g: Develop PL/SQL Program Units 1 E &&

In

%omparing t/e Parameter =odes

I<
DeBault mode Value is passed into subprogram

OU0
=ust be speciBied Value is returned to t/e calling environment Uninitiali4ed variable

I< OU0
=ust be speciBied Value passed into subE programR value returned to calling environment Initiali4ed variable

:ormal parameter acts as a constant .ctual parameter can be a literalA eCpressionA constantA or initiali4ed variable %an be assigned a deBault value

=ust be a variable

=ust be a variable

%annot be assigned a deBault value

%annot be assigned a deBault value

%op,rig/t @ &''"A Oracle) .ll rig/ts reserved)

%omparing t/e Parameter =odes 0/e I< parameter mode is t/e deBault mode iB no mode is speciBied in t/e declaration) 0/e OU0 and I< OU0 parameter modes must be eCplicitl, speciBied 2it/ t/e parameter declaration)

. Bormal parameter oB I< mode cannot be assigned a value and cannot be modiBied in t/e bod, oB t/e procedure) 6, deBaultA t/e I< parameter is passed b, reBerence) .n I< parameter can be assigned a deBault value in t/e Bormal parameter declarationA in 2/ic/ case t/e caller need not provide a value Bor t/e parameter iB t/e deBault applies) .n OU0 or I< OU0 parameter must be assigned a value beBore returning to t/e calling environment) 0/e OU0 and I< OU0 parameters cannot be assigned deBault values) 0o improve perBormance 2it/ OU0 and I< OU0 parametersA t/e <O%OP8 compiler /int can be used to rePuest to pass b, reBerence) <ote: Using <O%OP8 is discussed later in t/is course)

c ra O l, - On

, em ad .c

ra c O

le In

l ae rn Uste

Oracle Database 11g: Develop PL/SQL Program Units 1 E &*

Using t/e I< Parameter =ode: (Cample


%1(.0( O1 1(PL.%( P1O%(DU1( raiseLsalar, HpLidI< emplo,ees)emplo,eeLidQ08P(A pLpercent I< <U=6(1I IS 6( I< UPD.0( emplo,ees S(0salar, Z salar, K H1 N pLpercent/1''I >9(1( emplo,eeLid Z pLidR (<D raiseLsalar,R /

(O(%U0( raiseLsalar,H1G$A 1'I


%op,rig/t @ &''"A Oracle) .ll rig/ts reserved)

Using I< Parameters: (Cample 0/e eCample in t/e slide s/o2s a procedure 2it/ t2o I< parameters) 1unning t/e Birst slide eCample creates t/e raiseLsalar, procedure in t/e database) 0/e second slide eCample invo5es raiseLsalar, and provides t/e Birst parameter value oB 1G$ Bor t/e emplo,ee IDA and a salar, increase oB 1' percent Bor t/e second parameter value) 0o invo5e a procedure b, using t/e SQL >or5s/eet oB SQL Developer or b, using SQLKPlusA use t/e Bollo2ing (O(%U0( command s/o2n in t/e second code eCample in t/e slide)

0o invo5e a procedure Brom anot/er procedureA use a direct call inside an eCecutable section oB t/e calling bloc5) .t t/e location oB calling t/e ne2 procedureA enter t/e procedure name and actual parameters) :or eCample:
))) 6( I< raiseLsalar, H1G$A 1'IR (<DR

c ra O l, - On

, em ad .c

ra c O

le

<ote: I< parameters are passed as readEonl, values Brom t/e calling environment into t/e procedure) .ttempts to c/ange t/e value oB an I< parameter result in a compileEtime error)

l ae rn Uste

Oracle Database 11g: Develop PL/SQL Program Units 1 E &!

In

Using t/e OU0 Parameter =ode: (Cample


%1(.0( O1 1(PL.%( P1O%(DU1( Puer,Lemp HpLidI< emplo,ees)emplo,eeLidQ08P(A pLnameOU0 emplo,ees)lastLnameQ08P(A pLsalar, OU0 emplo,ees)salar,Q08P(I IS 6( I< S(L(%0 lastLnameA salar, I<0O pLnameA pLsalar, :1O=emplo,ees >9(1(emplo,eeLid Z pLidR (<D Puer,LempR /

S(0 S(1V(1OU0PU0 O< D(%L.1( vLempLname emplo,ees)lastLnameQ08P(R vLempLsal emplo,ees)salar,Q08P(R 6( I< Puer,LempH1G1A vLempLnameA vLempLsalIR D6=SLOU0PU0)PU0LLI<(HvLempLnameTTS earns STT toLc/arHvLempLsalA S["""A""")''SIIR (<DR /

%op,rig/t @ &''"A Oracle) .ll rig/ts reserved)

Using t/e OU0 Parameters: (Cample In t/e slide eCampleA ,ou create a procedure 2it/ OU0 parameters to retrieve inBormation about an emplo,ee) 0/e procedure accepts t/e value 1G1 Bor emplo,ee ID and retrieves t/e name and salar, oB t/e emplo,ee 2it/ ID 1G1 into t/e t2o OU0 parameters) 0/e Puer,Lemp procedure /as t/ree Bormal parameters) 02o oB t/em are OU0 parameters t/at return values to t/e calling environmentA s/o2n in t/e second code boC in t/e slide) 0/e procedure accepts an emplo,ee ID value t/roug/ t/e pLid parameter) 0/e vLempLname and vLempLsalar, variables are populated 2it/ t/e inBormation retrieved Brom t/e Puer, into t/eir t2o corresponding OU0 parameters) 0/e Bollo2ing is t/e result oB running t/e code in t/e second code eCample in t/e slide) vLempLname /olds t/e value Smit/ and vLempLsalar, /olds t/e value G!'':

c ra O l, - On

, em ad .c

ra c O

le In

<ote: =a5e sure t/at t/e data t,pe Bor t/e actual parameter variables used to retrieve values Brom t/e OU0 parameters /as a si4e suBBicient to /old t/e data values being returned)

l ae rn Uste

Oracle Database 11g: Develop PL/SQL Program Units 1 E &+

Using t/e I< OU0 Parameter =ode: (Cample


%alling environment pLp/oneLno HbeBore t/e callI S#''$**'+G+S pLp/oneLno HaBter t/e callI SH#''I $**E'+G+S

%1(.0( O1 1(PL.%( P1O%(DU1( BormatLp/one HpLp/oneLno I< OU0 V.1%9.1&I IS 6( I< pLp/oneLno :Z SHS TT SU6S01HpLp/oneLnoA1A*I TT SI S TT SU6S01HpLp/oneLnoA!A*I TT SES TT SU6S01HpLp/oneLnoAGIR (<D BormatLp/oneR /

%op,rig/t @ &''"A Oracle) .ll rig/ts reserved)

Using I< OU0 Parameters: (Cample Using an I< OU0 parameterA ,ou can pass a value into a procedure t/at can be updated) 0/e actual parameter value supplied Brom t/e calling environment can return eit/er t/e original unc/anged value or a ne2 value t/at is set 2it/in t/e procedure) <ote: .n I< OU0 parameter acts as an initiali4ed variable) 0/e slide eCample creates a procedure 2it/ an I< OU0 parameter to accept a 1'Ec/aracter string containing digits Bor a p/one number) 0/e procedure returns t/e p/one number Bormatted 2it/ parent/eses around t/e Birst t/ree c/aracters and a /,p/en aBter t/e siCt/ digitUBor eCampleA t/e p/one string #''$**'+G+ is returned as H#''I $**E'+G+) 0/e Bollo2ing code uses t/e bLp/oneLno /ost variable oB SQLKPlus to provide t/e input value passed to t/e :O1=.0LP9O<( procedure) 0/e procedure is eCecuted and returns an updated string in t/e bLp/oneLno /ost variable) 0/e output oB t/e Bollo2ing code is displa,ed in t/e slide above:

c ra O l, - On

, em ad .c

ra c O

V.1I.6L( bLp/oneLno V.1%9.1&H1+I (O(%U0( :bLp/oneLno :Z S#''$**'+G+S P1I<0 bLp/oneLno (O(%U0( BormatLp/one H:bLp/oneLnoI P1I<0 bLp/oneLno

le

l ae rn Uste

Oracle Database 11g: Develop PL/SQL Program Units 1 E &$

In

Vie2ing t/e OU0 Parameters: Using t/e D6=SLOU0PU0)PU0LLI<( Subroutine


Use PL/SQL variables t/at are printed 2it/ calls to t/e D6=SLOU0PU0)PU0LLI<( procedure)
S(0 S(1V(1OU0PU0 O< D(%L.1( vLempLname emplo,ees)lastLnameQ08P(R vLempLsal emplo,ees)salar,Q08P(R 6( I< Puer,LempH1G1A vLempLnameA vLempLsalIR D6=SLOU0PU0)PU0LLI<(HS<ame: S TT vLempLnameIR D6=SLOU0PU0)PU0LLI<(HSSalar,: S TT vLempLsalIR (<DR

%op,rig/t @ &''"A Oracle) .ll rig/ts reserved)

Vie2ing t/e OU0 Parameters: Using t/e D6=SLOU0PU0 Subroutine 0/e slide eCample illustrates /o2 to vie2 t/e values returned Brom t/e OU0 parameters in SQLKPlus or t/e SQL Developer >or5s/eet) 8ou can use PL/SQL variables in an anon,mous bloc5 to retrieve t/e OU0 parameter values) 0/e D6=SLOUPU0)PU0LLI<( procedure is called to print t/e values /eld in t/e PL/SQL variables) 0/e S(0 S(1V(1OUPU0 must be O<)

c ra O l, - On

, em ad .c

ra c O

le In

l ae rn Uste

Oracle Database 11g: Develop PL/SQL Program Units 1 E &G

Vie2ing OU0 Parameters: Using SQLKPlus 9ost Variables


1) Use SQLKPlus /ost variables) &) (Cecute QU(18L(=P using /ost variables) *) Print t/e /ost variables)

V.1I.6L( bLnameV.1%9.1&H&+I V.1I.6L( bLsal<U=6(1 (O(%U0( Puer,LempH1G1A :bLnameA :bLsalI P1I<0 bLname bLsal

%op,rig/t @ &''"A Oracle) .ll rig/ts reserved)

Vie2ing OU0 Parameters: Using SQLKPlus 9ost Variables

l e

0/e eCample in t/e slide demonstrates /o2 to use SQLKPlus /ost variables t/at are created using t/e V.1I.6L( command) 0/e SQLKPlus variables are eCternal to t/e PL/SQL bloc5 and are 5no2n as /ost or bind variables) 0o reBerence /ost variables Brom a PL/SQL bloc5A ,ou must preBiC t/eir names 2it/ a colon H:I) 0o displa, t/e values stored in t/e /ost variablesA ,ou must use t/e SQLKPlus P1I<0 command Bollo2ed b, t/e name oB t/e SQLKPlus variable H2it/out t/e colon because t/is is not a PL/SQL command or conteCtI) <ote: :or details about t/e V.1I.6L( commandA see t/e SQLKPlus %ommand 1eBerence)

c ra O l, - On

, em ad .c

ra c O

le In

l ae rn Uste

Oracle Database 11g: Develop PL/SQL Program Units 1 E &#

.vailable <otations Bor Passing .ctual Parameters


>/en calling a subprogramA ,ou can 2rite t/e actual parameters using t/e Bollo2ing notations:
M Positional: Lists t/e actual parameters in t/e same order as t/e Bormal parameters M <amed: Lists t/e actual parameters in arbitrar, order and uses t/e association operator HZ\I to associate a named Bormal parameter 2it/ its actual parameter M =iCed: Lists some oB t/e actual parameters as positional and some as named

Prior to Oracle Database 11gA onl, t/e positional notation is supported in calls Brom SQL Starting in Oracle Database 11gA named and miCed notation can be used Bor speciB,ing arguments in calls to PL/SQL subroutines Brom SQL statements

%op,rig/t @ &''"A Oracle) .ll rig/ts reserved)

S,ntaC Bor Passing Parameters >/en calling a subprogramA ,ou can 2rite t/e actual parameters using t/e Bollo2ing notations: Positional: 8ou list t/e actual parameter values in t/e same order in 2/ic/ t/e Bormal parameters are declared) 0/is notation is compactA but iB ,ou speciB, t/e parameters Hespeciall, literalsI in t/e 2rong orderA t/e error can be /ard to detect) 8ou must c/ange ,our code iB t/e procedureFs parameter list c/anges) <amed: 8ou list t/e actual values in arbitrar, order and use t/e association operator to associate eac/ actual parameter 2it/ its Bormal parameter b, name) 0/e PL/SQL association operator is an XePualY sign Bollo2ed b, an Xis greater t/anY signA 2it/out spaces: Z\) 0/e order oB t/e parameters is not signiBicant) 0/is notation is more verboseA but ma5es ,our code easier to read and maintain) 8ou can sometimes avoid c/anging ,our code iB t/e procedureFs parameter list c/angesA Bor eCampleA iB t/e parameters are reordered or a ne2 optional parameter is added) =iCed: 8ou list t/e Birst parameter values b, t/eir position and t/e remainder b, using t/e special s,ntaC oB t/e named met/od) 8ou can use t/is notation to call procedures t/at /ave some rePuired parametersA Bollo2ed b, some optional parameters)

c ra O l, - On

, em ad .c

ra c O

le

l ae rn Uste

Oracle Database 11g: Develop PL/SQL Program Units 1 E &"

In

Passing .ctual Parameters: %reating t/e addLdept Procedure


%1(.0( O1 1(PL.%( P1O%(DU1( addLdeptH pLname I< departments)departmentLnameQ08P(A pLloc I< departments)locationLidQ08P(I IS 6( I< I<S(10 I<0O departmentsHdepartmentLidA departmentLnameA locationLidI V.LU(S HdepartmentsLseP)<(O0V.LA pLname A pLloc IR (<D addLdeptR /

%op,rig/t @ &''"A Oracle) .ll rig/ts reserved)

Passing Parameters: (Camples In t/e slide eCampleA t/e addLdept procedure declares t2o I< Bormal parameters: pLname and pLloc) 0/e values oB t/ese parameters are used in t/e I<S(10 statement to set t/e departmentLname and locationLid columnsA respectivel,)

c ra O l, - On

, em ad .c

ra c O

le In

l ae rn Uste

Oracle Database 11g: Develop PL/SQL Program Units 1 E *'

Passing .ctual Parameters: (Camples

EE Passing parameters using t/e positional notation) (O(%U0( addLdept HS01.I<I< SA &+''I

EE Passing parameters using t/e named notation) (O(%U0( addLdept HpLlocZ\&!''A pLnameZ\S(DU%.0IO<SI

%op,rig/t @ &''"A Oracle) .ll rig/ts reserved)

Passing .ctual Parameters: (Camples Passing actual parameters b, position is s/o2n in t/e Birst call to eCecute addLdept in t/e Birst code eCample in t/e slide) 0/e Birst actual parameter supplies t/e value 01.I<I< Bor t/e name Bormal parameter) 0/e second actual parameter value oB &+'' is assigned b, position to t/e loc Bormal parameter)

Passing parameters using t/e named notation is s/o2n in t/e second code eCample in t/e slide) 0/e loc actual parameterA 2/ic/ is declared as t/e second Bormal parameterA is reBerenced b, name in t/e callA 2/ere it is associated 2it/ t/e actual value oB &!'') 0/e name parameter is associated 2it/ t/e value (DU%.0IO<) 0/e order oB t/e actual parameters is irrelevant iB all parameter values are speciBied) <ote: 8ou must provide a value Bor eac/ parameter unless t/e Bormal parameter is assigned a deBault value) SpeciB,ing deBault values Bor Bormal parameters is discussed neCt)

c ra O l, - On

, em ad .c

ra c O

le

l ae rn Uste

Oracle Database 11g: Develop PL/SQL Program Units 1 E *1

In

Using t/e D(:.UL0 Option Bor t/e Parameters


DeBines deBault values Bor parameters Provides BleCibilit, b, combining t/e positional and named parameterEpassing s,ntaC

%1(.0( O1 1(PL.%( P1O%(DU1( addLdeptH pLname departments)departmentLnameQ08P(:ZSUn5no2nSA pLloc departments)locationLidQ08P( D(:.UL0 1G''I IS 6( I< I<S(10 I<0O departments HdepartmentLidA departmentLnameA locationLidI V.LU(S HdepartmentsLseP)<(O0V.LA pLnameA pLlocIR (<D addLdeptR

(O(%U0( addLdept (O(%U0( addLdept HS.DV(10ISI< SA pLloc Z\ 1&''I (O(%U0( addLdept HpLloc Z\ 1&''I

%op,rig/t @ &''"A Oracle) .ll rig/ts reserved)

Using t/e D(:.UL0 Option Bor Parameters 8ou can assign a deBault value to an I< parameter as Bollo2s: 0/e assignment operator H:ZIA as s/o2n Bor t/e name parameter in t/e slide 0/e D(:.UL0 optionA as s/o2n Bor t/e pLloc parameter in t/e slide

ra c O

>/en deBault values are assigned to Bormal parametersA ,ou can call t/e procedure 2it/out suppl,ing an actual parameter value Bor t/e parameter) 0/usA ,ou can pass diBBerent numbers oB actual parameters to a subprogramA eit/er b, accepting or b, overriding t/e deBault values as rePuired) It is recommended t/at ,ou declare parameters 2it/out deBault values Birst) 0/enA ,ou can add Bormal parameters 2it/ deBault values 2it/out /aving to c/ange ever, call to t/e procedure) <ote: 8ou cannot assign deBault values to t/e OU0 and I< OU0 parameters) 0/e second code boC in t/e slide s/o2s t/ree 2a,s oB invo5ing t/e addLdept procedure: 0/e Birst eCample assigns t/e deBault values Bor eac/ parameter) 0/e second eCample illustrates a combination oB position and named notation to assign values) In t/is caseA using named notation is presented as an eCample) 0/e last eCample uses t/e deBault value Bor t/e name parameterA Un5no2nA and t/e supplied value Bor t/e pLloc parameter)

c ra O l, - On

, em ad .c

le

l ae rn Uste

Oracle Database 11g: Develop PL/SQL Program Units 1 E *&

In

Using t/e D(:.UL0 Option Bor Parameters HcontinuedI 0/e Bollo2ing is t/e result oB t/e second slide code eCample in t/e previous slide:

l c ra O l, - On e

, em ad .c

Usuall,A ,ou can use named notation to override t/e deBault values oB Bormal parameters) 9o2everA ,ou cannot s5ip providing an actual parameter iB t/ere is no deBault value provided Bor a Bormal parameter) <ote: .ll t/e positional parameters s/ould precede t/e named parameters in a subprogram call) Ot/er2iseA ,ou receive an error messageA as s/o2n in t/e Bollo2ing eCample:
(O(%U0( addLdeptHpLnameZ\Sne2 deptSA Sne2 locationSI

ra c O

le In

l ae rn Uste

Oracle Database 11g: Develop PL/SQL Program Units 1 E **

%alling Procedures
8ou can call procedures using anon,mous bloc5sA anot/er procedureA or pac5ages) 8ou must o2n t/e procedure or /ave t/e (O(%U0( privilege)

%1(.0( O1 1(PL.%( P1O%(DU1( processLemplo,ees IS %U1SO1 curLempLcursor IS S(L(%0 emplo,eeLid :1O=emplo,eesR 6( I< :O1 empLrec I< curLempLcursor LOOP raiseLsalar,HempLrec)emplo,eeLidA 1'IR (<D LOOPR %O==I0R (<D processLemplo,eesR /

%op,rig/t @ &''"A Oracle) .ll rig/ts reserved)

%alling Procedures 8ou can invo5e procedures b, using: .non,mous bloc5s .not/er procedure or PL/SQL subprogram (Camples on t/e preceding pages /ave illustrated /o2 to use anon,mous bloc5s Hor t/e (O(%U0( command in SQL Developer or SQLKPlusI)

0/e eCample in t/e slide s/o2s ,ou /o2 to invo5e a procedure Brom anot/er stored procedure) 0/e P1O%(SSL(=PLO8((S stored procedure uses a cursor to process all t/e records in t/e (=PLO8((S table and passes eac/ emplo,eeFs ID to t/e 1.IS(LS.L.18 procedureA 2/ic/ results in a 1'Q salar, increase across t/e compan,) <ote: 8ou must o2n t/e procedure or /ave t/e (O(%U0( privilege)

c ra O l, - On

, em ad .c

ra c O

le In

l ae rn Uste

Oracle Database 11g: Develop PL/SQL Program Units 1 E *!

%alling Procedures Using SQL Developer

1 &

1eplace PLID and PLP(1%(<0 2it/ actual values

%op,rig/t @ &''"A Oracle) .ll rig/ts reserved)

%alling Procedures Using SQL Developer In t/e slide eCampleA t/e raiseLsalar, procedure is called to raise t/e current salar, oB emplo,ee 1G$ H[ #A$''I b, 1' percent as Bollo2s: 1) 1ig/tEclic5 t/e procedure name in t/e Procedures nodeA and t/en clic5 1un) 0/e 1un PL/SQL dialog boC is displa,ed) &) In t/e PL/SQL 6loc5 sectionA c/ange t/e displa,ed Bormal I< and I</OU0 parameter speciBications displa,ed aBter t/e association operatorA XZ\Y to t/e actual values t/at ,ou 2ant to use Bor running or debugging t/e Bunction or procedure) :or eCampleA to raise t/e current salar, oB emplo,ee 1G$ Brom #A$'' b, 1' percentA ,ou can call t/e raiseLsalar, procedure as s/o2n in t/e slide) Provide t/e values Bor t/e ID and P(1%(<0 input parameters t/at are speciBied as 1G$ and 1' respectivel,) 0/is is done b, c/anging t/e displa,ed ID Z\ ID 2it/ ID Z\ 1G$ and P(1%(<0 Z\ P(1%(<0 2it/ P(1%(<0 Z\ 1') *) %lic5 O?) SQL Developer runs t/e procedure) 0/e updated salar, oB "A!$' is s/o2n belo2:

c ra O l, - On

, em ad .c
!

ra c O

le

l ae rn Uste

Oracle Database 11g: Develop PL/SQL Program Units 1 E *+

In

Lesson .genda
Using a modulari4ed and la,ered subprogram design and identiB,ing t/e beneBits oB subprograms >or5ing 2it/ procedures: M %reating and calling procedures M IdentiB,ing t/e available parameterEpassing modes M Using Bormal and actual parameters M Using positionalA namedA or miCed notation 9andling eCceptions in proceduresA removing a procedureA and displa,ing t/e proceduresF inBormation

%op,rig/t @ &''"A Oracle) .ll rig/ts reserved)

l c ra O l, - On ra c O le In l ae rn Uste e

, em ad .c

Oracle Database 11g: Develop PL/SQL Program Units 1 E *$

9andled (Cceptions

%alling procedure

%alled procedure

P1O%(DU1( P1O%1 ))) IS ))) 6( I< ))) P1O%&Harg1IR ))) (O%(P0IO< ))) (<D P1O%1R

P1O%(DU1( P1O%& ))) IS ))) 6( I< ))) (O%(P0IO< ))) (<D P1O%&R
%ontrol returns to calling procedure

(Cception raised (Cception /andled

%op,rig/t @ &''"A Oracle) .ll rig/ts reserved)

9andled (Cceptions >/en ,ou develop procedures t/at are called Brom ot/er proceduresA ,ou s/ould be a2are oB t/e eBBects t/at /andled and un/andled eCceptions /ave on t/e transaction and t/e calling procedure)

ra c O

>/en an eCception is raised in a called procedureA t/e control immediatel, goes to t/e eCception section oB t/at bloc5) .n eCception is considered /andled iB t/e eCception section provides a /andler Bor t/e eCception raised) >/en an eCception occurs and is /andledA t/e Bollo2ing code Blo2 ta5es place: 1) 0/e eCception is raised) &) %ontrol is transBerred to t/e eCception /andler) *) 0/e bloc5 is terminated) !) 0/e calling program/bloc5 continues to eCecute as iB not/ing /as /appened) IB a transaction 2as started Ht/at isA iB an, data manipulation language VD=LW statements eCecuted beBore eCecuting t/e procedure in 2/ic/ t/e eCception 2as raisedIA t/en t/e transaction is unaBBected) . D=L operation is rolled bac5 iB it 2as perBormed 2it/in t/e procedure beBore t/e eCception) <ote: 8ou can eCplicitl, end a transaction b, eCecuting a %O==I0 or 1OLL6.%? operation in t/e eCception section)

c ra O l, - On

, em ad .c

le

l ae rn Uste

Oracle Database 11g: Develop PL/SQL Program Units 1 E *G

In

9andled (Cceptions: (Cample

%1(.0( P1O%(DU1( addLdepartmentH pLname V.1%9.1&A pLmgr <U=6(1A pLloc <U=6(1I IS 6( I< I<S(10 I<0O D(P.10=(<0S HdepartmentLidA departmentLnameA managerLidA locationLidI V.LU(S HD(P.10=(<0SLS(Q)<(O0V.LA pLnameA pLmgrA pLlocIR D6=SLOU0PU0)PU0LLI<(HS.dded Dept: STT pLnameIR (O%(P0IO< >9(< O09(1S 09(< D6=SLOU0PU0)PU0LLI<(HS(rr: adding dept: STT pLnameIR (<DR

%1(.0( P1O%(DU1( createLdepartments IS 6( I< addLdepartmentHS=ediaSA 1''A 1#''IR addLdepartmentHS(ditingSA ""A 1#''IR addLdepartmentHS.dvertisingSA 1'1A 1#''IR (<DR

%op,rig/t @ &''"A Oracle) .ll rig/ts reserved)

9andled (Cceptions: (Cample 0/e t2o procedures in t/e slide are t/e Bollo2ing: 0/e addLdepartment procedure creates a ne2 department record b, allocating a ne2 department number Brom an Oracle sePuenceA and sets t/e departmentLnameA managerLidA and locationLid column values using t/e pLnameA pLmgrA and pLloc parametersA respectivel,) 0/e createLdepartments procedure creates more t/an one department b, using calls to t/e addLdepartment procedure) 0/e addLdepartment procedure catc/es all raised eCceptions in its o2n /andler) >/en createLdepartments is eCecutedA t/e Bollo2ing output is generated:

c ra O l, - On

, em ad .c

ra c O

0/e (diting department 2it/ a managerLid oB "" is not inserted because a Boreign 5e, integrit, constraint violation on managerLid ensures t/at no manager /as an ID oB "") 6ecause t/e eCception 2as /andled in t/e addLdepartment procedureA t/e createLdepartment procedure continues to eCecute) . Puer, on t/e D(P.10=(<0S table 2/ere t/e locationLid is 1#'' s/o2s t/at =edia and .dvertising are added but t/e (diting record is not)

le

l ae rn Uste

Oracle Database 11g: Develop PL/SQL Program Units 1 E *#

In

(Cceptions <ot 9andled

%alling procedure

%alled procedure

P1O%(DU1( P1O%1 ))) IS ))) 6( I< ))) P1O%&Harg1IR ))) (O%(P0IO< ))) (<D P1O%1R

P1O%(DU1( P1O%& ))) IS ))) 6( I< ))) (O%(P0IO< ))) (<D P1O%&R
%ontrol returned to eCception section oB calling procedure

(Cception raised (Cception not /andled

%op,rig/t @ &''"A Oracle) .ll rig/ts reserved)

(Cceptions <ot 9andled .s discussed earlierA 2/en an eCception is raised in a called procedureA control immediatel, goes to t/e eCception section oB t/at bloc5) IB t/e eCception section does not provide a /andler Bor t/e raised eCceptionA t/en it is not /andled) 0/e Bollo2ing code Blo2 occurs: 1) 0/e eCception is raised) &) 0/e bloc5 terminates because no eCception /andler eCistsR an, D=L operations perBormed 2it/in t/e procedure are rolled bac5) *) 0/e eCception propagates to t/e eCception section oB t/e calling procedureUt/at isA control is returned to t/e eCception section oB t/e calling bloc5A iB one eCists) IB an eCception is not /andledA t/en all t/e D=L statements in t/e calling procedure and t/e called procedure are rolled bac5 along 2it/ an, c/anges to an, /ost variables) 0/e D=L statements t/at are not aBBected are statements t/at 2ere eCecuted beBore calling t/e PL/SQL code 2/ose eCceptions are not /andled)

c ra O l, - On

, em ad .c

ra c O

le In

l ae rn Uste

Oracle Database 11g: Develop PL/SQL Program Units 1 E *"

(Cceptions <ot 9andled: (Cample

S(0 S(1V(1OU0PU0 O< %1(.0( P1O%(DU1( addLdepartmentLnoeCH pLname V.1%9.1&A pLmgr <U=6(1A pLloc <U=6(1I IS 6( I< I<S(10 I<0O D(P.10=(<0S HdepartmentLidA departmentLnameA managerLidA locationLidI V.LU(S HD(P.10=(<0SLS(Q)<(O0V.LA pLnameA pLmgrA pLlocIR D6=SLOU0PU0)PU0LLI<(HS.dded Dept: STT pLnameIR (<DR

%1(.0( P1O%(DU1( createLdepartmentsLnoeC IS 6( I< addLdepartmentLnoeCHS=ediaSA 1''A 1#''IR addLdepartmentLnoeCHS(ditingSA ""A 1#''IR addLdepartmentLnoeCHS.dvertisingSA 1'1A 1#''IR (<DR

%op,rig/t @ &''"A Oracle) .ll rig/ts reserved)

(Cceptions <ot 9andled: (Cample 0/e code eCample in t/e slide s/o2s addLdepartmentLnoeCA 2/ic/ does not /ave an eCception section) In t/is caseA t/e eCception occurs 2/en t/e (diting department is added) 6ecause oB t/e lac5 oB eCception /andling in eit/er oB t/e subprogramsA no ne2 department records are added into t/e D(P.10=(<0S table) (Cecuting t/e createLdepartmentsLnoeC procedure produces a result t/at is similar to t/e Bollo2ing:

c ra O l, - On

, em ad .c

ra c O

le In

.lt/oug/ t/e results s/o2 t/at t/e =edia department 2as addedA its operation is rolled bac5 because t/e eCception 2as not /andled in eit/er oB t/e subprograms invo5ed)

l ae rn Uste

Oracle Database 11g: Develop PL/SQL Program Units 1 E !'

1emoving Procedures: Using t/e D1OP SQL Statement or SQL Developer


Using t/e D1OP statement:

D1OP P1O%(DU1( raiseLsalar,R

Using SQL Developer:

& 1

%op,rig/t @ &''"A Oracle) .ll rig/ts reserved)

1emoving Procedures: Using t/e D1OP SQL Statement or SQL Developer >/en a stored procedure is no longer rePuiredA ,ou can use t/e D1OP P1O%(DU1( SQL statement Bollo2ed b, t/e procedureFs name to remove it as Bollo2s: D1OP P1O%(DU1( procedureLname

8ou can also use SQL Developer to drop a stored procedure as Bollo2s: 1) 1ig/tEclic5 t/e procedure name in t/e Procedures nodeA and t/en clic5 Drop) 0/e Drop dialog boC is displa,ed) &) %lic5 .ppl, to drop t/e procedure) <ote >/et/er successBul or notA eCecuting a data deBinition language HDDLI command suc/ as D1OP P1O%(DU1( commits an, pending transactions t/at cannot be rolled bac5) 8ou mig/t /ave to reBres/ t/e Procedures node beBore ,ou can see t/e results oB t/e drop operation) 0o reBres/ t/e Procedures nodeA rig/tEclic5 t/e procedure name in t/e Procedures nodeA and t/en clic5 1eBres/)

c ra O l, - On

, em ad .c

ra c O

le

l ae rn Uste

Oracle Database 11g: Develop PL/SQL Program Units 1 E !1

In

Vie2ing Procedure InBormation Using t/e Data Dictionar, Vie2s


D(S%1I6( userLsource

S(L(%0 teCt :1O=userLsource >9(1( name Z S.DDLD(P0S .<D t,pe Z SP1O%(DU1(S O1D(1 68 lineR

%op,rig/t @ &''"A Oracle) .ll rig/ts reserved)

Vie2ing Procedure in t/e Data Dictionar, 0/e source code Bor PL/SQL subprograms is stored in t/e data dictionar, tables) 0/e source code is accessible to PL/SQL procedures t/at are successBull, or unsuccessBull, compiled) 0o vie2 t/e PL/SQL source code stored in t/e data dictionar,A eCecute a S(L(%0 statement on t/e Bollo2ing tables: 0/e US(1LSOU1%( table to displa, PL/SQL code t/at ,ou o2n 0/e .LLLSOU1%( table to displa, PL/SQL code to 2/ic/ ,ou /ave been granted t/e (O(%U0( rig/t b, t/e o2ner oB t/at subprogram code 0/e Puer, eCample s/o2s all t/e columns provided b, t/e US(1LSOU1%( table: 0/e 0(O0 column /olds a line oB PL/SQL source code) 0/e <.=( column /olds t/e name oB t/e subprogram in uppercase teCt) 0/e 08P( column /olds t/e subprogram t,peA suc/ as P1O%(DU1( or :U<%0IO<) 0/e LI<( column stores t/e line number Bor eac/ source code line) 0/e .LLLSOU1%( table provides an O><(1 column in addition to t/e preceding columns)

c ra O l, - On

, em ad .c

ra c O

le

<ote: 8ou cannot displa, t/e source code Bor Oracle PL/SQL builtEin pac5agesA or PL/SQL 2/ose source code /as been 2rapped b, using a >1.P utilit,) 0/e >1.P utilit, converts t/e PL/SQL source code into a Borm t/at cannot be decip/ered b, /umans)

l ae rn Uste

Oracle Database 11g: Develop PL/SQL Program Units 1 E !&

In

Vie2ing Procedures InBormation Using SQL Developer

* 1 &

%op,rig/t @ &''"A Oracle) .ll rig/ts reserved)

Vie2ing Procedures InBormation Using SQL Developer 0o vie2 a procedureFs code in SQL DeveloperA use t/e Bollo2ing steps: 1) %lic5 t/e Procedures node in t/e %onnections tab) &) %lic5 t/e procedureFs name) *) 0/e procedureSs code is displa,ed in t/e %ode tab as s/o2n in t/e slide)

c ra O l, - On

, em ad .c

ra c O

le In

l ae rn Uste

Oracle Database 11g: Develop PL/SQL Program Units 1 E !*

Qui4
:ormal parameters are literal valuesA variablesA and eCpressions used in t/e parameter list oB t/e calling subprogram 1) 0rue &) :alse

%op,rig/t @ &''"A Oracle) .ll rig/ts reserved)

.ns2er: & :ormal and .ctual Hor argumentsI Parameters :ormal parameters: Local variables declared in t/e parameter list oB a subprogram speciBication) .ctual parameters: Literal valuesA variablesA and eCpressions used in t/e parameter list oB t/e calling subprogram)

c ra O l, - On

, em ad .c

ra c O

le In

l ae rn Uste

Oracle Database 11g: Develop PL/SQL Program Units 1 E !!

Summar,
In t/is lessonA ,ou s/ould /ave learned /o2 to: IdentiB, t/e beneBits oB modulari4ed and la,ered subprogram design %reate and call procedures Use Bormal and actual parameters Use positionalA namedA or miCed notation Bor passing parameters IdentiB, t/e available parameterEpassing modes 9andle eCceptions in procedures 1emove a procedure Displa, t/e proceduresF inBormation

%op,rig/t @ &''"A Oracle) .ll rig/ts reserved)

l c ra O l, - On ra c O le In l ae rn Uste e

, em ad .c

Oracle Database 11g: Develop PL/SQL Program Units 1 E !+

Practice 1 Overvie2: %reatingA %ompilingA and %alling Procedures


0/is practice covers t/e Bollo2ing topics: %reating stored procedures to:
M Insert ne2 ro2s into a table using t/e supplied parameter values M Update data in a table Bor ro2s t/at matc/ t/e supplied parameter values M Delete ro2s Brom a table t/at matc/ t/e supplied parameter values M Quer, a table and retrieve data based on supplied parameter values

9andling eCceptions in procedures %ompiling and invo5ing procedures

%op,rig/t @ &''"A Oracle) .ll rig/ts reserved)

Practice 1: Overvie2 In t/is practiceA ,ou createA compileA and invo5e procedures t/at issue D=L and Puer, commands) 8ou also learn /o2 to /andle eCceptions in procedures)

IB ,ou encounter compilation errors 2/en ,ou eCecute proceduresA ,ou can use t/e %ompilerE Log tab in SQL Developer) <ote: It is recommended to use SQL Developer Bor t/is practice) Important .ll practices in t/is course and t/e practice solutions assume t/at ,ou create ob3ects suc/ as proceduresA BunctionsA and so on using t/e SQL >or5s/eet area in SQL Developer) >/en ,ou create an ob3ect in t/e SQL >or5s/eet areaA ,ou need to reBres/ t/e ob3ect node in order Bor t/e ne2 ob3ect to be displa,ed in t/e <avigator tree) 0o compile t/e ne2l, created ob3ectA ,ou can rig/tEclic5 t/e ob3ect name in t/e <avigator treeA and t/en select %ompile Brom t/e s/ortcut menu) :or eCampleA aBter ,ou enter t/e code to create a procedure in t/e SQL >or5s/eet areaA ,ou clic5 t/e 1un Script icon Hor press :+I to run t/e code) 0/is creates and compiles t/e procedure) .lternativel,A ,ou can create ob3ects suc/ as procedures using t/e P1O%(DU1(S node in t/e <avigator treeA and t/en compile t/e procedure) %reating ob3ects using t/e <avigator tree automaticall, displa,s t/e ne2l, created ob3ect)

c ra O l, - On

, em ad .c

ra c O

le

l ae rn Uste

Oracle Database 11g: Develop PL/SQL Program Units 1 E !$

In

%reating :unctions and Debugging Subprograms

%op,rig/t @ &''"A Oracle) .ll rig/ts reserved)

l c ra O l, - On ra c O le In l ae rn Uste e

, em ad .c

Ob3ectives
.Bter completing t/is lessonA ,ou s/ould be able to do t/e Bollo2ing: DiBBerentiate bet2een a procedure and a Bunction Describe t/e uses oB Bunctions %reate stored Bunctions Invo5e a Bunction 1emove a Bunction Understand t/e basic Bunctionalit, oB t/e SQL Developer debugger

%op,rig/t @ &''"A Oracle) .ll rig/ts reserved)

Lesson .im In t/is lessonA ,ou learn /o2 to createA invo5eA and maintain Bunctions)

c ra O l, - On

, em ad .c

ra c O

le In

l ae rn Uste

Oracle Database 11g: Develop PL/SQL Program Units & E &

Lesson .genda
>or5ing 2it/ Bunctions:
M DiBBerentiating bet2een a procedure and a Bunction M Describing t/e uses oB Bunctions M %reatingA invo5ingA and removing stored Bunctions

Introducing t/e SQL Developer debugger

%op,rig/t @ &''"A Oracle) .ll rig/ts reserved)

l c ra O l, - On ra c O le In l ae rn Uste e

, em ad .c

Oracle Database 11g: Develop PL/SQL Program Units & E *

Overvie2 oB Stored :unctions


. Bunction: Is a named PL/SQL bloc5 t/at returns a value %an be stored in t/e database as a sc/ema ob3ect Bor repeated eCecution Is called as part oB an eCpression or is used to provide a parameter value Bor anot/er subprogram %an be grouped into PL/SQL pac5ages

%op,rig/t @ &''"A Oracle) .ll rig/ts reserved)

Overvie2 oB Stored :unctions . Bunction is a named PL/SQL bloc5 t/at can accept parametersA be invo5edA and return a value) In generalA ,ou use a Bunction to compute a value) :unctions and procedures are structured ali5e) . Bunction must return a value to t/e calling environmentA 2/ereas a procedure returns 4ero or more values to its calling environment) Li5e a procedureA a Bunction /as a /eaderA a declarative sectionA an eCecutable sectionA and an optional eCceptionE/andling section) . Bunction must /ave a 1(0U1< clause in t/e /eader and at least one 1(0U1< statement in t/e eCecutable section) :unctions can be stored in t/e database as sc/ema ob3ects Bor repeated eCecution) . Bunction t/at is stored in t/e database is reBerred to as a stored Bunction) :unctions can also be created on clientEside applications) :unctions promote reusabilit, and maintainabilit,) >/en validatedA t/e, can be used in an, number oB applications) IB t/e processing rePuirements c/angeA onl, t/e Bunction needs to be updated) . Bunction ma, also be called as part oB a SQL eCpression or as part oB a PL/SQL eCpression) In t/e conteCt oB a SQL eCpressionA a Bunction must obe, speciBic rules to control side eBBects) In a PL/SQL eCpressionA t/e Bunction identiBier acts li5e a variable 2/ose value depends on t/e parameters passed to it) :unctions Hand proceduresI can be grouped into PL/SQL pac5ages) Pac5ages ma5e code even more reusable and maintainable) Pac5ages are covered in t/e lessons titled X%reating Pac5agesY and X>or5ing 2it/ Pac5ages)Y

c ra O l, - On

, em ad .c

ra c O

le

l ae rn Uste

Oracle Database 11g: Develop PL/SQL Program Units & E !

In

%reating :unctions
0/e PL/SQL bloc5 must /ave at least one 1(0U1< statement)

%1(.0( VO1 1(PL.%(W :U<%0IO< BunctionLname VHparameter1 Vmode1W datat,pe1A ) ) )IW 1(0U1< datat,pe IST.S VlocalLvariableLdeclarationsR ) ) )W PL/SQL 6loc56( I< EE actionsR 1(0U1< eCpressionR (<D VBunctionLnameWR

%op,rig/t @ &''"A Oracle) .ll rig/ts reserved)

S,ntaC Bor %reating :unctions . Bunction is a PL/SQL bloc5 t/at returns a value) . 1(0U1< statement must be provided to return a value 2it/ a data t,pe t/at is consistent 2it/ t/e Bunction declaration) 8ou create ne2 Bunctions 2it/ t/e %1(.0( :U<%0IO< statementA 2/ic/ ma, declare a list oB parametersA must return one valueA and must deBine t/e actions to be perBormed b, t/e standard PL/SQL bloc5) 8ou s/ould consider t/e Bollo2ing points about t/e %1(.0( :U<%0IO< statement: 0/e 1(PL.%( option indicates t/at iB t/e Bunction eCistsA it is dropped and replaced 2it/ t/e ne2 version t/at is created b, t/e statement) 0/e 1(0U1< data t,pe must not include a si4e speciBication) 0/e PL/SQL bloc5 starts 2it/ a 6( I< aBter t/e declaration oB an, local variables and ends 2it/ an (<DA optionall, Bollo2ed b, t/e BunctionLname) 0/ere must be at least one 1(0U1< eCpression statement) 8ou cannot reBerence /ost or bind variables in t/e PL/SQL bloc5 oB a stored Bunction) <ote: .lt/oug/ t/e OU0 and I< OU0 parameter modes can be used 2it/ BunctionsA it is not good programming practice to use t/em 2it/ Bunctions) 9o2everA iB ,ou need to return more t/an one value Brom a BunctionA consider returning t/e values in a composite data structure suc/ as a PL/SQL record or a PL/SQL table)

c ra O l, - On

, em ad .c

ra c O

le

l ae rn Uste

Oracle Database 11g: Develop PL/SQL Program Units & E +

In

0/e DiBBerence 6et2een Procedures and :unctions


Procedures
(Cecute as a PL/SQL statement Do not contain 1(0U1< clause in t/e /eader %an pass values HiB an,I using output parameters %an contain a 1(0U1< statement 2it/out a value

:unctions
Invo5e as part oB an eCpression =ust contain a 1(0U1< clause in t/e /eader

=ust return a single value =ust contain at least one 1(0U1< statement

%op,rig/t @ &''"A Oracle) .ll rig/ts reserved)

0/e DiBBerence 6et2een Procedures and :unctions 8ou create a procedure to store a series oB actions Bor later eCecution) . procedure can contain 4ero or more parameters t/at can be transBerred to and Brom t/e calling environmentA but a procedure does not /ave to return a value) . procedure can call a Bunction to assist 2it/ its actions) <ote: . procedure containing a single OU0 parameter 2ould be better re2ritten as a Bunction returning t/e value)

8ou create a Bunction 2/en ,ou 2ant to compute a value t/at must be returned to t/e calling environment) . Bunction can contain 4ero or more parameters t/at are transBerred Brom t/e calling environment) :unctions t,picall, return onl, a single valueA and t/e value is returned t/roug/ a 1(0U1< statement) :unctions used in SQL statements s/ould not use OU0 or I< OU0 mode parameters) .lt/oug/ a Bunction using output parameters can be used in a PL/SQL procedure or bloc5A it cannot be used in SQL statements)

c ra O l, - On

, em ad .c

ra c O

le

l ae rn Uste

Oracle Database 11g: Develop PL/SQL Program Units & E $

In

%reating and 1unning :unctions: Overvie2

Vie2 errors/2arnings in SQL Developer

8(S
Use S9O> (11O1S command in SQLKPlus %reate/edit Bunction %ompiler 2arnings/errorsJ Vie2 compiler 2arnings/errors

<O
Use US(1/.LL/D6.L (11O1S vie2s

Invo5e Bunction

%op,rig/t @ &''"A Oracle) .ll rig/ts reserved)

%reating and 1unning :unctions: Overvie2 0/e diagram in t/e slide illustrates t/e basic steps involved in creating and running a Bunction: 1) %reate t/e Bunction using SQL DeveloperFs Ob3ect <avigator tree or t/e SQL >or5s/eet area) &) %ompile t/e Bunction) 0/e Bunction is created in t/e database) 0/e %1(.0( :U<%0IO< statement creates and stores source code and t/e compiled mEcode in t/e database) 0o compile t/e BunctionA rig/tEclic5 t/e BunctionFs name in t/e Ob3ect <avigator treeA and t/en clic5 %ompile) *) IB t/ere are compilation 2arning or errorsA ,ou can vie2 Hand t/en correctI t/e 2arnings or errors using one oB t/e Bollo2ing met/ods: a) Using t/e SQL Developer interBace Ht/e %ompiler M Log tabI b) Using t/e S9O> (11O1S SQLKPlus command c) Using t/e US(1/.LL/D6.L(11O1S vie2s

c ra O l, - On

, em ad .c

ra c O

!) .Bter successBul compilationA invo5e t/e Bunction to return t/e desired value)

le

l ae rn Uste

Oracle Database 11g: Develop PL/SQL Program Units & E G

In

%reating and Invo5ing a Stored :unction Using t/e %1(.0( :U<%0IO< Statement: (Cample
%1(.0( O1 1(PL.%( :U<%0IO< getLsal HpLid emplo,ees)emplo,eeLidQ08P(I 1(0U1< <U=6(1 IS vLsal emplo,ees)salar,Q08P( :Z 'R 6( I< S(L(%0 salar, I<0OvLsal :1O=emplo,ees >9(1( emplo,eeLid Z pLidR 1(0U1< vLsalR (<D getLsalR /

EE Invo5e t/e Bunction as an eCpression or as EE a parameter value) (O(%U0( dbmsLoutput)putLlineHgetLsalH1''II

%op,rig/t @ &''"A Oracle) .ll rig/ts reserved)

Stored :unction: (Cample 0/e getLsal Bunction is created 2it/ a single input parameter and returns t/e salar, as a number) (Cecute t/e command as s/o2nA or save it in a script Bile and run t/e script to create t/e getLsal Bunction) 0/e getLsal Bunction Bollo2s a common programming practice oB using a single 1(0U1< statement t/at returns a value assigned to a local variable) IB ,our Bunction /as an eCception sectionA t/en it ma, also contain a 1(0U1< statement)

Invo5e a Bunction as part oB a PL/SQL eCpression because t/e Bunction 2ill return a value to t/e calling environment) 0/e second code boC uses t/e SQLKPlus (O(%U0( command to call t/e D6=SLOU0PU0)PU0LLI<( procedure 2/ose argument is t/e return value Brom t/e Bunction getLsal) In t/is caseA getLsal is invo5ed Birst to calculate t/e salar, oB t/e emplo,ee 2it/ ID 1'') 0/e salar, value returned is supplied as t/e value oB t/e D6=SLOU0PU0)PU0LLI<( parameterA 2/ic/ displa,s t/e result HiB ,ou /ave eCecuted a S(0 S(1V(1OU0PU0 O<I)

c ra O l, - On

, em ad .c

ra c O

<ote: . Bunction must al2a,s return a value) 0/e eCample does not return a value iB a ro2 is not Bound Bor a given id) Ideall,A create an eCception /andler to return a value as 2ell)

le

l ae rn Uste

Oracle Database 11g: Develop PL/SQL Program Units & E #

In

Using DiBBerent =et/ods Bor (Cecuting :unctions


EE .s a PL/SQL eCpressionA get t/e results using /ost variables V.1I.6L( bLsalar, <U=6(1 (O(%U0( :bLsalar, :Z getLsalH1''I

EE .s a PL/SQL eCpressionA get t/e results using a local EE variable S(0 S(1V(1OU0PU0 O< D(%L.1( sal emplo,ees)salar,Qt,peR 6( I< sal :Z getLsalH1''IR D6=SLOU0PU0)PU0LLI<(HS0/e salar, is: STT salIR (<DR /

%op,rig/t @ &''"A Oracle) .ll rig/ts reserved)

Using DiBBerent =et/ods Bor (Cecuting :unctions IB Bunctions are 2ell designedA t/e, can be po2erBul constructs) :unctions can be invo5ed in t/e Bollo2ing 2a,s: .s part oB PL/SQL eCpressions: 8ou can use /ost or local variables to /old t/e returned value Brom a Bunction) 0/e Birst eCample in t/e slide uses a /ost variable and t/e second eCample uses a local variable in an anon,mous bloc5) <ote: 0/e beneBits and restrictions t/at appl, to Bunctions 2/en used in a SQL statement are discussed on t/e neCt Be2 pages)

c ra O l, - On

, em ad .c

ra c O

le In

l ae rn Uste

Oracle Database 11g: Develop PL/SQL Program Units & E "

Using DiBBerent =et/ods Bor (Cecuting :unctions


EE Use as a parameter to anot/er subprogram (O(%U0( dbmsLoutput)putLlineHgetLsalH1''II

EE Use in a SQL statement Hsub3ect to restrictionsI S(L(%0 3obLidA getLsalHemplo,eeLidI :1O= emplo,eesR

)))

%op,rig/t @ &''"A Oracle) .ll rig/ts reserved)

Using DiBBerent =et/ods Bor (Cecuting :unctions HcontinuedI .s a parameter to anot/er subprogram: 0/e Birst eCample in t/e slide demonstrates t/is usage) 0/e getLsal Bunction 2it/ all its arguments is nested in t/e parameter rePuired b, t/e D6=SLOU0PU0)PU0LLI<( procedure) 0/is comes Brom t/e concept oB nesting Bunctions as discussed in t/e course titled Oracle Database 11g: SQL :undamentals I) .s an eCpression in a SQL statement: 0/e second eCample in t/e slide s/o2s /o2 a Bunction can be used as a singleEro2 Bunction in a SQL statement)

c ra O l, - On

, em ad .c

ra c O

le In

l ae rn Uste

Oracle Database 11g: Develop PL/SQL Program Units & E 1'

%reating and %ompiling :unctions Using SQL Developer

& 1

%op,rig/t @ &''"A Oracle) .ll rig/ts reserved)

%reating and %ompiling :unctions Using SQL Developer 8ou can create a ne2 Bunction in SQL Developer using t/e Bollo2ing steps: 1) 1ig/tEclic5 t/e :unctions node) &) Select <e2 :unction Brom t/e s/ortcut menu) 0/e %reate PL/SQL :unction dialog boC is displa,ed) *) Select t/e sc/emaA Bunction nameA and t/e parameters list Husing t/e N iconIA and t/en clic5 O?) 0/e code editor Bor t/e Bunction is displa,ed) !) (nter t/e BunctionFs code) +) 0o compile t/e BunctionA clic5 t/e %ompile icon) <ote 0o create a ne2 Bunction in SQL DeveloperA ,ou can also enter t/e code in t/e SQL >or5s/eetA and t/en clic5 t/e 1un Script icon) :or additional inBormation about creating Bunctions in SQL DeveloperA access t/e appropriate online /elp topic titled X%reate PL/SQL Subprogram :unction or Procedure)Y

c ra O l, - On

, em ad .c

ra c O

le

l ae rn Uste

Oracle Database 11g: Develop PL/SQL Program Units & E 11

In

(Cecuting :unctions Using SQL Developer

1 &

1eplace t/e second PLID 2it/ t/e actual valueA 1''

%op,rig/t @ &''"A Oracle) .ll rig/ts reserved)

(Cecuting :unctions Using SQL Developer 8ou can eCecute a Bunction in SQL Developer using t/e Bollo2ing steps: 1) %lic5 t/e :unctions node) &) 1ig/tEclic5 t/e BunctionFs nameA and t/en select 1un) 0/e 1un PL/SQL dialog boC is displa,ed) *) 1eplace t/e second parameter name 2it/ t/e actual parameter value as s/o2n in t/e slide eCample) !) %lic5 O?) <ote: :or additional inBormation about running Bunctions in SQL DeveloperA access t/e online /elp topic titled X1unning and Debugging :unctions and Procedures)Y

c ra O l, - On

, em ad .c

ra c O

le In

l ae rn Uste

Oracle Database 11g: Develop PL/SQL Program Units & E 1&

.dvantages oB UserEDeBined :unctions in SQL Statements


%an eCtend SQL 2/ere activities are too compleCA too a252ardA or unavailable 2it/ SQL %an increase eBBicienc, 2/en used in t/e >9(1( clause to Bilter dataA as opposed to Biltering t/e data in t/e application %an manipulate data values

%op,rig/t @ &''"A Oracle) .ll rig/ts reserved)

.dvantages oB UserEDeBined :unctions in SQL Statements SQL statements can reBerence PL/SQL userEdeBined Bunctions an,2/ere a SQL eCpression is allo2ed) :or eCampleA a userEdeBined Bunction can be used an,2/ere t/at a builtEin SQL BunctionA suc/ as UPP(1HIA can be placed)

.dvantages Permits calculations t/at are too compleCA a252ardA or unavailable 2it/ SQL) :unctions increase data independence b, processing compleC data anal,sis 2it/in t/e Oracle serverA rat/er t/an b, retrieving t/e data into an application Increases eBBicienc, oB Pueries b, perBorming Bunctions in t/e Puer, rat/er t/an in t/e application =anipulates ne2 t,pes oB data HBor eCampleA latitude and longitudeI b, encoding c/aracter strings and using Bunctions to operate on t/e strings

c ra O l, - On

, em ad .c

ra c O

le In

l ae rn Uste

Oracle Database 11g: Develop PL/SQL Program Units & E 1*

Using a :unction in a SQL (Cpression: (Cample

%1(.0( O1 1(PL.%( :U<%0IO< taCHpLvalue I< <U=6(1I 1(0U1< <U=6(1 IS 6( I< 1(0U1< HpLvalue K ')'#IR (<D taCR / S(L(%0 emplo,eeLidA lastLnameA salar,A taCHsalar,I :1O=emplo,ees >9(1( departmentLid Z 1''R

%op,rig/t @ &''"A Oracle) .ll rig/ts reserved)

:unction in SQL (Cpressions: (Cample 0/e eCample in t/e slide s/o2s /o2 to create a taC Bunction to calculate income taC) 0/e Bunction accepts a <U=6(1 parameter and returns t/e calculated income taC based on a simple Blat taC rate oB #Q) 0o eCecute t/e code s/o2n in t/e slide eCample in SQL DeveloperA enter t/e code in t/e SQL >or5s/eetA and t/en clic5 t/e 1un Script icon) 0/e taC Bunction is invo5ed as an eCpression in t/e S(L(%0 clause along 2it/ t/e emplo,ee IDA last nameA and salar, Bor emplo,ees in a department 2it/ ID 1'') 0/e return result Brom t/e taC Bunction is displa,ed 2it/ t/e regular output Brom t/e Puer,)

c ra O l, - On

, em ad .c

ra c O

le In

l ae rn Uste

Oracle Database 11g: Develop PL/SQL Program Units & E 1!

%alling UserEDeBined :unctions in SQL Statements


UserEdeBined Bunctions act li5e builtEin singleEro2 Bunctions and can be used in: 0/e S(L(%0 list or clause oB a Puer, %onditional eCpressions oB t/e >9(1( and 9.VI< clauses 0/e %O<<(%0 68A S0.10 >I09A O1D(1 68A and 1OUP 68 clauses oB a Puer, 0/e V.LU(S clause oB t/e I<S(10 statement 0/e S(0 clause oB t/e UPD.0( statement

%op,rig/t @ &''"A Oracle) .ll rig/ts reserved)

%alling UserEDeBined :unctions in SQL Statements . PL/SQL userEdeBined Bunction can be called Brom an, SQL eCpression 2/ere a builtEin singleE ro2 Bunction can be called as s/o2n in t/e Bollo2ing eCample:
S(L(%0 emplo,eeLidA taCHsalar,I :1O=emplo,ees >9(1(

taCHsalar,I \ HS(L(%0 =.OHtaCHsalar,II :1O= emplo,ees >9(1( departmentLid Z *'I

O1D(1 68 taCHsalar,I D(S%R

c ra O l, - On

, em ad .c

ra c O

le In

l ae rn Uste

Oracle Database 11g: Develop PL/SQL Program Units & E 1+

1estrictions >/en %alling :unctions Brom SQL (Cpressions


UserEdeBined Bunctions t/at are callable Brom SQL eCpressions must:
M 6e stored in t/e database M .ccept onl, I< parameters 2it/ valid SQL data t,pesA not PL/SQLEspeciBic t,pes M 1eturn valid SQL data t,pesA not PL/SQLEspeciBic t,pes

>/en calling Bunctions in SQL statements:


M 8ou must o2n t/e Bunction or /ave t/e (O(%U0( privilege M 8ou ma, need to enable t/e P.1.LL(LL(<.6L( 5e,2ord to allo2 a parallel eCecution oB t/e SQL statement

%op,rig/t @ &''"A Oracle) .ll rig/ts reserved)

1estrictions >/en %alling :unctions Brom SQL (Cpressions 0/e userEdeBined PL/SQL Bunctions t/at are callable Brom SQL eCpressions must meet t/e Bollo2ing rePuirements: 0/e Bunction must be stored in t/e database) 0/e Bunction parameters must be I< and oB valid SQL data t,pes) 0/e Bunctions must return data t,pes t/at are valid SQL data t,pes) 0/e, cannot be PL/SQLEspeciBic data t,pes suc/ as 6OOL(.<A 1(%O1DA or 0.6L() 0/e same restriction applies to t/e parameters oB t/e Bunction) 0/e Bollo2ing restrictions appl, 2/en calling a Bunction in a SQL statement: Parameters must use positional notation) <amed notation is not supported) 8ou must o2n or /ave t/e (O(%U0( privilege on t/e Bunction) 8ou ma, need to enable t/e P.1.LL(LL(<.6L( 5e,2ord to allo2 a parallel eCecution oB t/e SQL statement using t/e Bunction) (ac/ parallel slave 2ill /ave private copies oB t/e BunctionFs local variables) Ot/er restrictions on a userEdeBined Bunction include t/e Bollo2ing: It cannot be called Brom t/e %9(%? constraint clause oB a %1(.0( 0.6L( or .L0(1 0.6L( statement) In additionA it cannot be used to speciB, a deBault value Bor a column) Onl, stored Bunctions are callable Brom SQL statements) Stored procedures cannot be called unless invo5ed Brom a Bunction t/at meets t/e preceding rePuirements)

c ra O l, - On

, em ad .c

ra c O

le

l ae rn Uste

Oracle Database 11g: Develop PL/SQL Program Units & E 1$

In

%ontrolling Side (BBects >/en %alling :unctions Brom SQL (Cpressions


:unctions called Brom: . S(L(%0 statement cannot contain D=L statements .n UPD.0( or D(L(0( statement on a table 0 cannot Puer, or contain D=L on t/e same table 0 SQL statements cannot end transactions Ht/at isA cannot eCecute %O==I0 or 1OLL6.%? operationsI

<ote: %alls to subprograms t/at brea5 t/ese restrictions are also not allo2ed in t/e Bunction)

%op,rig/t @ &''"A Oracle) .ll rig/ts reserved)

%ontrolling Side (BBects >/en %alling :unctions Brom SQL (Cpressions 0o eCecute a SQL statement t/at calls a stored BunctionA t/e Oracle server must 5no2 2/et/er t/e Bunction is Bree oB speciBic side eBBects) 0/e side eBBects are unacceptable c/anges to database tables) .dditional restrictions appl, 2/en a Bunction is called in eCpressions oB SQL statements: >/en a Bunction is called Brom a S(L(%0 statement or a parallel UPD.0( or D(L(0( statementA t/e Bunction cannot modiB, database tables) >/en a Bunction is called Brom an UPD.0( or D(L(0( statementA t/e Bunction cannot Puer, or modiB, database tables modiBied b, t/at statement) >/en a Bunction is called Brom a S(L(%0A I<S(10A UPD.0(A or D(L(0( statementA t/e Bunction cannot eCecute directl, or indirectl, t/roug/ anot/er subprogram or SQL transaction control statements suc/ as: E . %O==I0 or 1OLL6.%? statement E . session control statement Hsuc/ as S(0 1OL(I E . s,stem control statement Hsuc/ as .L0(1 S8S0(=I E .n, DDL statements Hsuc/ as %1(.0(I because t/e, are Bollo2ed b, an automatic commit

c ra O l, - On

, em ad .c

ra c O

le

l ae rn Uste

Oracle Database 11g: Develop PL/SQL Program Units & E 1G

In

1estrictions on %alling :unctions Brom SQL: (Cample


%1(.0( O1 1(PL.%( :U<%0IO< dmlLcallLsPlHpLsal <U=6(1I 1(0U1< <U=6(1 IS 6( I< I<S(10 I<0O emplo,eesHemplo,eeLidA lastLnameA emailA /ireLdateA 3obLidA salar,I V.LU(SH1A S:rostSA S3Brost]compan,)comSA S8SD.0(A SS.L=.<SA pLsalIR 1(0U1< HpLsal N 1''IR (<DR UPD.0( emplo,ees S(0 salar, Z dmlLcallLsPlH&'''I >9(1( emplo,eeLid Z 1G'R

%op,rig/t @ &''"A Oracle) .ll rig/ts reserved)

1estrictions on %alling :unctions Brom SQL: (Cample 0/e dmlLcallLsPl Bunction in t/e slide contains an I<S(10 statement t/at inserts a ne2 record into t/e (=PLO8((S table and returns t/e input salar, value incremented b, 1'') 0/is Bunction is invo5ed in t/e UPD.0( statement t/at modiBies t/e salar, oB emplo,ee 1G' to t/e amount returned Brom t/e Bunction) 0/e UPD.0( statement Bails 2it/ an error indicating t/at t/e table is mutating Ht/at isA c/anges are alread, in progress in t/e same tableI) In t/e Bollo2ing eCampleA t/e Puer,LcallLsPl Bunction Pueries t/e S.L.18 column oB t/e (=PLO8((S table:
%1(.0( O1 1(PL.%( :U<%0IO< Puer,LcallLsPlHpLa <U=6(1I 1(0U1< <U=6(1 IS vLs <U=6(1R 6( I< S(L(%0 salar, I<0O vLs :1O= emplo,ees >9(1( emplo,eeLid Z 1G'R 1(0U1< HvLs N pLaIR (<DR

c ra O l, - On

, em ad .c

ra c O

le

>/en invo5ed Brom t/e Bollo2ing UPD.0( statementA it returns t/e error message similar to t/e error message s/o2n in t/e slide:
UPD.0( emplo,ees S(0 salar, Z Puer,LcallLsPlH1''I >9(1( emplo,eeLid Z 1G'R Oracle Database 11g: Develop PL/SQL Program Units & E 1#

l ae rn Uste

In

<amed and =iCed <otation Brom SQL


PL/SQL allo2s arguments in a subroutine call to be speciBied using positionalA namedA or miCed notation) Prior to Oracle Database 11gA onl, t/e positional notation is supported in calls Brom SQL) Starting in Oracle Database 11gA named and miCed notation can be used Bor speciB,ing arguments in calls to PL/SQL subroutines Brom SQL statements) :or long parameter listsA 2it/ most /aving deBault valuesA ,ou can omit values Brom t/e optional parameters) 8ou can avoid duplicating t/e deBault value oB t/e optional parameter at eac/ call site)

%op,rig/t @ &''"A Oracle) .ll rig/ts reserved)

l c ra O l, - On ra c O le In l ae rn Uste e

, em ad .c

Oracle Database 11g: Develop PL/SQL Program Units & E 1"

<amed and =iCed <otation Brom SQL: (Cample


%1(.0( O1 1(PL.%( :U<%0IO< BH pLparameterL1 I< <U=6(1 D(:.UL0 1A pLparameterL+ I< <U=6(1 D(:.UL0 +I 1(0U1< <U=6(1 IS vLvar numberR 6( I< vLvar :Z pLparameterL1 N HpLparameterL+ K &IR 1(0U1< vLvarR (<D BR /

S(L(%0 BHpLparameterL+ Z\ 1'I :1O= DU.LR

%op,rig/t @ &''"A Oracle) .ll rig/ts reserved)

(Cample oB Using <amed and =iCed <otation Brom a SQL Statement In t/e eCample in t/e slideA t/e call to t/e Bunction B 2it/in t/e SQL S(L(%0 statement uses t/e named notation) 6eBore Oracle Database 11gA ,ou could not use t/e named or miCed notation 2/en passing parameters to a Bunction Brom 2it/in a SQL statement) 6eBore Oracle Database 11gA ,ou received t/e Bollo2ing error:
S(L(%0 BHpLparameterL+ Z\ 1'I :1O= DU.LR O1.E''"'G: missing rig/t parent/esis

c ra O l, - On

, em ad .c

ra c O

le In

l ae rn Uste

Oracle Database 11g: Develop PL/SQL Program Units & E &'

1emoving :unctions: Using t/e D1OP SQL Statement or SQL Developer


Using t/e D1OP statement:
D1OP :U<%0IO< BR

Using SQL Developer:


1 &

%op,rig/t @ &''"A Oracle) .ll rig/ts reserved)

1emoving :unctions Using t/e D1OP statement

l c ra O l, - On e

>/en a stored Bunction is no longer rePuiredA ,ou can use a SQL statement in SQLKPlus to drop it) 0o remove a stored Bunction b, using SQLKPlusA eCecute t/e D1OP :U<%0IO< SQL command) Using %1(.0( O1 1(PL.%( Versus D1OP and %1(.0( 0/e 1(PL.%( clause in t/e %1(.0( O1 1(PL.%( s,ntaC is ePuivalent to dropping a Bunction and reEcreating it) >/en ,ou use t/e %1(.0( O1 1(PL.%( s,ntaCA t/e privileges granted on t/is ob3ect to ot/er users remain t/e same) >/en ,ou D1OP a Bunction and t/en reE create itA all t/e privileges granted on t/is Bunction are automaticall, revo5ed) Using SQL Developer

, em ad .c

ra c O

0o drop a Bunction in SQL DeveloperA rig/tEclic5 t/e Bunction name in t/e :unctions nodeA and t/en select Drop) 0/e Drop dialog boC is displa,ed) 0o drop t/e BunctionA clic5 .ppl,)

le

l ae rn Uste

Oracle Database 11g: Develop PL/SQL Program Units & E &1

In

Vie2ing :unctions Using Data Dictionar, Vie2s


D(S%1I6( US(1LSOU1%(

S(L(%0 :1O= >9(1( O1D(1

teCt userLsource t,pe Z S:U<%0IO<S 68 lineR

)))
%op,rig/t @ &''"A Oracle) .ll rig/ts reserved)

Vie2ing :unctions Using Data Dictionar, Vie2s 0/e source code Bor PL/SQL Bunctions is stored in t/e data dictionar, tables) 0/e source code is accessible Bor PL/SQL Bunctions t/at are successBull, or unsuccessBull, compiled) 0o vie2 t/e PL/SQL Bunction code stored in t/e data dictionar,A eCecute a S(L(%0 statement on t/e Bollo2ing tables 2/ere t/e 08P( column value is :U<%0IO<: 0/e US(1LSOU1%( table to displa, t/e PL/SQL code t/at ,ou o2n 0/e .LLLSOU1%( table to displa, t/e PL/SQL code to 2/ic/ ,ou /ave been granted t/e (O(%U0( rig/t b, t/e o2ner oB t/at subprogram code 0/e second eCample in t/e slide uses t/e US(1LSOU1%( table to displa, t/e source code Bor all t/e Bunctions in ,our sc/ema) 8ou can also use t/e US(1LO6;(%0S data dictionar, vie2 to displa, a list oB ,our Bunction names) <ote: 0/e output oB t/e second code eCample in t/e slide 2as generated using t/e (Cecute Statement H:"I icon on t/e toolbar to provide betterEBormatted output)

c ra O l, - On

, em ad .c

ra c O

le

l ae rn Uste

Oracle Database 11g: Develop PL/SQL Program Units & E &&

In

Vie2ing :unctions InBormation Using SQL Developer

1 &

%op,rig/t @ &''"A Oracle) .ll rig/ts reserved)

Vie2ing :unctions InBormation Using SQL Developer 0o vie2 a BunctionFs code in SQL DeveloperA use t/e Bollo2ing steps: 1) %lic5 t/e :unctions node in t/e %onnections tab) &) %lic5 t/e BunctionFs name) *) 0/e BunctionSs code is displa,ed in t/e %ode tab as s/o2n in t/e slide)

c ra O l, - On

, em ad .c

ra c O

le In

l ae rn Uste

Oracle Database 11g: Develop PL/SQL Program Units & E &*

Qui4
. PL/SQL stored Bunction: 1) %an be invo5ed as part oB an eCpression &) =ust contain a 1(0U1< clause in t/e /eader *) =ust return a single value !) =ust contain at least one 1(0U1< statement +) Does not contain a 1(0U1< clause in t/e /eader

%op,rig/t @ &''"A Oracle) .ll rig/ts reserved)

.ns2ers: 1A &A *A !

l c ra O l, - On e

, em ad .c

ra c O

le In

l ae rn Uste

Oracle Database 11g: Develop PL/SQL Program Units & E &!

Practice &E1: Overvie2


0/is practice covers t/e Bollo2ing topics: %reating stored Bunctions:
M 0o Puer, a database table and return speciBic values M 0o be used in a SQL statement M 0o insert a ne2 ro2A 2it/ speciBied parameter valuesA into a database table M Using deBault parameter values

Invo5ing a stored Bunction Brom a SQL statement Invo5ing a stored Bunction Brom a stored procedure

%op,rig/t @ &''"A Oracle) .ll rig/ts reserved)

Practice &E1: Overvie2 It is recommended to use SQL Developer Bor t/is practice)

l e

c ra O l, - On

, em ad .c

ra c O

le In

l ae rn Uste

Oracle Database 11g: Develop PL/SQL Program Units & E &+

Lesson .genda
>or5ing 2it/ Bunctions:
M DiBBerentiating bet2een a procedure and a Bunction M Describing t/e uses oB Bunctions M %reatingA invo5ingA and removing stored Bunctions

Introducing t/e SQL Developer debugger

%op,rig/t @ &''"A Oracle) .ll rig/ts reserved)

l c ra O l, - On ra c O le In l ae rn Uste e

, em ad .c

Oracle Database 11g: Develop PL/SQL Program Units & E &$

Debugging PL/SQL Subprograms Using t/e SQL Developer Debugger


8ou can use t/e debugger to control t/e eCecution oB ,our PL/SQL program) 0o debug a PL/SQL subprogramA a securit, administrator needs to grant t/e Bollo2ing privileges to t/e application developer:
M D(6U .<8 P1O%(DU1( M D(6U %O<<(%0 S(SSIO<

1.<0 D(6U .<8 P1O%(DU1( 0O ora$1R 1.<0 D(6U %O<<(%0 S(SSIO< 0O ora$1R

%op,rig/t @ &''"A Oracle) .ll rig/ts reserved)

=oving 0/roug/ %ode >/ile Debugging 0/e SQL Developer debugger enables ,ou to control t/e eCecution oB ,our program) 8ou can control 2/et/er ,our program eCecutes a single line oB codeA an entire subprogram Hprocedure or BunctionIA or an entire program bloc5) 6, manuall, controlling 2/en t/e program s/ould run and 2/en it s/ould pauseA ,ou can Puic5l, move over t/e sections t/at ,ou 5no2 2or5 correctl, and concentrate on t/e sections t/at are causing problems)

c ra O l, - On

, em ad .c

ra c O

le In

l ae rn Uste

Oracle Database 11g: Develop PL/SQL Program Units & E &G

Debugging a Subprogram: Overvie2

1) (dit procedure

&) .dd brea5points

*) %ompile Bor Debug

$) %/oose debugging toolA and monitor data

+) (nter parameter valueHsI

%op,rig/t @ &''"A Oracle) .ll rig/ts reserved)

l c ra O l, - On ra c O le In l ae rn Uste e

, em ad .c
!) Debug

Oracle Database 11g: Develop PL/SQL Program Units & E &#

0/e Procedure or :unction %ode (diting 0ab

%op,rig/t @ &''"A Oracle) .ll rig/ts reserved)

0/e Procedure or :unction %ode 0ab 0/is tab displa,s a toolbar and t/e teCt oB t/e subprogramA 2/ic/ ,ou can edit) 8ou can set and unset brea5points Bor debugging b, clic5ing to t/e leBt oB t/e t/in vertical line beside eac/ statement 2it/ 2/ic/ ,ou 2ant to associate a brea5point) H>/en a brea5point is setA a red circle is displa,ed)I

c ra O l, - On

, em ad .c

ra c O

le In

l ae rn Uste

Oracle Database 11g: Develop PL/SQL Program Units & E &"

0/e Procedure or :unction 0ab 0oolbar


* + 1
Icon
1) 1un

&

Description
Starts normal eCecution oB t/e Bunction or procedureA and displa,s t/e results in t/e 1unning E Log tab (Cecutes t/e subprogram in debug modeA and displa,s t/e Debugging E Log tabA 2/ic/ includes t/e debugging toolbar Bor controlling eCecution %ompiles t/e subprogram %ompiles t/e subprogram so t/at it can be debugged Displa,s t/e ProBile 2indo2 t/at ,ou use to speciB, parameter values Bor runningA debuggingA or proBiling a PL/SQL Bunction or procedure

&) Debug

*) %ompile !) %ompile Bor Debug +) ProBile

%op,rig/t @ &''"A Oracle) .ll rig/ts reserved)

l c ra O l, - On ra c O le In l ae rn Uste e

, em ad .c

Oracle Database 11g: Develop PL/SQL Program Units & E *'

0/e Debugging M Log 0ab 0oolbar


* 1 &
Icon
1) :ind (Cecution Point &) Step Over

!
Description
oes to t/e neCt eCecution point 6,passes t/e neCt subprogram and goes to t/e neCt statement aBter t/e subprogram (Cecutes a single program statement at a time) IB t/e eCecution point is located on a call to a subprogramA it steps into t/e Birst statement in t/at subprogram Leaves t/e current subprogram and goes to t/e neCt statement 2it/ a brea5point

*) Step Into

!) Step Out

%op,rig/t @ &''"A Oracle) .ll rig/ts reserved)

0/e Debugging M Log 0ab 0oolbar 0/e Debugging E Log contains t/e debugging toolbar and inBormational messages) 1) :ind (Cecution Point: oes to t/e eCecution point Ht/e neCt line oB source code to be eCecuted b, t/e debuggerI &) Step Over: 6,passes t/e neCt subprogram Hunless t/e subprogram /as a brea5pointI and goes to t/e neCt statement aBter t/e subprogram) IB t/e eCecution point is located on a subprogram callA it runs t/at subprogram 2it/out stopping Hinstead oB stepping into itIA and t/en positions t/e eCecution point on t/e statement t/at Bollo2s t/e call) IB t/e eCecution point is located on t/e last statement oB a subprogramA Step Over returns Brom t/e subprogramA placing t/e eCecution point on t/e line oB code t/at Bollo2s t/e call to t/e subprogram Brom 2/ic/ ,ou are returning) *) Step Into: (Cecutes a single program statement at a time) IB t/e eCecution point is located on a call to a subprogramA Step Into steps into t/at subprogram and places t/e eCecution point on its Birst statement) IB t/e eCecution point is located on t/e last statement oB a subprogramA Step Into returns Brom t/e subprogramA placing t/e eCecution point on t/e line oB code t/at Bollo2s t/e call to t/e subprogram Brom 2/ic/ ,ou are returning) !) Step Out: Leaves t/e current subprogram and goes to t/e neCt statement

c ra O l, - On

, em ad .c

ra c O

le

l ae rn Uste

Oracle Database 11g: Develop PL/SQL Program Units & E *1

In

0/e Debugging M Log 0ab 0oolbar

$
Icon
+) Step to (nd oB =et/od $) 1esume G) Pause #) 0erminate

Description
oes to t/e last statement oB t/e current subprogram %ontinues eCecution 9alts eCecution but does not eCit 9alts and eCits t/e eCecution

%op,rig/t @ &''"A Oracle) .ll rig/ts reserved)

0/e Debugging M Log 0ab 0oolbar HcontinuedI +) Step to (nd oB =et/od: oes to t/e last statement oB t/e current subprogram $) 1esume: %ontinues eCecution G) Pause: 9alts eCecution but does not eCitA t/us allo2ing ,ou to resume eCecution #) 0erminate: 9alts and eCits t/e eCecution) 8ou cannot resume eCecution Brom t/is pointR insteadA to start running or debugging Brom t/e beginning oB t/e subprogramA clic5 t/e 1un or Debug icon in t/e Source tab toolbar)

c ra O l, - On

, em ad .c

ra c O

le In

l ae rn Uste

Oracle Database 11g: Develop PL/SQL Program Units & E *&

.dditional 0abs

0ab
6rea5points Smart Data

Description
Displa,s brea5pointsA bot/ s,stemEdeBined and userEdeBined) Displa,s inBormation about variables) 8ou can speciB, t/ese preBerences b, rig/tEclic5ing in t/e Smart Data 2indo2 and selecting PreBerences) Located under t/e code teCt areaR displa,s inBormation about all variables Located under t/e code teCt areaR displa,s inBormation about 2atc/es

Data

>atc/es

%op,rig/t @ &''"A Oracle) .ll rig/ts reserved)

.dditional 0abs Setting (Cpression >atc/es . 2atc/ enables ,ou to monitor t/e c/anging values oB variables or eCpressions as ,our program runs) .Bter ,ou enter a 2atc/ eCpressionA t/e >atc/es 2indo2 displa,s t/e current value oB t/e eCpression) .s ,our program runsA t/e value oB t/e 2atc/ c/anges as ,our program updates t/e values oB t/e variables in t/e 2atc/ eCpression) . 2atc/ evaluates an eCpression according to t/e current conteCtA 2/ic/ is controlled b, t/e selection in t/e Stac5 2indo2) IB ,ou move to a ne2 conteCtA t/e eCpression is reevaluated Bor t/e ne2 conteCt) IB t/e eCecution point moves to a location 2/ere an, oB t/e variables in t/e 2atc/ eCpression are undeBinedA t/e entire 2atc/ eCpression becomes undeBined) IB t/e eCecution point returns to a location 2/ere t/e 2atc/ eCpression can be evaluatedA t/e >atc/es 2indo2 again displa,s t/e value oB t/e 2atc/ eCpression) 0o open t/e >atc/es 2indo2A clic5 Vie2A t/en DebuggerA t/en >atc/es) 0o add a 2atc/A rig/tEclic5 in t/e >atc/es 2indo2 and select .dd >atc/) 0o edit a 2atc/A rig/tEclic5 in t/e >atc/es 2indo2 and select (dit >atc/) <ote: IB ,ou cannot see some oB t/e debugging tabs described in t/is lessonA ,ou can reEdispla, suc/ tabs b, using t/e Vie2 \ Debugger menu option)

c ra O l, - On

, em ad .c

ra c O

le

l ae rn Uste

Oracle Database 11g: Develop PL/SQL Program Units & E **

In

Debugging a Procedure (Cample: %reating a <e2 empLlist Procedure

%op,rig/t @ &''"A Oracle) .ll rig/ts reserved)

Debugging a Procedure (Cample: %reating a <e2 empLlist Procedure 0/e empLlist procedure gat/ers emplo,ee inBormation suc/ t/e emplo,eeFs department nameA IDA nameA salar,A and commission percentage) 0/e procedure creates a record to store t/e emplo,eeFs inBormation) 0/e procedure also creates a table t/at can /old multiple records oB emplo,ees) XiY is a counter) 0/e code opens t/e cursor and Betc/es t/e emplo,eesF records) 0/e code also c/ec5s 2/et/er or not t/ere are more records to Betc/ or 2/et/er t/e number oB records Betc/ed so Bar is less t/an t/e number oB records t/at ,ou speciB,) 0/e code eventuall, prints out t/e emplo,eesF inBormation) 0/e procedure also calls t/e getLlocation Bunction t/at returns t/e name oB t/e cit, in 2/ic/ an emplo,ee 2or5s)

<ote: =a5e sure t/at ,ou are displa,ing t/e procedure code in edit mode) 0o edit t/e procedure codeA clic5 t/e (dit icon on t/e procedureFs toolbar)

c ra O l, - On

, em ad .c

ra c O

le

l ae rn Uste

Oracle Database 11g: Develop PL/SQL Program Units & E *!

In

Debugging a Procedure (Cample: %reating a <e2 getLlocation :unction

%op,rig/t @ &''"A Oracle) .ll rig/ts reserved)

Debugging a Procedure (Cample: %reating a <e2 Procedure 0/is Bunction returns t/e cit, in 2/ic/ an emplo,ee 2or5s) It is called Brom t/e empLlist procedure)

c ra O l, - On

, em ad .c

ra c O

le In

l ae rn Uste

Oracle Database 11g: Develop PL/SQL Program Units & E *+

Setting 6rea5points and %ompiling empLlist Bor Debug =ode

%op,rig/t @ &''"A Oracle) .ll rig/ts reserved)

Setting 6rea5points and %ompiling empLlist Bor Debug =ode In t/e eCample in t/e slideA t/e empLlist procedure is displa,ed in edit modeA and Bour brea5points are added to various locations in t/e code) 0o compile t/e procedure Bor debuggingA rig/tEclic5 t/e codeA and t/en select %ompile Bor Debug Brom t/e s/ortcut menu) 0/e =essages M Log tab displa,s t/e message t/at t/e procedure 2as compiled)

c ra O l, - On

, em ad .c

ra c O

le In

l ae rn Uste

Oracle Database 11g: Develop PL/SQL Program Units & E *$

%ompiling t/e getLlocation :unction Bor Debug =ode

%op,rig/t @ &''"A Oracle) .ll rig/ts reserved)

%ompiling t/e getLlocation :unction Bor Debug =ode In t/e eCample in t/e slideA t/e getLlocation Bunction is displa,ed in edit mode) 0o compile t/e Bunction Bor debuggingA rig/tEclic5 t/e codeA and t/en select %ompile Bor Debug Brom t/e s/ortcut menu) 0/e =essages M Log tab displa,s t/e message t/at t/e Bunction 2as compiled)

c ra O l, - On

, em ad .c

ra c O

le In

l ae rn Uste

Oracle Database 11g: Develop PL/SQL Program Units & E *G

Debugging empLlist and (ntering Values Bor t/e P=.O1O>S Parameter

(nter t/e procedureFs parameter value using t/e anon,mous bloc5)

%op,rig/t @ &''"A Oracle) .ll rig/ts reserved)

Debugging empLlist and (ntering Values Bor t/e P=.O1O>S Parameter

0/e neCt step in t/e debugging process is to debug t/e procedure using an, oB t/e several available met/ods mentioned earlierA suc/ as clic5ing t/e Debug icon on t/e procedureFs toolbar) .n anon,mous bloc5 is displa,edA 2/ere ,ou are prompted to enter t/e parameters Bor t/is procedure) empLlist /as one parameterA P=.O1O>SA 2/ic/ speciBies t/e number oB records to return) 1eplace t/e second P=.O1O>S 2it/ a number suc/ as 1''A and t/en clic5 O?)

c ra O l, - On

, em ad .c

ra c O

le In

l ae rn Uste

Oracle Database 11g: Develop PL/SQL Program Units & E *#

Debugging empLlist: Step Into H:GI t/e %ode

Program control stops at Birst brea5point)

%op,rig/t @ &''"A Oracle) .ll rig/ts reserved)

0/e Step Into Debugging 0ool 0/e Step Into command eCecutes a single program statement at a time) IB t/e eCecution point is located on a call to a subprogramA t/e Step Into command steps into t/at subprogram and places t/e eCecution point on t/e subprogramFs Birst statement) IB t/e eCecution point is located on t/e last statement oB a subprogramA c/oosing Step Into causes t/e debugger to return Brom t/e subprogramA placing t/e eCecution point on t/e line oB code t/at Bollo2s t/e call to t/e subprogram ,ou are returning Brom) 0/e term single stepping reBers to using Step Into to run successivel, t/oug/ t/e statements in ,our program code) 8ou can step into a subprogram in an, oB t/e Bollo2ing 2a,s: Select Debug \ Step IntoA press :GA or clic5 t/e Step Into icon in t/e Debugging M Log toolbar) In t/e eCample in t/e slideA t/e program control is stopped at t/e Birst brea5point in t/e code) 0/e arro2 neCt to t/e brea5point indicated t/at t/is is t/e line oB code t/at 2ill be eCecuted neCt) <ote t/e various tabs at t/e bottom oB t/e 2indo2) <ote: 0/e Step Into and Step Over commands oBBer t/e simplest 2a, oB moving t/roug/ ,our program code) >/ile t/e t2o commands are ver, similarA t/e, eac/ oBBer a diBBerent 2a, to control code eCecution)

c ra O l, - On

, em ad .c

ra c O

le

l ae rn Uste

Oracle Database 11g: Develop PL/SQL Program Units & E *"

In

Debugging empLlist: Step Into H:GI t/e %ode

1 &
Step Into H:GI: Steps into and eCecutes t/e cursor code) %ontrol is transBerred to cursor deBinition)

%op,rig/t @ &''"A Oracle) .ll rig/ts reserved)

Debugging empLlist: Step Into t/e %ode

l c ra O l, - On e

Selecting t/e Step Into command eCecutes a single program statement at a time) IB t/e eCecution point is located on a call to a subprogramA t/e Step Into command steps into t/at subprogram and places t/e eCecution at t/e Birst statement in t/e subprogram) In t/e eCample in t/e slideA pressing :G eCecutes t/e line oB code at t/e Birst brea5point) In t/is caseA program control is transBerred to t/e section 2/ere t/e cursor is deBined)

, em ad .c

ra c O

le In

l ae rn Uste

Oracle Database 11g: Develop PL/SQL Program Units & E !'

Vie2ing t/e Data

%op,rig/t @ &''"A Oracle) .ll rig/ts reserved)

Vie2ing t/e Data >/ile ,ou are debugging ,our codeA ,ou can use t/e Data tab to displa, and modiB, t/e variables) 8ou can also set 2atc/es to monitor a subset oB t/e variables displa,ed in t/e Data tab) 0o displa, or /ide t/e DataA Smart DataA and >atc/ tabs: Select Vie2 \ DebuggerA and t/en select t/e tabs t/at ,ou 2ant to displa, or /ide)

c ra O l, - On

, em ad .c

ra c O

le In

l ae rn Uste

Oracle Database 11g: Develop PL/SQL Program Units & E !1

=odiB,ing t/e Variables >/ile Debugging t/e %ode


&

* !

%op,rig/t @ &''"A Oracle) .ll rig/ts reserved)

=odiB,ing t/e Variables >/ile Debugging t/e %ode 0o modiB, t/e value oB a variable in t/e Data tabA rig/tEclic5 t/e variable nameA and t/en select =odiB, Value Brom t/e s/ortcut menu) 0/e =odiB, Value 2indo2 is displa,ed) 0/e current value Bor t/e variable is displa,ed) 8ou can enter a ne2 value in t/e second teCt boCA and t/en clic5 O?)

c ra O l, - On

, em ad .c

ra c O

le In

l ae rn Uste

Oracle Database 11g: Develop PL/SQL Program Units & E !&

Debugging empLlist: Step Over t/e %ode


:# Step Over H:#I: (Cecutes t/e %ursor Hsame as :GIA but control is not transBerred to Open %ursor code

&

:#

%op,rig/t @ &''"A Oracle) .ll rig/ts reserved)

0/e Step Over Debugging 0ool 0/e Step Over commandA li5e Step IntoA enables ,ou to eCecute program statements one at a time) 9o2everA iB ,ou issue t/e Step Over command 2/en t/e eCecution point is located on a subprogram callA t/e debugger runs t/at subprogram 2it/out stopping Hinstead oB stepping into itIA and t/en positions t/e eCecution point on t/e statement t/at Bollo2s t/e subprogram call) IB t/e eCecution point is located on t/e last statement oB a subprogramA c/oosing Step Over causes t/e debugger to return Brom t/e subprogramA placing t/e eCecution point on t/e line oB code t/at Bollo2s t/e call to t/e subprogram ,ou are returning Brom) 8ou can step over a subprogram in an, oB t/e Bollo2ing 2a,s: Select Debug \ Step OverA press :#A or clic5 t/e Step Over icon in t/e Debugging M Log toolbar) In t/e eCample in t/e slideA stepping over 2ill eCecute t/e open cursor line 2it/out transBerring program control to t/e cursor deBinition as 2as t/e case 2it/ t/e Step Into option eCample)

c ra O l, - On

, em ad .c

ra c O

le In

l ae rn Uste

Oracle Database 11g: Develop PL/SQL Program Units & E !*

Debugging empLlist: Step Out oB t/e %ode HS/iBt N :GI


1 & * ! + $ #

%op,rig/t @ &''"A Oracle) .ll rig/ts reserved)

Debugging empLlist: Step Out oB t/e %ode HS/iBt N :GI

l e

0/e Step Out oB t/e code option leaves t/e current subprogram and goes to t/e neCt statement subprogram) In t/e eCample in t/e slideA starting 2it/ step *A iB ,ou press S/iBt N :GA program control leaves t/e procedure and goes to t/e neCt statement in t/e anon,mous bloc5) %ontinuing to press S/iBt N :G 2ill ta5e ,ou to t/e neCt anon,mous bloc5 t/at prints t/e contents oB t/e SQL buBBer)

c ra O l, - On

, em ad .c
G

ra c O

le In

l ae rn Uste

Oracle Database 11g: Develop PL/SQL Program Units & E !!

Debugging empLlist: 1un to %ursor H:!I

1un to %ursor :!: 1un to ,our cursor location 2it/out /aving to single step or set a brea5point)

%op,rig/t @ &''"A Oracle) .ll rig/ts reserved)

1unning to t/e %ursor Location >/en stepping t/roug/ ,our application code in t/e debuggerA ,ou ma, 2ant to run to a particular location 2it/out /aving to single step or set a brea5point) 0o run to a speciBic program location: In a subprogram editorA position ,our teCt cursor on t/e line oB code 2/ere ,ou 2ant t/e debugger to stop) 8ou can run to t/e cursor location using an, oB t/e Bollo2ing procedures: In t/e procedure editorA rig/tEclic5 and c/oose 1un to %ursorA c/oose t/e Debug \ 1un to %ursor option Brom t/e main menuA or press :!) .n, oB t/e Bollo2ing conditions ma, result: >/en ,ou run to t/e cursorA ,our program eCecutes 2it/out stoppingA until t/e eCecution reac/es t/e location mar5ed b, t/e teCt cursor in t/e source editor) IB ,our program never actuall, eCecutes t/e line oB code 2/ere t/e teCt cursor isA t/e 1un to %ursor command 2ill cause ,our program to run until it encounters a brea5point or until it Binis/es)

c ra O l, - On

, em ad .c

ra c O

le In

l ae rn Uste

Oracle Database 11g: Develop PL/SQL Program Units & E !+

Debugging empLlist: Step to (nd oB =et/od

Loops until i ^\ P=.O1O>S

%op,rig/t @ &''"A Oracle) .ll rig/ts reserved)

Debugging empLlist: Step to (nd oB =et/od

l c ra O l, - On e

Step to (nd oB =et/od goes to t/e last statement in t/e current subprogram or to t/e neCt brea5point iB t/ere are an, in t/e current subprogram)

, em ad .c

In t/e eCample in t/e slideA t/e Step to (nd oB =et/od debugging tool is used) 6ecause t/ere is a second brea5pointA selecting Step to (nd oB =et/od transBers control to t/at brea5point) Selecting Step to (nd oB =et/od again goes t/roug/ t/e iterations oB t/e 2/ile loop BirstA and t/en transBers t/e program control to t/e neCt eCecutable statement in t/e anon,mous bloc5)

ra c O

le In

l ae rn Uste

Oracle Database 11g: Develop PL/SQL Program Units & E !$

Debugging a Subprogram 1emotel,: Overvie2

1) (dit procedure

&) .dd brea5points

*) %ompile Bor Debug

$) Issue t/e debugger connection command and call procedure in anot/er session suc/ as SQLKPlus

+) (nter local mac/ine IP address and debugging port

!) Select 1emote Debug

G) >/en t/e brea5point is reac/edA control passes to SQL Developer

#) Debug and monitor data using debugging tools

%op,rig/t @ &''"A Oracle) .ll rig/ts reserved)

1emote Debugging 8ou can use remote debugging to connect to an, PL/SQL code in a database and debug itA regardless oB 2/ere t/e database is located as long as ,ou /ave access to t/e database and /ave created a connection to it) 1emote debugging is 2/en somet/ing elseA ot/er t/an ,ou as a developerA 5ic5s oBB a procedure t/at ,ou can t/en debug) 1emote debugging and local debugging /ave man, steps in common) 0o debug remotel,A perBorm t/e Bollo2ing steps: 1) (dit t/e subprogram t/at ,ou 2ould li5e to debug) &) .dd t/e brea5points in t/e subprogram) *) %lic5 t/e %ompile Bor Debug icon in t/e toolbar) !) 1ig/tEclic5 t/e connection Bor t/e remote databaseA and select 1emote Debug) +) In t/e Debugger E .ttac/ to ;PD. dialog boCA enter t/e local mac/ine IP address and port numberA suc/ as !'''A and t/en clic5 O?) $) Issue t/e debugger connection command using a diBBerent session suc/ as SQLKPlusA and t/en call t/e procedure in t/at session) G) >/en a brea5point is reac/edA control is passed bac5 to t/e original SQL Developer session and t/e debugger toolbar is displa,ed) #) Debug t/e subprogram and monitor t/e data using t/e debugging tools discussed earlier)

c ra O l, - On

, em ad .c

ra c O

le

l ae rn Uste

Oracle Database 11g: Develop PL/SQL Program Units & E !G

In

Practice &E& Overvie2: Introduction to t/e SQL Developer Debugger


0/is practice covers t/e Bollo2ing topics: %reating a procedure and a Bunction Inserting brea5points in t/e procedure %ompiling t/e procedure and Bunction Bor debug mode Debugging t/e procedure and stepping into t/e code Displa,ing and modiB,ing t/e subprogramsF variables

%op,rig/t @ &''"A Oracle) .ll rig/ts reserved)

Practice &E&: Overvie2 8ou must use SQL Developer Bor t/is practice) 0/is practice introduces ,ou to t/e basic Bunctionalit, oB t/e SQL Developer debugger)

c ra O l, - On

, em ad .c

ra c O

le In

l ae rn Uste

Oracle Database 11g: Develop PL/SQL Program Units & E !#

Summar,
In t/is lessonA ,ou s/ould /ave learned /o2 to: DiBBerentiate bet2een a procedure and a Bunction Describe t/e uses oB Bunctions %reate stored Bunctions Invo5e a Bunction 1emove a Bunction Understand t/e basic Bunctionalit, oB t/e SQL Developer debugger

%op,rig/t @ &''"A Oracle) .ll rig/ts reserved)

Summar, . Bunction is a named PL/SQL bloc5 t/at must return a value) enerall,A ,ou create a Bunction to compute and return a valueA and ,ou create a procedure to perBorm an action) . Bunction can be created or dropped) . Bunction is invo5ed as a part oB an eCpression)

c ra O l, - On

, em ad .c

ra c O

le In

l ae rn Uste

Oracle Database 11g: Develop PL/SQL Program Units & E !"

l c ra O l, - On ra c O le In l ae rn Uste e

, em ad .c

%reating Pac5ages

%op,rig/t @ &''"A Oracle) .ll rig/ts reserved)

l c ra O l, - On ra c O le In l ae rn Uste e

, em ad .c

Ob3ectives
.Bter completing t/is lessonA ,ou s/ould be able to do t/e Bollo2ing: Describe pac5ages and list t/eir components %reate a pac5age to group toget/er related variablesA cursorsA constantsA eCceptionsA proceduresA and Bunctions Designate a pac5age construct as eit/er public or private Invo5e a pac5age construct Describe t/e use oB a bodiless pac5age

%op,rig/t @ &''"A Oracle) .ll rig/ts reserved)

Lesson .im In t/is lessonA ,ou learn 2/at a pac5age is and 2/at its components are) 8ou also learn /o2 to create and use pac5ages)

c ra O l, - On

, em ad .c

ra c O

le In

l ae rn Uste

Oracle Database 11g: Develop PL/SQL Program Units * E &

Lesson .genda
IdentiB,ing t/e beneBits and t/e components oB pac5ages >or5ing 2it/ pac5ages:
M M M M %reating t/e pac5age speciBication and bod, Invo5ing t/e pac5age subprograms 1emoving a pac5age Displa,ing t/e pac5age inBormation

%op,rig/t @ &''"A Oracle) .ll rig/ts reserved)

l c ra O l, - On ra c O le In l ae rn Uste e

, em ad .c

Oracle Database 11g: Develop PL/SQL Program Units * E *

>/at .re PL/SQL Pac5agesJ


. pac5age is a sc/ema ob3ect t/at groups logicall, related PL/SQL t,pesA variablesA and subprograms) Pac5ages usuall, /ave t2o parts:
M . speciBication HspecI M . bod,

0/e speciBication is t/e interBace to t/e pac5age) It declares t/e t,pesA variablesA constantsA eCceptionsA cursorsA and subprograms t/at can be reBerenced Brom outside t/e pac5age) 0/e bod, deBines t/e Pueries Bor t/e cursors and t/e code Bor t/e subprograms) (nable t/e Oracle server to read multiple ob3ects into memor, at once)

%op,rig/t @ &''"A Oracle) .ll rig/ts reserved)

PL/SQL Pac5ages: Overvie2 PL/SQL pac5ages enable ,ou to bundle related PL/SQL t,pesA variablesA data structuresA eCceptionsA and subprograms into one container) :or eCampleA a 9uman 1esources pac5age can contain /iring and Biring proceduresA commission and bonus BunctionsA and taC eCemption variables) . pac5age usuall, consists oB t2o parts stored separatel, in t/e database: . speciBication . bod, HoptionalI 0/e pac5age itselB cannot be calledA parameteri4edA or nested) .Bter 2riting and compilingA t/e contents can be s/ared 2it/ man, applications) >/en a PL/SQLEpac5aged construct is reBerenced Bor t/e Birst timeA t/e 2/ole pac5age is loaded into memor,) SubsePuent access to constructs in t/e same pac5age does not rePuire dis5 input/output HI/OI)

c ra O l, - On

, em ad .c

ra c O

le In

l ae rn Uste

Oracle Database 11g: Develop PL/SQL Program Units * E !

.dvantages oB Using Pac5ages



M Onl, t/e declarations in t/e pac5age speciBication are visible and accessible to applications M Private constructs in t/e pac5age bod, are /idden and inaccessible M .ll coding is /idden in t/e pac5age bod,

=odularit,: (ncapsulating related constructs (asier maintenance: ?eeping logicall, related Bunctionalit, toget/er (asier application design: %oding and compiling t/e speciBication and bod, separatel, 9iding inBormation:

%op,rig/t @ &''"A Oracle) .ll rig/ts reserved)

.dvantages oB Using Pac5ages Pac5ages provide an alternative to creating procedures and Bunctions as standEalone sc/ema ob3ectsA and t/e, oBBer several beneBits)

ra c O

=odularit, and easier maintenance: 8ou encapsulate logicall, related programming structures in a named module) (ac/ pac5age is eas, to understandA and t/e interBace bet2een pac5ages is simpleA clearA and 2ell deBined) (asier application design: .ll ,ou need initiall, is t/e interBace inBormation in t/e pac5age speciBication) 8ou can code and compile a speciBication 2it/out its bod,) 0/ereaBterA stored subprograms t/at reBerence t/e pac5age can compile as 2ell) 8ou need not deBine t/e pac5age bod, Bull, until ,ou are read, to complete t/e application) 9iding inBormation: 8ou decide 2/ic/ constructs are public Hvisible and accessibleI and 2/ic/ are private H/idden and inaccessibleI) Declarations in t/e pac5age speciBication are visible and accessible to applications) 0/e pac5age bod, /ides t/e deBinition oB t/e private constructsA so t/at onl, t/e pac5age is aBBected Hnot ,our application or an, calling programsI iB t/e deBinition c/anges) 0/is enables ,ou to c/ange t/e implementation 2it/out /aving to recompile t/e calling programs) .lsoA b, /iding implementation details Brom usersA ,ou protect t/e integrit, oB t/e pac5age)

c ra O l, - On

, em ad .c

le

l ae rn Uste

Oracle Database 11g: Develop PL/SQL Program Units * E +

In

.dvantages oB Using Pac5ages


.dded Bunctionalit,: Persistenc, oB public variables and cursors 6etter perBormance:
M 0/e entire pac5age is loaded into memor, 2/en t/e pac5age is Birst reBerenced) M 0/ere is onl, one cop, in memor, Bor all users) M 0/e dependenc, /ierarc/, is simpliBied)

Overloading: =ultiple subprograms oB t/e same name

%op,rig/t @ &''"A Oracle) .ll rig/ts reserved)

.dvantages oB Using Pac5ages HcontinuedI .dded Bunctionalit,: Pac5aged public variables and cursors persist Bor t/e duration oB a session) 0/usA t/e, can be s/ared b, all subprograms t/at eCecute in t/e environment) 0/e, also enable ,ou to maintain data across transactions 2it/out /aving to store it in t/e database) Private constructs also persist Bor t/e duration oB t/e session but can be accessed onl, 2it/in t/e pac5age) 6etter perBormance: >/en ,ou call a pac5aged subprogram t/e Birst timeA t/e entire pac5age is loaded into memor,) Later calls to related subprograms in t/e pac5ageA t/ereBoreA rePuire no Burt/er dis5 I/O) Pac5aged subprograms also stop cascading dependencies and t/us avoid unnecessar, compilation)

ra c O

Overloading: >it/ pac5agesA ,ou can overload procedures and BunctionsA 2/ic/ means ,ou can create multiple subprograms 2it/ t/e same name in t/e same pac5ageA eac/ ta5ing parameters oB diBBerent number or data t,pe) <ote: Dependencies are covered in detail in t/e lesson titled X=anaging Dependencies)Y

c ra O l, - On

, em ad .c

le

l ae rn Uste

Oracle Database 11g: Develop PL/SQL Program Units * E $

In

%omponents oB a PL/SQL Pac5age

Pac5age speciBication

variable Public Procedure . declarationR

variable Procedure 6 deBinition _ Procedure . deBinition variable Pac5age bod, 6( I< _ (<DR Private

%op,rig/t @ &''"A Oracle) .ll rig/ts reserved)

%omponents oB a PL/SQL Pac5age 8ou create a pac5age in t2o parts: 0/e pac5age speciBication is t/e interBace to ,our applications) It declares t/e public t,pesA variablesA constantsA eCceptionsA cursorsA and subprograms available Bor use) 0/e pac5age speciBication ma, also include P1. =.sA 2/ic/ are directives to t/e compiler) 0/e pac5age bod, deBines its o2n subprograms and must Bull, implement subprograms declared in t/e speciBication part) 0/e pac5age bod, ma, also deBine PL/SQL constructsA suc/ as t,pesA variablesA constantsA eCceptionsA and cursors) Public components are declared in t/e pac5age speciBication) 0/e speciBication deBines a public application programming interBace H.PII Bor users oB pac5age Beatures and Bunctionalit,Ut/at isA public components can be reBerenced Brom an, Oracle server environment t/at is eCternal to t/e pac5age) Private components are placed in t/e pac5age bod, and can be reBerenced onl, b, ot/er constructs 2it/in t/e same pac5age bod,) Private components can reBerence t/e public components oB a pac5age) <ote: IB a pac5age speciBication does not contain subprogram declarationsA t/en t/ere is no rePuirement Bor a pac5age bod,)

c ra O l, - On

, em ad .c

ra c O

le

l ae rn Uste

Oracle Database 11g: Develop PL/SQL Program Units * E G

In

Internal and (Cternal Visibilit, oB a Pac5ageFs %omponents


Pac5age speciBication

publicLvar Procedure .R (Cternal code privateLvar Procedure 6 IS 6( I< _ (<DR Procedure . IS localLvar

Pac5age bod,

6( I< _ (<DR

%op,rig/t @ &''"A Oracle) .ll rig/ts reserved)

Internal and (Cternal Visibilit, oB a Pac5ageFs %omponents 0/e visibilit, oB a component describes 2/et/er t/at component can be seenA t/at isA reBerenced and used b, ot/er components or ob3ects) 0/e visibilit, oB components depends on 2/et/er t/e, are locall, or globall, declared) Local components are visible 2it/in t/e structure in 2/ic/ t/e, are declaredA suc/ as: Variables deBined in a subprogram can be reBerenced 2it/in t/at subprogramA and are not visible to eCternal componentsUBor eCampleA localLvar can be used in procedure .) Private pac5age variablesA 2/ic/ are declared in a pac5age bod,A can be reBerenced b, ot/er components in t/e same pac5age bod,) 0/e, are not visible to an, subprograms or ob3ects t/at are outside t/e pac5age) :or eCampleA privateLvar can be used b, procedures . and 6 2it/in t/e pac5age bod,A but not outside t/e pac5age) loball, declared components are visible internall, and eCternall, to t/e pac5ageA suc/ as: . public variableA 2/ic/ is declared in a pac5age speciBicationA can be reBerenced and c/anged outside t/e pac5age HBor eCampleA publicLvar can be reBerenced eCternall,I) . pac5age subprogram in t/e speciBication can be called Brom eCternal code sources HBor eCampleA procedure . can be called Brom an environment eCternal to t/e pac5ageI) <ote: Private subprogramsA suc/ as procedure 6A can be invo5ed onl, 2it/ public subprogramsA suc/ as procedure .A or ot/er private pac5age constructs) . public variable declared in t/e pac5age speciBication is a global variable)

c ra O l, - On

, em ad .c

ra c O

le

l ae rn Uste

Oracle Database 11g: Develop PL/SQL Program Units * E #

In

Developing PL/SQL Pac5ages: Overvie2

Vie2 errors/2arnings in SQL Developer

8(S
Use S9O> (11O1S command in SQLKPlus %reate/edit pac5age spec and bod, %ompiler 2arnings/errorsJ Vie2 compiler 2arnings/errors

<O
Use US(1/.LL/D6.L (11O1S vie2s

Invo5e pac5age subprograms

%op,rig/t @ &''"A Oracle) .ll rig/ts reserved)

Developing PL/SQL Pac5ages 0/e grap/ic in t/e slide illustrates t/e basic steps involved in developing and using a pac5age: 1) %reate t/e procedure using SQL DeveloperFs Ob3ect <avigator tree or t/e SQL >or5s/eet area) &) %ompile t/e pac5age) 0/e pac5age is created in t/e database) 0/e %1(.0( P.%?. ( statement creates and stores source code and t/e compiled mEcode in t/e database) 0o compile t/e pac5ageA rig/tEclic5 t/e pac5ageFs name in t/e Ob3ect <avigator treeA and t/en clic5 %ompile) *) IB t/ere are no compilation 2arnings or errorsA ,ou eCecute an, public construct 2it/in t/e pac5age speciBication Brom an Oracle Server environment) !) IB t/ere are compilation 2arning or errorsA ,ou can vie2 Hand t/en correctI t/e 2arnings or errors using one oB t/e Bollo2ing met/ods: E Using t/e SQL Developer interBace Ht/e %ompiler M Log tabI E Using t/e S9O> (11O1S SQLKPlus command E Using t/e US(1/.LL/D6.L(11O1S vie2s

c ra O l, - On

, em ad .c

ra c O

le

l ae rn Uste

Oracle Database 11g: Develop PL/SQL Program Units * E "

In

Lesson .genda
IdentiB,ing t/e beneBits and t/e components oB pac5ages >or5ing 2it/ pac5ages: M %reating t/e pac5age speciBication and bod, M Invo5ing t/e pac5age subprograms M 1emoving a pac5age M Displa,ing t/e pac5age inBormation

%op,rig/t @ &''"A Oracle) .ll rig/ts reserved)

l c ra O l, - On ra c O le In l ae rn Uste e

, em ad .c

Oracle Database 11g: Develop PL/SQL Program Units * E 1'

%reating t/e Pac5age SpeciBication: Using t/e %1(.0( P.%?. ( Statement

%1(.0( VO1 1(PL.%(W P.%?. ( pac5ageLname IST.S public t,pe and variable declarations subprogram speciBications (<D Vpac5ageLnameWR

0/e O1 1(PL.%( option drops and reEcreates t/e pac5age speciBication) Variables declared in t/e pac5age speciBication are initiali4ed to <ULL b, deBault) .ll t/e constructs declared in a pac5age speciBication are visible to users 2/o are granted privileges on t/e pac5age)

%op,rig/t @ &''"A Oracle) .ll rig/ts reserved)

%reating t/e Pac5age SpeciBication 0o create pac5agesA ,ou declare all public constructs 2it/in t/e pac5age speciBication) SpeciB, t/e O1 1(PL.%( option iB over2riting an eCisting pac5age speciBication) Initiali4e a variable 2it/ a constant value or Bormula 2it/in t/e declarationA iB rePuiredR ot/er2iseA t/e variable is initiali4ed implicitl, to <ULL)

ra c O

0/e Bollo2ing are deBinitions oB items in t/e pac5age s,ntaC: pac5ageLname speciBies a name Bor t/e pac5age t/at must be uniPue among ob3ects 2it/in t/e o2ning sc/ema) Including t/e pac5age name aBter t/e (<D 5e,2ord is optional) public t,pe and variable declarations declares public variablesA constantsA cursorsA eCceptionsA userEdeBined t,pesA and subt,pes) subprogram speciBication speciBies t/e public procedure or Bunction declarations) 0/e pac5age speciBication s/ould contain procedure and Bunction /eadings terminated b, a semicolonA 2it/out t/e IS Hor .SI 5e,2ord and its PL/SQL bloc5) 0/e implementation oB a procedure or Bunction t/at is declared in a pac5age speciBication is done in t/e pac5age bod,) 0/e Oracle database stores t/e speciBication and bod, oB a pac5age separatel,) 0/is enables ,ou to c/ange t/e implementation oB a program construct in t/e pac5age bod, 2it/out invalidating ot/er sc/ema ob3ects t/at call or reBerence t/e program construct)

c ra O l, - On

, em ad .c

le

l ae rn Uste

Oracle Database 11g: Develop PL/SQL Program Units * E 11

In

%reating t/e Pac5age SpeciBication: Using SQL Developer


*

&

G ! (nter pac5ageFs declarations $

%op,rig/t @ &''"A Oracle) .ll rig/ts reserved)

%reating t/e Pac5age SpeciBication: Using SQL Developer 8ou can use SQL Developer to create t/e pac5age speciBication as Bollo2s: 1) 1ig/tEclic5 t/e Pac5ages node in t/e %onnections navigation tree) &) Select <e2 Pac5age Brom t/e s/ortcut menu) *) In t/e %reate PL/SQL Pac5age 2indo2A select t/e sc/ema nameA enter t/e name Bor t/e ne2 pac5ageA and t/en clic5 O?) . tab Bor t/e ne2 pac5age is displa,ed along 2it/ t/e s/ell Bor t/e ne2 pac5age) !) (nter t/e code Bor t/e ne2 pac5age) +) %ompile or save Husing t/e Save icon on t/e main toolbarI t/e ne2 pac5age) $) 0/e =essages M Log tab displa,s 2/et/er or not t/e compilation 2as successBul) G) 0/e ne2l, created pac5age is displa,ed under t/e Pac5ages node in t/e %onnections navigation tree)

c ra O l, - On

, em ad .c

ra c O

le In

l ae rn Uste

Oracle Database 11g: Develop PL/SQL Program Units * E 1&

%reating t/e Pac5age 6od,: Using SQL Developer

&

*
(nter pac5ageFs bod, code

%op,rig/t @ &''"A Oracle) .ll rig/ts reserved)

%reating t/e Pac5age 6od,: Using SQL Developer 8ou can use SQL Developer to create t/e pac5age bod, as Bollo2s: 1) 1ig/tEclic5 t/e pac5age name Bor 2/ic/ ,ou are creating a bod, in t/e Pac5ages node in t/e %onnections navigation tree) &) Select %reate 6od, Brom t/e s/ortcut menu) . tab Bor t/e ne2 pac5age bod, is displa,ed along 2it/ t/e s/ell Bor t/e ne2 pac5age bod,) *) (nter t/e code Bor t/e ne2 pac5age bod,) !) %ompile or save t/e pac5age bod,) +) 0/e =essages M Log tab displa,s 2/et/er or not t/e compilation 2as successBul) $) 0/e ne2l, created pac5age bod, is displa,ed under t/e Pac5ages node in t/e %onnections navigation tree)

c ra O l, - On

, em ad .c

ra c O

le In

l ae rn Uste

Oracle Database 11g: Develop PL/SQL Program Units * E 1*

(Cample oB a Pac5age SpeciBication: commLp5g

EE 0/e pac5age spec 2it/ a public variable and a EE public procedure t/at are accessible Brom EE outside t/e pac5age) %1(.0( O1 1(PL.%( P.%?. ( commLp5g IS vLstdLcomm <U=6(1 :Z ')1'R EEinitiali4ed to ')1' P1O%(DU1( resetLcommHpLne2Lcomm <U=6(1IR (<D commLp5gR /

VLS0DL%O== is a public global variable initiali4ed to ')1') 1(S(0L%O== is a public procedure used to reset t/e standard commission based on some business rules) It is implemented in t/e pac5age bod,)

%op,rig/t @ &''"A Oracle) .ll rig/ts reserved)

(Cample oB Pac5age SpeciBication: commLp5g 0/e eCample in t/e slide creates a pac5age called commLp5g used to manage business processing rules Bor commission calculations) 0/e vLstdLcomm public HglobalI variable is declared to /old a maCimum allo2able percentage commission Bor t/e user sessionA and it is initiali4ed to ')1' Ht/at isA 1'QI) 0/e resetLcomm public procedure is declared to accept a ne2 commission percentage t/at updates t/e standard commission percentage iB t/e commission validation rules are accepted) 0/e validation rules Bor resetting t/e commission are not made public and do not appear in t/e pac5age speciBication) 0/e validation rules are managed b, using a private Bunction in t/e pac5age bod,)

c ra O l, - On

, em ad .c

ra c O

le In

l ae rn Uste

Oracle Database 11g: Develop PL/SQL Program Units * E 1!

%reating t/e Pac5age 6od,

%1(.0( VO1 1(PL.%(W P.%?. ( 6OD8 pac5ageLname IST.S private t,pe and variable declarations subprogram bodies V6( I< initiali4ation statementsW (<D Vpac5ageLnameWR

0/e O1 1(PL.%( option drops and reEcreates t/e pac5age bod,) IdentiBiers deBined in t/e pac5age bod, are private and not visible outside t/e pac5age bod,) .ll private constructs must be declared beBore t/e, are reBerenced) Public constructs are visible to t/e pac5age bod,)

%op,rig/t @ &''"A Oracle) .ll rig/ts reserved)

%reating t/e Pac5age 6od, %reate a pac5age bod, to deBine and implement all public subprograms and supporting private constructs) >/en creating a pac5age bod,A perBorm t/e Bollo2ing steps: SpeciB, t/e O1 1(PL.%( option to over2rite an eCisting pac5age bod,) DeBine t/e subprograms in an appropriate order) 0/e basic principle is t/at ,ou must declare a variable or subprogram beBore it can be reBerenced b, ot/er components in t/e same pac5age bod,) It is common to see all private variables and subprograms deBined Birst and t/e public subprograms deBined last in t/e pac5age bod,) %omplete t/e implementation Bor all procedures or Bunctions declared in t/e pac5age speciBication 2it/in t/e pac5age bod,) 0/e Bollo2ing are deBinitions oB items in t/e pac5age bod, s,ntaC: pac5ageLname speciBies a name Bor t/e pac5age t/at must be t/e same as its pac5age speciBication) Using t/e pac5age name aBter t/e (<D 5e,2ord is optional) private t,pe and variable declarations declares private variablesA constantsA cursorsA eCceptionsA userEdeBined t,pesA and subt,pes) subprogram speciBication speciBies t/e Bull implementation oB an, private and/or public procedures or Bunctions) V6( I< initiali4ation statementsW is an optional bloc5 oB initiali4ation code t/at eCecutes 2/en t/e pac5age is Birst reBerenced)

c ra O l, - On

, em ad .c

ra c O

le

l ae rn Uste

Oracle Database 11g: Develop PL/SQL Program Units * E 1+

In

(Cample oB a Pac5age 6od,: commLp5g


%1(.0( O1 1(PL.%( P.%?. ( 6OD8 commLp5g IS :U<%0IO< validateHpLcomm <U=6(1I 1(0U1< 6OOL(.< IS vLmaCLcommemplo,ees)commissionLpctQt,peR 6( I< S(L(%0 =.OHcommissionLpctI I<0O vLmaCLcomm :1O=emplo,eesR 1(0U1< HpLcomm 6(0>((< ')' .<D vLmaCLcommIR (<D validateR

P1O%(DU1( resetLcomm HpLne2Lcomm <U=6(1I IS 6( I< I: validateHpLne2LcommI 09(< vLstdLcomm :Z pLne2LcommR EE reset public var (LS( 1.IS(L.PPLI%.0IO<L(11O1H E&'&1'A S6ad %ommissionSIR (<D I:R (<D resetLcommR (<D commLp5gR

%op,rig/t @ &''"A Oracle) .ll rig/ts reserved)

(Cample oB a Pac5age 6od,: commLp5g 0/e slide s/o2s t/e complete pac5age bod, Bor commLp5gA 2it/ a private Bunction called validate to c/ec5 Bor a valid commission) 0/e validation rePuires t/at t/e commission be positive and less t/an t/e /ig/est commission among eCisting emplo,ees) 0/e resetLcomm procedure invo5es t/e private validation Bunction beBore c/anging t/e standard commission in vLstdLcomm) In t/e eCampleA note t/e Bollo2ing: 0/e vLstdLcomm variable reBerenced in t/e resetLcomm procedure is a public variable) Variables declared in t/e pac5age speciBicationA suc/ as vLstdLcommA can be directl, reBerenced 2it/out PualiBication) 0/e resetLcomm procedure implements t/e public deBinition in t/e speciBication) In t/e commLp5g bod,A t/e validate Bunction is private and is directl, reBerenced Brom t/e resetLcomm procedure 2it/out PualiBication) <ote: 0/e validate Bunction appears beBore t/e resetLcomm procedure because t/e resetLcomm procedure reBerences t/e validate Bunction) It is possible to create Bor2ard declarations Bor subprograms in t/e pac5age bod, iB t/eir order oB appearance needs to be c/anged) IB a pac5age speciBication declares onl, t,pesA constantsA variablesA and eCceptions 2it/out an, subprogram speciBicationsA t/en t/e pac5age bod, is unnecessar,) 9o2everA t/e bod, can be used to initiali4e items declared in t/e pac5age speciBication)

c ra O l, - On

, em ad .c

ra c O

le

l ae rn Uste

Oracle Database 11g: Develop PL/SQL Program Units * E 1$

In

Invo5ing t/e Pac5age Subprograms: (Camples


EE Invo5e a Bunction 2it/in t/e same pac5ages: %1(.0( O1 1(PL.%( P.%?. ( 6OD8 commLp5g IS ))) P1O%(DU1( resetLcommHpLne2Lcomm <U=6(1I IS 6( I< I: validateHpLne2LcommI 09(< vLstdLcomm :Z pLne2LcommR (LS( ))) (<D I:R (<D resetLcommR (<D commLp5gR

EE Invo5e a pac5age procedure Brom SQLKPlus: (O(%U0( commLp5g)resetLcommH')1+I

EE Invo5e a pac5age procedure in a diBBerent sc/ema: (O(%U0( scott)commLp5g)resetLcommH')1+I

%op,rig/t @ &''"A Oracle) .ll rig/ts reserved)

Invo5ing Pac5age Subprograms .Bter t/e pac5age is stored in t/e databaseA ,ou can invo5e public or private subprograms 2it/in t/e same pac5ageA or public subprograms iB eCternal to t/e pac5age) :ull, PualiB, t/e subprogram 2it/ its pac5age name 2/en invo5ed eCternall, Brom t/e pac5age) Use t/e pac5ageLname)subprogram s,ntaC)

ra c O

:ull, PualiB,ing a subprogram 2/en invo5ed 2it/in t/e same pac5age is optional) (Cample 1: Invo5es t/e validate Bunction Brom t/e resetLcomm procedure 2it/in t/e same pac5age) 0/e pac5age name preBiC is not rePuiredR it is optional) (Cample &: %alls t/e resetLcomm procedure Brom SQLKPlus Han environment eCternal to t/e pac5ageI to reset t/e prevailing commission to ')1+ Bor t/e user session) (Cample *: %alls t/e resetLcomm procedure t/at is o2ned b, a sc/ema user called S%O00) Using SQLKPlusA t/e PualiBied pac5age procedure is preBiCed 2it/ t/e sc/ema name) 0/is can be simpliBied b, using a s,non,m t/at reBerences t/e sc/ema)pac5ageLname) .ssume t/at a database lin5 named <8 /as been created Bor a remote database in 2/ic/ t/e resetLcomm pac5age procedure is created) 0o invo5e t/e remote procedureA use:

c ra O l, - On

, em ad .c

le

(O(%U0( commLp5g)resetLcomm]<8H')1+I

l ae rn Uste

Oracle Database 11g: Develop PL/SQL Program Units * E 1G

In

Invo5ing t/e Pac5age Subprograms: Using SQL Developer

&

* !

%op,rig/t @ &''"A Oracle) .ll rig/ts reserved)

Invo5ing t/e Pac5age Subprograms: Using SQL Developer 8ou can use SQL Developer to invo5e a pac5ageSs subprogram as Bollo2s: 1) 1ig/tEclic5 t/e pac5ageSs name in t/e Pac5ages node in t/e <avigation tree) &) Select 1un Brom t/e Bloating menu) 0/e 1un PL/SQL 2indo2 is displa,ed) 8ou can use t/e 1un PL/SQL 2indo2 to speciB, parameter values Bor running a PL/SQL Bunction or procedure) HIB ,ou speciB, a pac5ageA select a Bunction or procedure in t/e pac5age)I SpeciB, t/e Bollo2ing: a) 0arget: Select t/e name oB t/e Bunction or procedure to run) b) Parameters: 0/is section lists eac/ parameter Bor t/e speciBied target) 0/e mode oB eac/ parameter can be I< Ht/e value is passed inIA OU0 Ht/e value is returnedIA or I</OU0 Ht/e value is passed inA and t/e result oB t/e Bunction or procedureSs action is stored in t/e parameterI) *) In t/e PL/SQL 6loc5 sectionA c/ange t/e Bormal I< and I</OU0 parameter speciBications in t/is bloc5 to actual values t/at ,ou 2ant to use Bor running t/e Bunction or procedure) :or eCampleA to speciB, ')1+ as t/e value Bor an input parameter named PL<(>L%O==A c/ange PL<(>L%O== Z\ PL<(>L%O== to PL<(>L%O== Z\ ')1+) !) %lic5 O?) SQL Developer runs t/e Bunction or procedure)

c ra O l, - On

, em ad .c

ra c O

le

l ae rn Uste

Oracle Database 11g: Develop PL/SQL Program Units * E 1#

In

%reating and Using 6odiless Pac5ages


%1(.0( O1 1(PL.%( P.%?. ( globalLconsts IS cLmileL&L5ilo%O<S0.<0 <U=6(1 :Z 1)$'"*R cL5iloL&Lmile%O<S0.<0 <U=6(1 :Z ')$&1!R cL,ardL&Lmeter%O<S0.<0 <U=6(1 :Z ')"1!!R cLmeterL&L,ard%O<S0.<0 <U=6(1 :Z 1)'"*$R (<D globalLconstsR

S(0 S(1V(1OU0PU0 O< 6( I< D6=SLOU0PU0)PU0LLI<(HS&' miles Z S TT &' K globalLconsts)cLmileL&L5ilo TT S 5mSIR (<DR S(0 S(1V(1OU0PU0 O< %1(.0( :U<%0IO< mtr&,rdHpLm <U=6(1I 1(0U1< <U=6(1 IS 6( I< 1(0U1< HpLm K globalLconsts)cLmeterL&L,ardIR (<D mtr&,rdR / (O(%U0( D6=SLOU0PU0)PU0LLI<(Hmtr&,rdH1II

%op,rig/t @ &''"A Oracle) .ll rig/ts reserved)

%reating and Using 6odiless Pac5ages 0/e variables and constants declared 2it/in standEalone subprograms eCist onl, Bor t/e duration t/at t/e subprogram eCecutes) 0o provide data t/at eCists Bor t/e duration oB t/e user sessionA create a pac5age speciBication containing public HglobalI variables and constant declarations) In t/is caseA create a pac5age speciBication 2it/out a pac5age bod,A 5no2n as a bodiless pac5age) .s discussed earlier in t/is lessonA iB a speciBication declares onl, t,pesA constantsA variablesA and eCceptionsA t/en t/e pac5age bod, is unnecessar,) (Camples 0/e Birst code boC in t/e slide creates a bodiless pac5age speciBication 2it/ several constants to be used Bor conversion rates) . pac5age bod, is not rePuired to support t/is pac5age speciBication) It is assumed t/at t/e S(0 S(1V(1OU0PU0 O< statement 2as issued beBore eCecuting t/e code eCamples in t/e slide) 0/e second code boC reBerences t/e cLmileL&L5ilo constant in t/e globalLconsts pac5age b, preBiCing t/e pac5age name to t/e identiBier oB t/e constant) 0/e t/ird eCample creates a standEalone Bunction cLmtr&,rd to convert meters to ,ardsA and uses t/e constant conversion rate cLmeterL&L,ard declared in t/e globalLconsts pac5age) 0/e Bunction is invo5ed in a D6=SLOU0PU0)PU0LLI<( parameter)

c ra O l, - On

, em ad .c

ra c O

le

1ule to be Bollo2ed: >/en reBerencing a variableA cursorA constantA or eCception Brom outside t/e pac5ageA ,ou must PualiB, it 2it/ t/e name oB t/e pac5age)
Oracle Database 11g: Develop PL/SQL Program Units * E 1"

l ae rn Uste

In

1emoving Pac5ages: Using SQL Developer or t/e SQL D1OP Statement


Drop pac5age speciBication and bod, Drop pac5age bod, onl,

EE 1emove t/e pac5age speciBication and bod, D1OP P.%?. ( pac5ageLnameR

EE 1emove t/e pac5age bod, onl, D1OP P.%?. ( 6OD8 pac5ageLnameR

%op,rig/t @ &''"A Oracle) .ll rig/ts reserved)

1emoving Pac5ages >/en a pac5age is no longer rePuiredA ,ou can use a SQL statement in SQL Developer to remove it) . pac5age /as t2o partsR t/ereBoreA ,ou can remove t/e 2/ole pac5ageA or ,ou can remove onl, t/e pac5age bod, and retain t/e pac5age speciBication)

c ra O l, - On

, em ad .c

ra c O

le In

l ae rn Uste

Oracle Database 11g: Develop PL/SQL Program Units * E &'

Vie2ing Pac5ages Using t/e Data Dictionar,


EE Vie2 t/e pac5age speciBication) S(L(%0 teCt :1O=userLsource >9(1( name Z S%O==LP? S .<D t,pe Z SP.%?. (S O1D(1 68 LI<(R

EE Vie2 t/e pac5age bod,) S(L(%0 teCt :1O=userLsource >9(1( name Z S%O==LP? S .<D t,pe Z SP.%?. ( 6OD8S O1D(1 68 LI<(R

%op,rig/t @ &''"A Oracle) .ll rig/ts reserved)

Vie2ing Pac5ages in t/e Data Dictionar, 0/e source code Bor PL/SQL pac5ages is also stored in t/e US(1LSOU1%( and .LLLSOU1%( data dictionar, vie2s) 0/e US(1LSOU1%( table is used to displa, PL/SQL code t/at ,ou o2n) 0/e .LLLSOU1%( table is used to displa, PL/SQL code to 2/ic/ ,ou /ave been granted t/e (O(%U0( rig/t b, t/e o2ner oB t/at subprogram code and provides an O><(1 column in addition to t/e preceding columns) >/en Puer,ing t/e pac5ageA use a condition in 2/ic/ t/e 08P( column is: (Pual to SP.%?. (S to displa, t/e source code Bor t/e pac5age speciBication (Pual to SP.%?. ( 6OD8S to displa, t/e source code Bor t/e pac5age bod,

ra c O

8ou can also vie2 t/e pac5age speciBication and bod, in SQL Developer using t/e pac5age name in t/e Pac5ages node) <ote: 8ou cannot displa, t/e source code Bor Oracle PL/SQL builtEin pac5agesA or PL/SQL 2/ose source code /as been 2rapped b, using a >1.P utilit, or obBuscation) ObBuscating and 2rapping PL/SQL source code is covered in a later lesson) %lic5ing t/e (Cecute Statement H:"I icon Hinstead oB t/e 1un Script iconI in t/e SQL >or5s/eet toolbarA sometimes displa,s a better Bormatted output in t/e 1esults tab as s/o2n in t/e slide eCamples)

c ra O l, - On

, em ad .c

le

l ae rn Uste

Oracle Database 11g: Develop PL/SQL Program Units * E &1

In

Vie2ing Pac5ages Using SQL Developer


0o vie2 t/e pac5age specA clic5 t/e pac5age name

1 &

0o vie2 t/e pac5age bod,A clic5 t/e pac5age bod,

1 &

%op,rig/t @ &''"A Oracle) .ll rig/ts reserved)

Vie2ing Pac5ages Using SQL Developer 0o vie2 a pac5ageSs spec in SQL DeveloperA use t/e Bollo2ing steps: 1) %lic5 t/e Pac5ages node in t/e %onnections tab) &) %lic5 t/e pac5ageSs name) *) 0/e pac5ageSs spec code is displa,ed in t/e %ode tab as s/o2n in t/e slide) 0o vie2 a pac5ageSs bod, in SQL DeveloperA use t/e Bollo2ing steps: 1) %lic5 t/e Pac5ages node in t/e %onnections tab) &) %lic5 t/e pac5ageFs bod,) *) 0/e pac5ageFs bod, code is displa,ed in t/e %ode tab as s/o2n in t/e slide)

c ra O l, - On

, em ad .c

ra c O

le In

l ae rn Uste

Oracle Database 11g: Develop PL/SQL Program Units * E &&

uidelines Bor >riting Pac5ages


Develop pac5ages Bor general use) DeBine t/e pac5age speciBication beBore t/e bod,) 0/e pac5age speciBication s/ould contain onl, t/ose constructs t/at ,ou 2ant to be public) Place items in t/e declaration part oB t/e pac5age bod, 2/en ,ou must maintain t/em t/roug/out a session or across transactions) 0/e BineEgrain dependenc, management reduces t/e need to recompile reBerencing subprograms 2/en a pac5age speciBication c/anges) 0/e pac5age speciBication s/ould contain as Be2 constructs as possible)

%op,rig/t @ &''"A Oracle) .ll rig/ts reserved)

uidelines Bor >riting Pac5ages ?eep ,our pac5ages as general as possibleA so t/at t/e, can be reused in Buture applications) .lsoA avoid 2riting pac5ages t/at duplicate Beatures provided b, t/e Oracle server)

Pac5age speciBications reBlect t/e design oB ,our applicationA so deBine t/em beBore deBining t/e pac5age bodies) 0/e pac5age speciBication s/ould contain onl, t/ose constructs t/at must be visible to t/e users oB t/e pac5age) 0/usA ot/er developers cannot misuse t/e pac5age b, basing code on irrelevant details) Place items in t/e declaration part oB t/e pac5age bod, 2/en ,ou must maintain t/em t/roug/out a session or across transactions) :or eCampleA declare a variable called <U=6(1L(=PLO8(D as a private variable iB eac/ call to a procedure t/at uses t/e variable needs to be maintained) >/en declared as a global variable in t/e pac5age speciBicationA t/e value oB t/at global variable is initiali4ed in a session t/e Birst time a construct Brom t/e pac5age is invo5ed) 6eBore Oracle Database 11gA c/anges to t/e pac5age bod, did not rePuire recompilation oB dependent constructsA 2/ereas c/anges to t/e pac5age speciBication rePuired t/e recompilation oB ever, stored subprogram t/at reBerences t/e pac5age) Oracle Database 11g reduces t/is dependenc,) Dependencies are no2 trac5ed at t/e level oB element 2it/in unit) :ineE rain Dependenc, =anagement is covered in a later lesson)

c ra O l, - On

, em ad .c

ra c O

le

l ae rn Uste

Oracle Database 11g: Develop PL/SQL Program Units * E &*

In

Qui4
0/e pac5age speciBication is t/e interBace to ,our applications) It declares t/e public t,pesA variablesA constantsA eCceptionsA cursorsA and subprograms available Bor use) 0/e pac5age speciBication ma, also include P1. =.sA 2/ic/ are directives to t/e compiler) 1) 0rue &) :alse

%op,rig/t @ &''"A Oracle) .ll rig/ts reserved)

.ns2er: 1

l c ra O l, - On e

, em ad .c

ra c O

le In

l ae rn Uste

Oracle Database 11g: Develop PL/SQL Program Units * E &!

Summar,
In t/is lessonA ,ou s/ould /ave learned /o2 to: Describe pac5ages and list t/eir components %reate a pac5age to group related variablesA cursorsA constantsA eCceptionsA proceduresA and Bunctions Designate a pac5age construct as eit/er public or private Invo5e a pac5age construct Describe t/e use oB a bodiless pac5age

%op,rig/t @ &''"A Oracle) .ll rig/ts reserved)

Summar, 8ou group related procedures and Bunctions in a pac5age) Pac5ages improve organi4ationA managementA securit,A and perBormance)

. pac5age consists oB a pac5age speciBication and a pac5age bod,) 8ou can c/ange a pac5age bod, 2it/out aBBecting its pac5age speciBication) Pac5ages enable ,ou to /ide source code Brom users) >/en ,ou invo5e a pac5age Bor t/e Birst timeA t/e entire pac5age is loaded into memor,) 0/is reduces t/e dis5 access Bor subsePuent calls)

c ra O l, - On

, em ad .c

ra c O

le In

l ae rn Uste

Oracle Database 11g: Develop PL/SQL Program Units * E &+

Practice * Overvie2: %reating and Using Pac5ages


0/is practice covers t/e Bollo2ing topics: %reating pac5ages Invo5ing pac5age program units

%op,rig/t @ &''"A Oracle) .ll rig/ts reserved)

Practice *: Overvie2 In t/is practiceA ,ou create pac5age speciBications and pac5age bodies) 8ou t/en invo5e t/e constructs in t/e pac5ages b, using sample data)

<ote: IB ,ou are using SQL DeveloperA ,our compileEtime errors are displa,ed in t/e =essage Log tab) IB ,ou are using SQLKPlus to create ,our stored codeA use S9O> (11O1S to vie2 compile errors)

c ra O l, - On

, em ad .c

ra c O

le In

l ae rn Uste

Oracle Database 11g: Develop PL/SQL Program Units * E &$

>or5ing 2it/ Pac5ages

%op,rig/t @ &''"A Oracle) .ll rig/ts reserved)

l c ra O l, - On ra c O le In l ae rn Uste e

, em ad .c

Ob3ectives
.Bter completing t/is lessonA ,ou s/ould be able to do t/e Bollo2ing: Overload pac5age procedures and Bunctions Use Bor2ard declarations %reate an initiali4ation bloc5 in a pac5age bod, =anage persistent pac5age data states Bor t/e liBe oB a session Use associative arra,s HindeCEb, tablesI and records in pac5ages

%op,rig/t @ &''"A Oracle) .ll rig/ts reserved)

Lesson .im 0/is lesson introduces t/e more advanced Beatures oB PL/SQLA including overloadingA Bor2ard reBerencingA oneEtimeEonl, proceduresA and t/e persistenc, oB variablesA constantsA eCceptionsA and cursors) It also eCplains t/e eBBect oB pac5aging Bunctions t/at are used in SQL statements)

c ra O l, - On

, em ad .c

ra c O

le In

l ae rn Uste

Oracle Database 11g: Develop PL/SQL Program Units ! E &

Lesson .genda
Overloading pac5age subprogramsA using Bor2ard declarationsA and creating an initiali4ation bloc5 in a pac5age bod, =anaging persistent pac5age data states Bor t/e liBe oB a session and using associative arra,s HindeCEb, tablesI and records in pac5ages

%op,rig/t @ &''"A Oracle) .ll rig/ts reserved)

l c ra O l, - On ra c O le In l ae rn Uste e

, em ad .c

Oracle Database 11g: Develop PL/SQL Program Units ! E *

Overloading Subprograms in PL/SQL


(nables ,ou to create t2o or more subprograms 2it/ t/e same name 1ePuires t/at t/e subprogramFs Bormal parameters diBBer in numberA orderA or data t,pe Bamil, (nables ,ou to build BleCible 2a,s Bor invo5ing subprograms 2it/ diBBerent data Provides a 2a, to eCtend Bunctionalit, 2it/out loss oB eCisting codeR t/at isA adding ne2 parameters to eCisting subprograms Provides a 2a, to overload local subprogramsA pac5age subprogramsA and t,pe met/odsA but not standEalone subprograms

%op,rig/t @ &''"A Oracle) .ll rig/ts reserved)

Overloading Subprograms 0/e overloading Beature in PL/SQL enables ,ou to develop t2o or more pac5aged subprograms 2it/ t/e same name) Overloading is useBul 2/en ,ou 2ant a subprogram to accept similar sets oB parameters t/at /ave diBBerent data t,pes) :or eCampleA t/e 0OL%9.1 Bunction /as more t/an one 2a, to be calledA enabling ,ou to convert a number or a date to a c/aracter string) PL/SQL allo2s overloading oB pac5age subprogram names and ob3ect t,pe met/ods) 0/e 5e, rule is t/at ,ou can use t/e same name Bor diBBerent subprograms as long as t/eir Bormal parameters diBBer in numberA orderA or data t,pe Bamil,) %onsider using overloading 2/en: Processing rules Bor t2o or more subprograms are similarA but t/e t,pe or number oB parameters used varies Providing alternative 2a,s Bor Binding diBBerent data 2it/ var,ing searc/ criteria) :or eCampleA ,ou ma, 2ant to Bind emplo,ees b, t/eir emplo,ee ID and also provide a 2a, to Bind emplo,ees b, t/eir last name) 0/e logic is intrinsicall, t/e sameA but t/e parameters or searc/ criteria diBBer) (Ctending Bunctionalit, 2/en ,ou do not 2ant to replace eCisting code <ote: StandEalone subprograms cannot be overloaded) >riting local subprograms in ob3ect t,pe met/ods is not discussed in t/is course)

c ra O l, - On

, em ad .c

ra c O

le

l ae rn Uste

Oracle Database 11g: Develop PL/SQL Program Units ! E !

In

Overloading Subprograms HcontinuedI 1estrictions 8ou cannot overload: 02o subprograms iB t/eir Bormal parameters diBBer onl, in data t,pe and t/e diBBerent data t,pes are in t/e same Bamil, H<U=6(1 and D(%I=.L belong to t/e same Bamil,)I 02o subprograms iB t/eir Bormal parameters diBBer onl, in subt,pe and t/e diBBerent subt,pes are based on t,pes in t/e same Bamil, HV.1%9.1 and S01I< are PL/SQL subt,pes oB V.1%9.1&)I 02o Bunctions t/at diBBer onl, in return t,peA even iB t/e t,pes are in diBBerent Bamilies 8ou get a runEtime error 2/en ,ou overload subprograms 2it/ t/e preceding Beatures) <ote: 0/e preceding restrictions appl, iB t/e names oB t/e parameters are also t/e same) IB ,ou use diBBerent names Bor t/e parametersA ,ou can invo5e t/e subprograms b, using named notation Bor t/e parameters) 1esolving %alls 0/e compiler tries to Bind a declaration t/at matc/es t/e call) It searc/es Birst in t/e current scope and t/enA iB necessar,A in successive enclosing scopes) 0/e compiler stops searc/ing iB it Binds one or more subprogram declarations in 2/ic/ t/e name matc/es t/e name oB t/e called subprogram) :or similarl, named subprograms at t/e same level oB scopeA t/e compiler needs an eCact matc/ in numberA orderA and data t,pe bet2een t/e actual and Bormal parameters)

l c ra O l, - On ra c O le In l ae rn Uste e

, em ad .c

Oracle Database 11g: Develop PL/SQL Program Units ! E +

Overloading Procedures (Cample: %reating t/e Pac5age SpeciBication

%1(.0( O1 1(PL.%( P.%?. ( deptLp5g IS P1O%(DU1( addLdepartment HpLdeptno departments)departmentLidQ08P(A pLname departments)departmentLnameQ08P( :ZSun5no2nSA pLloc departments)locationLidQ08P( :Z 1G''IR

P1O%(DU1( addLdepartment HpLname departments)departmentLnameQ08P( :ZSun5no2nSA pLloc departments)locationLidQ08P( :Z 1G''IR (<D deptLp5gR /

%op,rig/t @ &''"A Oracle) .ll rig/ts reserved)

Overloading: (Cample 0/e slide s/o2s t/e deptLp5g pac5age speciBication 2it/ an overloaded procedure called addLdepartment) 0/e Birst declaration ta5es t/ree parameters t/at are used to provide data Bor a ne2 department record inserted into t/e department table) 0/e second declaration ta5es onl, t2o parameters because t/is version internall, generates t/e department ID t/roug/ an Oracle sePuence) It is better to speciB, data t,pes using t/e Q08P( attribute Bor variables t/at are used to populate columns in database tablesA as s/o2n in t/e eCample in t/e slideR /o2everA ,ou can also speciB, t/e data t,pes as Bollo2s:
%1(.0( O1 1(PL.%( P.%?. ( deptLp5gLmet/od& IS P1O%(DU1( addLdepartmentHpLdeptno <U=6(1A pLname V.1%9.1& :Z Sun5no2nSA pLloc <U=6(1 :Z 1G''IR )))

c ra O l, - On

, em ad .c

ra c O

le

l ae rn Uste

Oracle Database 11g: Develop PL/SQL Program Units ! E $

In

Overloading Procedures (Cample: %reating t/e Pac5age 6od,


EE Pac5age bod, oB pac5age deBined on previous slide) %1(.0( O1 1(PL.%( P.%?. ( 6OD8 deptLp5g IS P1O%(DU1( addLdepartment ME :irst procedureFs declaration HpLdeptno departments)departmentLidQ08P(A pLnamedepartments)departmentLnameQ08P( :Z Sun5no2nSA pLlocdepartments)locationLidQ08P( :Z 1G''I IS 6( I< I<S(10 I<0O departmentsHdepartmentLidA departmentLnameA locationLidI V.LU(S HpLdeptnoA pLnameA pLlocIR (<D addLdepartmentR P1O%(DU1( addLdepartment ME Second procedureFs declaration HpLnamedepartments)departmentLnameQ08P( :Z Sun5no2nSA pLlocdepartments)locationLidQ08P( :Z 1G''I IS 6( I< I<S(10 I<0O departments HdepartmentLidA departmentLnameA locationLidI V.LU(S HdepartmentsLseP)<(O0V.LA pLnameA pLlocIR (<D addLdepartmentR (<D deptLp5gR /

%op,rig/t @ &''"A Oracle) .ll rig/ts reserved)

Overloading: (Cample HcontinuedI IB ,ou call addLdepartment 2it/ an eCplicitl, provided department IDA t/en PL/SQL uses t/e Birst version oB t/e procedure) %onsider t/e Bollo2ing eCample:
(O(%U0( deptLp5g)addLdepartmentH"#'AS(ducationSA&+''I S(L(%0 K :1O= departments >9(1( departmentLid Z "#'R

IB ,ou call addLdepartment 2it/ no department IDA PL/SQL uses t/e second version:

c ra O l, - On

, em ad .c

ra c O

(O(%U0( deptLp5g)addLdepartment HS0rainingSA &!''I S(L(%0 K :1O= departments >9(1( departmentLname Z S0rainingSR

le

l ae rn Uste

Oracle Database 11g: Develop PL/SQL Program Units ! E G

In

Overloading and t/e S0.<D.1D Pac5age


. pac5age named S0.<D.1D deBines t/e PL/SQL environment and builtEin Bunctions) =ost builtEin Bunctions are overloaded) .n eCample is t/e 0OL%9.1 Bunction:

:U<%0IO< 0OL%9.1 :U<%0IO< 0OL%9.1 :U<%0IO< 0OL%9.1 :U<%0IO< 0OL%9.1 V.1%9.1&R )))

Hp1 Hp& Hp1 Hp1

D.0(I 1(0U1< V.1%9.1&R <U=6(1I 1(0U1< V.1%9.1&R D.0(A P& V.1%9.1&I 1(0U1< V.1%9.1&R <U=6(1A P& V.1%9.1&I 1(0U1<

. PL/SQL subprogram 2it/ t/e same name as a builtEin subprogram overrides t/e standard declaration in t/e local conteCtA unless PualiBied b, t/e pac5age name)
%op,rig/t @ &''"A Oracle) .ll rig/ts reserved)

Overloading and t/e S0.<D.1D Pac5age . pac5age named S0.<D.1D deBines t/e PL/SQL environment and globall, declares t,pesA eCceptionsA and subprograms t/at are available automaticall, to PL/SQL programs) =ost oB t/e builtEin Bunctions t/at are Bound in t/e S0.<D.1D pac5age are overloaded) :or eCampleA t/e 0OL%9.1 Bunction /as Bour diBBerent declarationsA as s/o2n in t/e slide) 0/e 0OL%9.1 Bunction can ta5e eit/er t/e D.0( or t/e <U=6(1 data t,pe and convert it to t/e c/aracter data t,pe) 0/e Bormat to 2/ic/ t/e date or number /as to be converted can also be speciBied in t/e Bunction call) IB ,ou reEdeclare a builtEin subprogram in anot/er PL/SQL programA t/en ,our local declaration overrides t/e standard or builtEin subprogram) 0o be able to access t/e builtEin subprogramA ,ou must PualiB, it 2it/ its pac5age name) :or eCampleA iB ,ou reEdeclare t/e 0OL%9.1 Bunction to access t/e builtEin BunctionA ,ou reBer to it as S0.<D.1D)0OL%9.1)

c ra O l, - On

, em ad .c

ra c O

IB ,ou reEdeclare a builtEin subprogram as a standEalone subprogramA t/enA to access ,our subprogramA ,ou must PualiB, it 2it/ ,our sc/ema name: Bor eCampleA S%O00)0OL%9.1) In t/e eCample in t/e slideA PL/SQL resolves a call to 0OL%9.1 b, matc/ing t/e number and data t,pes oB t/e Bormal and actual parameters)

le

l ae rn Uste

Oracle Database 11g: Develop PL/SQL Program Units ! E #

In

Illegal Procedure 1eBerence


6loc5Estructured languages suc/ as PL/SQL must declare identiBiers beBore reBerencing t/em) (Cample oB a reBerencing problem:

%1(.0( O1 1(PL.%( P.%?. ( 6OD8 Bor2ardLp5g IS P1O%(DU1( a2ardLbonusH) ) )I IS 6( I< calcLrating H) ) )IREEillegal reBerence (<DR

P1O%(DU1( calcLrating H) ) )I IS 6( I< ))) (<DR (<D Bor2ardLp5gR /

%op,rig/t @ &''"A Oracle) .ll rig/ts reserved)

Using :or2ard Declarations In generalA PL/SQL is li5e ot/er bloc5Estructured languages and does not allo2 Bor2ard reBerences) 8ou must declare an identiBier beBore using it) :or eCampleA a subprogram must be declared beBore ,ou can call it) %oding standards oBten rePuire t/at subprograms be 5ept in alp/abetical sePuence to ma5e t/em eas, to Bind) In t/is caseA ,ou ma, encounter problemsA as s/o2n in t/e slideA 2/ere t/e calcLrating procedure cannot be reBerenced because it /as not ,et been declared)

ra c O

8ou can solve t/e illegal reBerence problem b, reversing t/e order oB t/e t2o procedures) 9o2everA t/is eas, solution does not 2or5 iB t/e coding rules rePuire subprograms to be declared in alp/abetical order) 0/e solution in t/is case is to use Bor2ard declarations provided in PL/SQL) . Bor2ard declaration enables ,ou to declare t/e /eading oB a subprogramA t/at isA t/e subprogram speciBication terminated b, a semicolon) <ote: 0/e compilation error Bor calcLrating occurs onl, iB calcLrating is a private pac5aged procedure) IB calcLrating is declared in t/e pac5age speciBicationA it is alread, declared as iB it is a Bor2ard declarationA and its reBerence can be resolved b, t/e compiler)

c ra O l, - On

, em ad .c

le

l ae rn Uste

Oracle Database 11g: Develop PL/SQL Program Units ! E "

In

Using :or2ard Declarations to Solve Illegal Procedure 1eBerence


In t/e pac5age bod,A a Bor2ard declaration is a private subprogram speciBication terminated b, a semicolon)

%1(.0( O1 1(PL.%( P.%?. ( 6OD8 Bor2ardLp5g IS P1O%(DU1( calcLrating H)))IREE Bor2ard declaration EE Subprograms deBined in alp/abetical order P1O%(DU1( a2ardLbonusH)))I IS 6( I< calcLrating H)))IREE reBerence resolved` ))) (<DR P1O%(DU1( calcLrating H)))I IS EE implementation 6( I< ))) (<DR (<D Bor2ardLp5gR
%op,rig/t @ &''"A Oracle) .ll rig/ts reserved)

Using :or2ard Declarations HcontinuedI .s previousl, mentionedA PL/SQL enables ,ou to create a special subprogram declaration called a Bor2ard declaration) . Bor2ard declaration ma, be rePuired Bor private subprograms in t/e pac5age bod,A and consists oB t/e subprogram speciBication terminated b, a semicolon) :or2ard declarations /elp to: DeBine subprograms in logical or alp/abetical order DeBine mutuall, recursive subprograms) =utuall, recursive programs are programs t/at call eac/ ot/er directl, or indirectl,) roup and logicall, organi4e subprograms in a pac5age bod, >/en creating a Bor2ard declaration: 0/e Bormal parameters must appear in bot/ t/e Bor2ard declaration and t/e subprogram bod, 0/e subprogram bod, can appear an,2/ere aBter t/e Bor2ard declarationA but bot/ must appear in t/e same program unit :or2ard Declarations and Pac5ages 0,picall,A t/e subprogram speciBications go in t/e pac5age speciBicationA and t/e subprogram bodies go in t/e pac5age bod,) 0/e public subprogram declarations in t/e pac5age speciBication do not rePuire Bor2ard declarations)

c ra O l, - On

, em ad .c

ra c O

le

l ae rn Uste

Oracle Database 11g: Develop PL/SQL Program Units ! E 1'

In

Initiali4ing Pac5ages
0/e bloc5 at t/e end oB t/e pac5age bod, eCecutes once and is used to initiali4e public and private pac5age variables)
%1(.0( O1 1(PL.%( P.%?. ( taCes IS vLtaC<U=6(1R ))) EE declare all public procedures/Bunctions (<D taCesR / %1(.0( O1 1(PL.%( P.%?. ( 6OD8 taCes IS ))) EE declare all private variables ))) EE deBine public/private procedures/Bunctions 6( I< S(L(%0rateLvalue I<0O vLtaC :1O=taCLrates >9(1(rateLname Z S0.OSR (<D taCesR /

%op,rig/t @ &''"A Oracle) .ll rig/ts reserved)

Pac5age Initiali4ation 6loc5 0/e Birst time a component in a pac5age is reBerencedA t/e entire pac5age is loaded into memor, Bor t/e user session) 6, deBaultA t/e initial value oB variables is <ULL HiB not eCplicitl, initiali4edI) 0o initiali4e pac5age variablesA ,ou can: Use assignment operations in t/eir declarations Bor simple initiali4ation tas5s .dd code bloc5 to t/e end oB a pac5age bod, Bor more compleC initiali4ation tas5s %onsider t/e bloc5 oB code at t/e end oB a pac5age bod, as a pac5age initiali4ation bloc5 t/at eCecutes onceA 2/en t/e pac5age is Birst invo5ed 2it/in t/e user session) 0/e eCample in t/e slide s/o2s t/e vLtaC public variable being initiali4ed to t/e value in t/e taCLrates table t/e Birst time t/e taCes pac5age is reBerenced)

ra c O

<ote: IB ,ou initiali4e t/e variable in t/e declaration b, using an assignment operationA it is over2ritten b, t/e code in t/e initiali4ation bloc5 at t/e end oB t/e pac5age bod,) 0/e initiali4ation bloc5 is terminated b, t/e (<D 5e,2ord Bor t/e pac5age bod,)

c ra O l, - On

, em ad .c

le

l ae rn Uste

Oracle Database 11g: Develop PL/SQL Program Units ! E 11

In

Using Pac5age :unctions in SQL


8ou use pac5age Bunctions in SQL statements) 0o eCecute a SQL statement t/at calls a member BunctionA t/e Oracle database must 5no2 t/e BunctionFs purit, level) Purit, level is t/e eCtent to 2/ic/ t/e Bunction is Bree oB side eBBectsA 2/ic/ reBers to accessing database tablesA pac5age variablesA and so onA Bor reading or 2riting) It is important to control side eBBects because t/e, can:

M Prevent t/e proper paralleli4ation oB a Puer, M Produce orderEdependent andA t/ereBoreA indeterminate results M 1ePuire impermissible actions suc/ as t/e maintenance oB pac5age state across user sessions

%op,rig/t @ &''"A Oracle) .ll rig/ts reserved)

Using Pac5age :unctions in SQL and 1estrictions 0o eCecute a SQL statement t/at calls a stored BunctionA t/e Oracle Server must 5no2 t/e purit, level oB t/e BunctionA or t/e eCtent to 2/ic/ t/e Bunction is Bree oB side eBBects) 0/e term side eBBect reBers to accessing database tablesA pac5age variablesA and so Bort/ Bor reading or 2riting) It is important to control side eBBects because t/e, can prevent t/e proper paralleli4ation oB a Puer,A produce orderEdependent and t/ereBore indeterminate resultsA or rePuire impermissible actions suc/ as t/e maintenance oB pac5age state across user sessions) In generalA restrictions are c/anges to database tables or public pac5age variables Ht/ose declared in a pac5age speciBicationI) 1estrictions can dela, t/e eCecution oB a Puer,A ,ield orderE dependent Ht/ereBore indeterminateI resultsA or rePuire t/at t/e pac5age state variables be maintained across user sessions) Various restrictions are not allo2ed 2/en a Bunction is called Brom a SQL Puer, or a D=L statement)

c ra O l, - On

, em ad .c

ra c O

le In

l ae rn Uste

Oracle Database 11g: Develop PL/SQL Program Units ! E 1&

%ontrolling Side (BBects oB PL/SQL Subprograms


0o be callable Brom SQL statementsA a stored Bunction must obe, t/e Bollo2ing purit, rules to control side eBBects: >/en called Brom a S(L(%0 or a paralleli4ed D=L statementA t/e Bunction cannot modiB, an, database tables) >/en called Brom a D=L statementA t/e Bunction cannot Puer, or modiB, an, database tables modiBied b, t/at statement) >/en called Brom a S(L(%0 or D=L statementA t/e Bunction cannot eCecute SQL transaction controlA session controlA or s,stem control statements)

%op,rig/t @ &''"A Oracle) .ll rig/ts reserved)

%ontrolling Side (BBects oB PL/SQL Subprograms 0/e Be2er side eBBects a Bunction /asA t/e better it can be optimi4ed 2it/in a Puer,A particularl, 2/en t/e P.1.LL(LL(<.6L( or D(0(1=I<IS0I% /ints are used)

0o be callable Brom SQL statementsA a stored Bunction Hand an, subprograms t/at it callsI must obe, t/e purit, rules listed in t/e slide) 0/e purpose oB t/ose rules is to control side eBBects) IB an, SQL statement inside t/e Bunction bod, violates a ruleA ,ou get an error at run time H2/en t/e statement is parsedI) 0o c/ec5 Bor purit, rule violations at compile timeA use t/e 1(S01I%0L1(:(1(<%(S pragma to assert t/at a Bunction does not read or 2rite database tables or pac5age variables) <ote In t/e slideA a D=L statement reBers to an I<S(10A UPD.0(A or D(L(0( statement) :or inBormation about using t/e 1(S01I%0L1(:(1(<%(S pragmaA reBer to t/e Oracle Database PL/SQL Language 1eBerence 11g 1elease & H11)&I)

c ra O l, - On

, em ad .c

ra c O

le

l ae rn Uste

Oracle Database 11g: Develop PL/SQL Program Units ! E 1*

In

Pac5age :unction in SQL: (Cample

%1(.0( O1 1(PL.%( P.%?. ( taCesLp5g IS :U<%0IO< taC HpLvalue I< <U=6(1I 1(0U1< <U=6(1R (<D taCesLp5gR / %1(.0( O1 1(PL.%( P.%?. ( 6OD8 taCesLp5g IS :U<%0IO< taC HpLvalue I< <U=6(1I 1(0U1< <U=6(1 IS vLrate <U=6(1 :Z ')'#R 6( I< 1(0U1< HpLvalue K vLrateIR (<D taCR (<D taCesLp5gR /

S(L(%0 taCesLp5g)taCHsalar,IA salar,A lastLname :1O=emplo,eesR

%op,rig/t @ &''"A Oracle) .ll rig/ts reserved)

Pac5age :unction in SQL: (Cample 0/e Birst code eCample in t/e slide s/o2s /o2 to create t/e pac5age speciBication and t/e bod, encapsulating t/e taC Bunction in t/e taCesLp5g pac5age) 0/e second code eCample s/o2s /o2 to call t/e pac5aged taC Bunction in t/e S(L(%0 statement) 0/e results are as Bollo2s:

c ra O l, - On

, em ad .c

ra c O

)))

le In

l ae rn Uste

Oracle Database 11g: Develop PL/SQL Program Units ! E 1!

Lesson .genda
Overloading pac5age subprogramsA using Bor2ard declarationsA and creating an initiali4ation bloc5 in a pac5age bod, =anaging persistent pac5age data states Bor t/e liBe oB a session and using associative arra,s HindeCEb, tablesI and records in pac5ages

%op,rig/t @ &''"A Oracle) .ll rig/ts reserved)

l c ra O l, - On ra c O le In l ae rn Uste e

, em ad .c

Oracle Database 11g: Develop PL/SQL Program Units ! E 1+

Persistent State oB Pac5ages


0/e collection oB pac5age variables and t/e values deBine t/e pac5age state) 0/e pac5age state is: Initiali4ed 2/en t/e pac5age is Birst loaded Persistent Hb, deBaultI Bor t/e liBe oB t/e session:
M Stored in t/e User lobal .rea HU .I M UniPue to eac/ session M Sub3ect to c/ange 2/en pac5age subprograms are called or public variables are modiBied

<ot persistent Bor t/e session but persistent Bor t/e liBe oB a subprogram call 2/en using P1. =. S(1I.LL8L1(US.6L( in t/e pac5age speciBication

%op,rig/t @ &''"A Oracle) .ll rig/ts reserved)

Persistent State oB Pac5ages 0/e collection oB public and private pac5age variables represents t/e pac5age state Bor t/e user session) 0/at isA t/e pac5age state is t/e set oB values stored in all t/e pac5age variables at a given point in time) In generalA t/e pac5age state eCists Bor t/e liBe oB t/e user session) Pac5age variables are initiali4ed t/e Birst time a pac5age is loaded into memor, Bor a user session) 0/e pac5age variables areA b, deBaultA uniPue to eac/ session and /old t/eir values until t/e user session is terminated) In ot/er 2ordsA t/e variables are stored in t/e User lobal .rea HU .I memor, allocated b, t/e database Bor eac/ user session) 0/e pac5age state c/anges 2/en a pac5age subprogram is invo5ed and its logic modiBies t/e variable state) Public pac5age state can be directl, modiBied b, operations appropriate to its t,pe) P1. =. signiBies t/at t/e statement is a compiler directive) P1. =.s are processed at compile timeA not at run time) 0/e, do not aBBect t/e meaning oB a programR t/e, simpl, conve, inBormation to t/e compiler) IB ,ou add P1. =. S(1I.LL8L1(SU.6L( to t/e pac5age speciBicationA t/en t/e database stores pac5age variables in t/e S,stem lobal .rea HS .I s/ared across user sessions) In t/is caseA t/e pac5age state is maintained Bor t/e liBe oB a subprogram call or a single reBerence to a pac5age construct) 0/e S(1I.LL8L1(US.6L( directive is useBul iB ,ou 2ant to conserve memor, and iB t/e pac5age state does not need to persist Bor eac/ user session)

c ra O l, - On

, em ad .c

ra c O

le

l ae rn Uste

Oracle Database 11g: Develop PL/SQL Program Units ! E 1$

In

Persistent State oB Pac5ages HcontinuedI 0/is P1. =. is appropriate Bor pac5ages t/at declare large temporar, 2or5 areas t/at are used once and not needed during subsePuent database calls in t/e same session) 8ou can mar5 a bodiless pac5age as seriall, reusable) IB a pac5age /as a spec and bod,A ,ou must mar5 bot/) 8ou cannot mar5 onl, t/e bod,) 0/e global memor, Bor seriall, reusable pac5ages is pooled in t/e S,stem lobal .rea HS .IA not allocated to individual users in t/e User lobal .rea HU .I) 0/at 2a,A t/e pac5age 2or5 area can be reused) >/en t/e call to t/e server endsA t/e memor, is returned to t/e pool) (ac/ time t/e pac5age is reusedA its public variables are initiali4ed to t/eir deBault values or to <ULL)

<ote: Seriall, reusable pac5ages cannot be accessed Brom database triggers or ot/er PL/SQL subprograms t/at are called Brom SQL statements) IB ,ou tr,A t/e Oracle server generates an error)

l c ra O l, - On ra c O le In l ae rn Uste e

, em ad .c

Oracle Database 11g: Develop PL/SQL Program Units ! E 1G

Persistent State oB Pac5age Variables: (Cample


State Bor Scott
0ime (vents
vLstdL comm VvariableW =.O Hcommissi onLpctI VcolumnW ')!

State Bor ;ones


vLstdL comm VvariableW E =.O Hcommissi onLpctI V%olumnW ')!

":''

Scott\ (O(%U0( commLp5g)resetLcommH')&+I ;ones\ I<S(10 I<0O emplo,eesHlastLnameA commissionLpctI V.LU(SHS=adonnaSA ')#IR ;ones\ (O(%U0( commLp5g)resetLcomm H')+I Scott\ (O(%U0( commLp5g)resetLcommH')$I (rr M&'&1' S6ad %ommissionS ;ones\ 1OLL6.%?R (OI0 ))) (O(% commLp5g)resetLcommH')&I

')1' ')&+

":*'

')#

')&+

')! ')1' ')+ ')#

":*+

')&+

')!

1':''

')&+ ')&+ ')&+ ')&+

')! ')! ')! ')!

')+ ')+ E ')&

')# ')! ')! ')!

11:'' 11:'1 1&:''

%op,rig/t @ &''"A Oracle) .ll rig/ts reserved)

Persistent State oB Pac5age Variables: (Cample 0/e slide sePuence is based on t2o diBBerent usersA Scott and ;onesA eCecuting commLp5g Hcovered in t/e lesson titled X%reating Pac5agesYIA in 2/ic/ t/e resetLcomm procedure invo5es t/e validate Bunction to c/ec5 t/e ne2 commission) 0/e eCample s/o2s /o2 t/e persistent state oB t/e vLstdLcomm pac5age variable is maintained in eac/ user session) .t ":'': Scott calls resetLcomm 2it/ a ne2 commission value oB ')&+A t/e pac5age state Bor vLstdLcomm is initiali4ed to ')1' and t/en set to ')&+A 2/ic/ is validated because it is less t/an t/e database maCimum value oB ')!) .t ":*': ;ones inserts a ne2 ro2 into t/e (=PLO8((S table 2it/ a ne2 maCimum vLcommissionLpct value oB ')#) 0/is is not committedA so it is visible to ;ones onl,) ScottFs state is unaBBected) .t ":*+: ;ones calls resetLcomm 2it/ a ne2 commission value oB ')+) 0/e state Bor ;onesFs vLstdLcomm is Birst initiali4ed to ')1' and t/en set to t/e ne2 value ')+ t/at is valid Bor /is session 2it/ t/e database maCimum value oB ')#) .t 1':'': Scott calls resetLcomm 2it/ a ne2 commission value oB ')$A 2/ic/ is greater t/an t/e maCimum database commission visible to /is sessionA t/at isA ')!) H;ones did not commit t/e ')# value)I 6et2een 11:'' and 1&:'': ;ones rolls bac5 t/e transaction HI<S(10 statementI and eCits t/e session) ;ones logs in at 11:!+ and successBull, eCecutes t/e procedureA setting /is state to ')&)

c ra O l, - On

, em ad .c

ra c O

le

l ae rn Uste

Oracle Database 11g: Develop PL/SQL Program Units ! E 1#

In

Persistent State oB a Pac5age %ursor: (Cample

%1(.0( O1 1(PL.%( P.%?. ( cursLp5g IS ME Pac5age spec P1O%(DU1( openR :U<%0IO< neCtHpLn <U=6(1 :Z 1I 1(0U1< 6OOL(.<R P1O%(DU1( closeR (<D cursLp5gR %1(.0( O1 1(PL.%( P.%?. ( 6OD8 cursLp5g IS ME Pac5age bod, %U1SO1 curLc IS S(L(%0 emplo,eeLid :1O= emplo,eesR P1O%(DU1( open IS 6( I< I: <O0 curLcQISOP(< 09(< OP(< curLcR (<D I:R (<D openR ) ) ) EE code continued on neCt slide

%op,rig/t @ &''"A Oracle) .ll rig/ts reserved)

Persistent State oB a Pac5age %ursor: (Cample 0/e eCample in t/e slide s/o2s t/e %U1SLP? pac5age speciBication and bod,) 0/e bod, declaration is continued in t/e neCt slide) 0o use t/is pac5ageA perBorm t/e Bollo2ing steps to process t/e ro2s: 1) %all t/e open procedure to open t/e cursor)

c ra O l, - On

, em ad .c

ra c O

le In

l ae rn Uste

Oracle Database 11g: Develop PL/SQL Program Units ! E 1"

Persistent State oB a Pac5age %ursor: (Cample


))) :U<%0IO< neCtHpLn <U=6(1 :Z 1I 1(0U1< 6OOL(.< IS vLempLid emplo,ees)emplo,eeLidQ08P(R 6( I< :O1 count I< 1 )) pLn LOOP :(0%9 curLc I<0O vLempLidR (OI0 >9(< curLcQ<O0:OU<DR D6=SLOU0PU0)PU0LLI<(HSId: S TTHvLempLidIIR (<D LOOPR 1(0U1< curLcQ:OU<DR (<D neCtR P1O%(DU1( close IS 6( I< I: curLcQISOP(< 09(< %LOS( curLcR (<D I:R (<D closeR (<D cursLp5gR

%op,rig/t @ &''"A Oracle) .ll rig/ts reserved)

Persistent State oB a Pac5age %ursor: (Cample HcontinuedI &) %all t/e neCt procedure to Betc/ one or a speciBied number oB ro2s) IB ,ou rePuest more ro2s t/an actuall, eCistA t/e procedure successBull, /andles termination) It returns 01U( iB more ro2s need to be processedR ot/er2ise it returns :.LS() *) %all t/e close procedure to close t/e cursorA beBore or at t/e end oB processing t/e ro2s) <ote: 0/e cursor declaration is private to t/e pac5age) 0/ereBoreA t/e cursor state can be inBluenced b, invo5ing t/e pac5age procedure and Bunctions listed in t/e slide)

c ra O l, - On

, em ad .c

ra c O

le In

l ae rn Uste

Oracle Database 11g: Develop PL/SQL Program Units ! E &'

(Cecuting t/e %U1SLP? Pac5age

%op,rig/t @ &''"A Oracle) .ll rig/ts reserved)

(Cecuting %U1SLP?

l c ra O l, - On e

1ecall t/at t/e state oB a pac5age variable or cursor persists across transactions 2it/in a session) 9o2everA t/e state does not persist across diBBerent sessions Bor t/e same user) 0/e database tables /old data t/at persists across sessions and users) 0/e call to cursLp5g)open opens t/e cursorA 2/ic/ remains open until t/e session is terminatedA or t/e cursor is eCplicitl, closed) 0/e anon,mous bloc5 eCecutes t/e neCt Bunction in t/e Declaration sectionA initiali4ing t/e 6OOL(.< variable bLmore to 01U(A as t/ere are more t/an t/ree ro2s in t/e (=PLO8((S table) 0/e bloc5 c/ec5s Bor t/e end oB t/e result set and closes t/e cursorA iB appropriate) >/en t/e bloc5 eCecutesA it displa,s t/e Birst t/ree ro2s:
Id :1'' Id :1'1 Id :1'& Id :1'* Id :1'! Id :1'+

, em ad .c

IB ,ou clic5 t/e 1un Script H:+I icon againA t/e neCt t/ree ro2s are displa,ed:

ra c O

le

0o close t/e cursorA ,ou can issue t/e Bollo2ing command to close t/e cursor in t/e pac5ageA or eCit t/e session:
(O(%U0( cursLp5g)close

l ae rn Uste

Oracle Database 11g: Develop PL/SQL Program Units ! E &1

In

Using .ssociative .rra,s in Pac5ages

%1(.0( O1 1(PL.%( P.%?. ( empLp5g IS 08P( empLtableLt,pe IS 0.6L( O: emplo,eesQ1O>08P( I<D(O 68 6I<.18LI<0( (1R P1O%(DU1( getLemplo,eesHpLemps OU0 empLtableLt,peIR (<D empLp5gR

%1(.0( O1 1(PL.%( P.%?. ( 6OD8 empLp5g IS P1O%(DU1( getLemplo,eesHpLemps OU0 empLtableLt,peI IS vLi 6I<.18LI<0( (1 :Z 'R 6( I< :O1 empLrecord I< HS(L(%0 K :1O= emplo,eesI LOOP empsHvLiI :Z empLrecordR vLi:Z vLi N 1R (<D LOOPR (<D getLemplo,eesR (<D empLp5gR

%op,rig/t @ &''"A Oracle) .ll rig/ts reserved)

Using .ssociative .rra,s in Pac5ages .ssociative arra,s used to be 5no2n as indeC b, tables) 0/e empLp5g pac5age contains a getLemplo,ees procedure t/at reads ro2s Brom t/e (=PLO8((S table and returns t/e ro2s using t/e OU0 parameterA 2/ic/ is an associative arra, HPL/SQL table oB recordsI) 0/e 5e, points include t/e Bollo2ing: emplo,eeLtableLt,pe is declared as a public t,pe) emplo,eeLtableLt,pe is used Bor a Bormal output parameter in t/e procedureA and t/e emplo,ees variable in t/e calling bloc5 Hs/o2n belo2I) In SQL DeveloperA ,ou can invo5e t/e getLemplo,ees procedure in an anon,mous PL/SQL bloc5 b, using t/e vLemplo,ees variableA as s/o2n in t/e Bollo2ing eCample and output:

ra c O

S(0 S(1V(1OU0PU0 O< D(%L.1( vLemplo,ees empLp5g)empLtableLt,peR 6( I< empLp5g)getLemplo,eesHvLemplo,eesIR D6=SLOU0PU0)PU0LLI<(HS(mp +: STTvLemplo,eesH!I)lastLnameIR (<DR

c ra O l, - On

, em ad .c

le

l ae rn Uste

Oracle Database 11g: Develop PL/SQL Program Units ! E &&

In

Qui4
Overloading subprograms in PL/SQL: 1) (nables ,ou to create t2o or more subprograms 2it/ t/e same name &) 1ePuires t/at t/e subprogramFs Bormal parameters diBBer in numberA orderA or data t,pe Bamil, *) (nables ,ou to build BleCible 2a,s Bor invo5ing subprograms 2it/ diBBerent data !) Provides a 2a, to eCtend Bunctionalit, 2it/out loss oB eCisting codeR t/at isA adding ne2 parameters to eCisting subprograms

%op,rig/t @ &''"A Oracle) .ll rig/ts reserved)

.ns2ers: 1A &A *A ! 0/e overloading Beature in PL/SQL enables ,ou to develop t2o or more pac5aged subprograms 2it/ t/e same name) Overloading is useBul 2/en ,ou 2ant a subprogram to accept similar sets oB parameters t/at /ave diBBerent data t,pes) :or eCampleA t/e 0OL%9.1 Bunction /as more t/an one 2a, to be calledA enabling ,ou to convert a number or a date to a c/aracter string) PL/SQL allo2s overloading oB pac5age subprogram names and ob3ect t,pe met/ods) 0/e 5e, rule is t/at ,ou can use t/e same name Bor diBBerent subprograms as long as t/eir Bormal parameters diBBer in numberA orderA or data t,pe Bamil,) %onsider using overloading 2/en: Processing rules Bor t2o or more subprograms are similarA but t/e t,pe or number oB parameters used varies Providing alternative 2a,s Bor Binding diBBerent data 2it/ var,ing searc/ criteria) :or eCampleA ,ou ma, 2ant to Bind emplo,ees b, t/eir emplo,ee ID and also provide a 2a, to Bind emplo,ees b, t/eir last name) 0/e logic is intrinsicall, t/e sameA but t/e parameters or searc/ criteria diBBer) (Ctending Bunctionalit, 2/en ,ou do not 2ant to replace eCisting code

c ra O l, - On

, em ad .c

ra c O

le

l ae rn Uste

Oracle Database 11g: Develop PL/SQL Program Units ! E &*

In

Summar,
In t/is lessonA ,ou s/ould /ave learned /o2 to: Overload pac5age procedures and Bunctions Use Bor2ard declarations %reate an initiali4ation bloc5 in a pac5age bod, =anage persistent pac5age data states Bor t/e liBe oB a session Use associative arra,s HindeCEb, tablesI and records in pac5ages

%op,rig/t @ &''"A Oracle) .ll rig/ts reserved)

Summar, Overloading is a Beature t/at enables ,ou to deBine diBBerent subprograms 2it/ t/e same name) It is logical to give t2o subprograms t/e same name 2/en t/e processing in bot/ t/e subprograms is t/e same but t/e parameters passed to t/em var,) PL/SQL permits a special subprogram declaration called a Bor2ard declaration) . Bor2ard declaration enables ,ou to deBine subprograms in logical or alp/abetical orderA deBine mutuall, recursive subprogramsA and group subprograms in a pac5age) . pac5age initiali4ation bloc5 is eCecuted onl, 2/en t/e pac5age is Birst invo5ed 2it/in t/e ot/er user session) 8ou can use t/is Beature to initiali4e variables onl, once per session) 8ou can 5eep trac5 oB t/e state oB a pac5age variable or cursorA 2/ic/ persists t/roug/out t/e user sessionA Brom t/e time t/e user Birst reBerences t/e variable or cursor to t/e time t/e user disconnects) Using t/e PL/SQL 2rapperA ,ou can obscure t/e source code stored in t/e database to protect ,our intellectual propert,)

c ra O l, - On

, em ad .c

ra c O

le

l ae rn Uste

Oracle Database 11g: Develop PL/SQL Program Units ! E &!

In

Practice !: Overvie2
0/is practice covers t/e Bollo2ing topics: Using overloaded subprograms %reating a pac5age initiali4ation bloc5 Using a Bor2ard declaration

%op,rig/t @ &''"A Oracle) .ll rig/ts reserved)

Practice !: Overvie2 In t/is practiceA ,ou modiB, an eCisting pac5age to contain overloaded subprograms and ,ou use Bor2ard declarations) 8ou also create a pac5age initiali4ation bloc5 2it/in a pac5age bod, to populate a PL/SQL table)

c ra O l, - On

, em ad .c

ra c O

le In

l ae rn Uste

Oracle Database 11g: Develop PL/SQL Program Units ! E &+

l c ra O l, - On ra c O le In l ae rn Uste e

, em ad .c

Using OracleESupplied Pac5ages in .pplication Development

%op,rig/t @ &''"A Oracle) .ll rig/ts reserved)

l c ra O l, - On ra c O le In l ae rn Uste e

, em ad .c

Ob3ectives
.Bter completing t/is lessonA ,ou s/ould be able to do t/e Bollo2ing: Describe /o2 t/e D6=SLOU0PU0 pac5age 2or5s Use U0LL:IL( to direct output to operating s,stem Biles Describe t/e main Beatures oB U0LL=.IL

%op,rig/t @ &''"A Oracle) .ll rig/ts reserved)

Lesson .im In t/is lessonA ,ou learn /o2 to use some oB t/e OracleEsupplied pac5ages and t/eir capabilities)

c ra O l, - On

, em ad .c

ra c O

le In

l ae rn Uste

Oracle Database 11g: Develop PL/SQL Program Units + E &

Lesson .genda

IdentiB,ing t/e beneBits oB using t/e OracleEsupplied pac5ages and listing some oB t/ose pac5ages
Using t/e Bollo2ing OracleEsupplied pac5ages: M D6=SLOU0PU0 M U0LL:IL( M U0LL=.IL

%op,rig/t @ &''"A Oracle) .ll rig/ts reserved)

l c ra O l, - On ra c O le In l ae rn Uste e

, em ad .c

Oracle Database 11g: Develop PL/SQL Program Units + E *

Using OracleESupplied Pac5ages


0/e OracleEsupplied pac5ages:
M .re provided 2it/ t/e Oracle server M (Ctend t/e Bunctionalit, oB t/e database M (nable access to certain SQL Beatures t/at are normall, restricted Bor PL/SQL

:or eCampleA t/e D6=SLOU0PU0 pac5age 2as originall, designed to debug PL/SQL programs)

%op,rig/t @ &''"A Oracle) .ll rig/ts reserved)

Using OracleESupplied Pac5ages Pac5ages are provided 2it/ t/e Oracle server to allo2 eit/er oB t/e Bollo2ing: PL/SQL access to certain SQL Beatures 0/e eCtension oB t/e Bunctionalit, oB t/e database 8ou can use t/e Bunctionalit, provided b, t/ese pac5ages 2/en creating ,our applicationA or ,ou ma, simpl, 2ant to use t/ese pac5ages as ideas 2/en ,ou create ,our o2n stored procedures) =ost oB t/e standard pac5ages are created b, running catproc)sPl) 0/e D6=SLOU0PU0 pac5age is t/e one t/at ,ou 2ill be most Bamiliar 2it/ during t/is course) 8ou s/ould alread, be Bamiliar 2it/ t/is pac5age iB ,ou attended t/e Oracle Database 11g: PL/SQL :undamentals course)

c ra O l, - On

, em ad .c

ra c O

le In

l ae rn Uste

Oracle Database 11g: Develop PL/SQL Program Units + E !

(Camples oB Some OracleESupplied Pac5ages


9ere is an abbreviated list oB some OracleEsupplied pac5ages: D6=SLOU0PU0 U0LL:IL( U0LL=.IL D6=SL.L(10 D6=SLLO%? D6=SLS(SSIO< D6=SL.PPLI%.0IO<LI<:O 90P D6=SLS%9(DUL(1

%op,rig/t @ &''"A Oracle) .ll rig/ts reserved)

List oB Some OracleESupplied Pac5ages 0/e list oB PL/SQL pac5ages provided 2it/ an Oracle database gro2s 2it/ t/e release oB ne2 versions) 0/is lesson covers t/e Birst t/ree pac5ages in t/e slide) :or more inBormationA reBer to t/e Oracle Database PL/SQL Pac5ages and 0,pes 1eBerence 11g 1elease & H11)&I) 0/e Bollo2ing is a brieB description about t/e remaining listed pac5ages in t/e slide: D6=SLOU0PU0 provides debugging and buBBering oB teCt data) U0LL:IL( enables reading and 2riting oB operating s,stem teCt Biles) U0LL=.IL enables composing and sending oB email messages) D6=SL.L(10 supports as,nc/ronous notiBication oB database events) =essages or alerts are sent on a %O==I0 command) D6=SLLO%? is used to rePuestA convertA and release loc5s t/roug/ Oracle Loc5 =anagement services) D6=SLS(SSIO< enables programmatic use oB t/e .L0(1 S(SSIO< SQL statement and ot/er sessionElevel commands) D6=SL.PPLI%.0IO<LI<:O can be used 2it/ Oracle 0race and t/e SQL trace Bacilit, to record names oB eCecuting modules or transactions in t/e database Bor later use 2/en trac5ing t/e perBormance oB various modules and debugging) 90P pac5age 2rites 90=LEtagged data into database buBBers) D6=SLS%9(DUL(1 enables sc/eduling and automated eCecution oB PL/SQL bloc5sA stored proceduresA and eCternal procedures and eCecutables Hcovered in .ppendiC I)

c ra O l, - On

, em ad .c

ra c O

le

l ae rn Uste

Oracle Database 11g: Develop PL/SQL Program Units + E +

In

Lesson .genda
IdentiB,ing t/e beneBits oB using t/e OracleEsupplied pac5ages and listing some oB t/ose pac5ages Using t/e Bollo2ing OracleEsupplied pac5ages: M D6=SLOU0PU0 M U0LL:IL( M U0LL=.IL

%op,rig/t @ &''"A Oracle) .ll rig/ts reserved)

l c ra O l, - On ra c O le In l ae rn Uste e

, em ad .c

Oracle Database 11g: Develop PL/SQL Program Units + E $

9o2 t/e D6=SLOU0PU0 Pac5age >or5s


0/e D6=SLOU0PU0 pac5age enables ,ou to send messages Brom stored subprograms and triggers) PU0 and PU0LLI<( place teCt in t/e buBBer) (0LLI<( and (0LLI<(S read t/e buBBer) =essages are not sent until t/e sending subprogram or trigger completes) Use S(0 S(1V(1OU0PU0 O< to displa, messages in SQL Developer and SQLKPlus)
PU0 <(>LLI<( PU0LLI<(

Output

S(0 S(1V(1OU0 O< VSI7( nW (O(%U0( proc


%op,rig/t @ &''"A Oracle) .ll rig/ts reserved)

(0LLI<( (0LLI<(S

9o2 t/e D6=SLOU0PU0 Pac5age >or5s 0/e D6=SLOU0PU0 pac5age sends teCtual messages Brom an, PL/SQL bloc5 into a buBBer in t/e database) Procedures provided b, t/e pac5age include t/e Bollo2ing: PU0 appends teCt Brom t/e procedure to t/e current line oB t/e line output buBBer) <(>LLI<( places an endEoBEline mar5er in t/e output buBBer) PU0LLI<( combines t/e action oB PU0 and <(>LLI<( Hto trim leading spacesI) (0LLI<( retrieves t/e current line Brom t/e buBBer into a procedure variable) (0LLI<(S retrieves an arra, oB lines into a procedureEarra, variable) (<.6L(/DIS.6L( enables and disables calls to D6=SLOU0PU0 procedures)

ra c O

0/e buBBer si4e can be set b, using: 0/e SI7( n option appended to t/e S(0 S(1V(1OU0PU0 O< command 2/ere n is t/e number oB c/aracters) 0/e minimum is &A''' and t/e maCimum is unlimited) 0/e deBault is &'A''') .n integer parameter bet2een &A''' and 1A'''A''' in t/e (<.6L( procedure

c ra O l, - On

, em ad .c
6uBBer

le

8ou can output results to t/e 2indo2 Bor debugging purposes) 8ou can trace a code eCecution pat/ Bor a Bunction or procedure) 8ou can send messages bet2een subprograms and triggers) <ote: 0/ere is no mec/anism to Blus/ output during t/e eCecution oB a procedure)

l ae rn Uste

Oracle Database 11g: Develop PL/SQL Program Units + E G

In

Using t/e U0LL:IL( Pac5age to Interact 2it/ Operating S,stem :iles


0/e U0LL:IL( pac5age eCtends PL/SQL programs to read and 2rite operating s,stem teCt Biles: Provides a restricted version oB operating s,stem stream Bile I/O Bor teCt Biles %an access Biles in operating s,stem directories deBined b, a %1(.0( DI1(%0O18 statement

%1(.0( DI1(%0O18 reportsLdir .S S//ome/oracle/labs/plpu/reportsS

(O(% proc

U0LL:IL(

Operating s,stem Bile

%op,rig/t @ &''"A Oracle) .ll rig/ts reserved)

Interacting 2it/ Operating S,stem :iles 0/e OracleEsupplied U0LL:IL( pac5age is used to access teCt Biles in t/e operating s,stem oB t/e database server) 0/e database provides read and 2rite access to speciBic operating s,stem directories b, using: . %1(.0( DI1(%0O18 statement t/at associates an alias 2it/ an operating s,stem director,) 0/e database director, alias can be granted t/e 1(.D and >1I0( privileges to control t/e t,pe oB access to Biles in t/e operating s,stem) :or eCample:
%1(.0( DI1(%0O18 m,Ldir .S S/temp/m,LBilesSR 1.<0 1(.DA >1I0( O< DI1(%0O18 m,Ldir 0O public)

ra c O

0/e pat/s speciBied in t/e utlLBileLdir database initiali4ation parameter It is recommended t/at ,ou use t/e %1(.0( DI1(%0O18 Beature instead oB U0LL:IL(LDI1 Bor director, access veriBication) Director, ob3ects oBBer more BleCibilit, and granular control to t/e U0LL:IL( application administratorA can be maintained d,namicall, Ht/at isA 2it/out s/utting do2n t/e databaseIA and are consistent 2it/ ot/er Oracle tools) 0/e %1(.0( DI1(%0O18 privilege is granted onl, to S8S and S8S0(= b, deBault)

c ra O l, - On

, em ad .c

le

0/e operating s,stem directories speciBied b, using eit/er oB t/ese tec/niPues s/ould be accessible to and on t/e same mac/ine as t/e database server processes) 0/e pat/ Hdirector,I names ma, be caseEsensitive Bor some operating s,stems)

l ae rn Uste

Oracle Database 11g: Develop PL/SQL Program Units + E #

In

Some oB t/e U0LL:IL( Procedures and :unctions


Subprogram
ISOP(< Bunction :OP(< Bunction :%LOS( Bunction :%OP8 procedure : (0.001 procedure (0LLI<( procedure :1(=OV( procedure :1(<.=( procedure PU0 procedure PU0LLI<( procedure

Description
Determines iB a Bile /andle reBers to an open Bile Opens a Bile Bor input or output %loses all open Bile /andles %opies a contiguous portion oB a Bile to a ne2l, created Bile 1eads and returns t/e attributes oB a dis5 Bile 1eads teCt Brom an open Bile Deletes a dis5 BileA iB ,ou /ave suBBicient privileges 1enames an eCisting Bile to a ne2 name >rites a string to a Bile >rites a line to a BileA and so appends an operating s,stemEspeciBic line terminator

%op,rig/t @ &''"A Oracle) .ll rig/ts reserved)

Some oB t/e U0LL:IL( Procedures and :unctions 0/e table in t/e slide lists some oB t/e U0LL:IL( Pac5age subprograms) :or a complete list oB t/e pac5ageFs subprogramsA see t/e Oracle Database PL/SQL Pac5ages and 0,pes 1eBerence 11g 1elease & H11)&I guide)

c ra O l, - On

, em ad .c

ra c O

le In

l ae rn Uste

Oracle Database 11g: Develop PL/SQL Program Units + E "

:ile Processing Using t/e U0LL:IL( Pac5age: Overvie2


1eading a Bile
B:Z:OP(<HdirABileA S1SI Open Bor reading et lines Brom t/e teCt Bile (0LLI<(HBAbuBAlenI %lose t/e teCt Bile 8es =ore to readJ <o

>riting or appending to a Bile


PU0HBAbuBI PU0LLI<(HBAbuBI Open Bor 2rite/append B:Z:OP(<HdirABileAS>SI B:Z:OP(<HdirABileAS.SI Put lines into t/e teCt Bile =ore to 2riteJ 8es

:%LOS(HBI <o

%op,rig/t @ &''"A Oracle) .ll rig/ts reserved)

:ile Processing Using t/e U0LL:IL( Pac5age 8ou can use t/e procedures and Bunctions in t/e U0LL:IL( pac5age to open Biles 2it/ t/e :OP(< Bunction) 8ou can t/en eit/er read Brom or 2rite or append to t/e Bile until processing is done) .Bter ,ou Binis/ processing t/e BileA close t/e Bile b, using t/e :%LOS( procedure) 0/e Bollo2ing are t/e subprograms: 0/e :OP(< Bunction opens a Bile in a speciBied director, Bor input/output HI/OI and returns a Bile /andle used in subsePuent I/O operations) 0/e ISLOP(< Bunction returns a 6oolean value 2/enever a Bile /andle reBers to an open Bile) Use ISLOP(< to c/ec5 2/et/er t/e Bile is alread, open beBore opening t/e Bile) 0/e (0LLI<( procedure reads a line oB teCt Brom t/e Bile into an output buBBer parameter) H0/e maCimum input record si4e is 1A'&* b,tes unless ,ou speciB, a larger si4e in t/e overloaded version oB :OP(<)I 0/e PU0 and PU0LLI<( procedures 2rite teCt to t/e opened Bile) 0/e PU0: procedure provides Bormatted output 2it/ t2o Bormat speciBiers: Qs to substitute a value into t/e output string and an Bor a ne2 line c/aracter) 0/e <(>LLI<( procedure terminates a line in an output Bile) 0/e ::LUS9 procedure 2rites all data buBBered in memor, to a Bile) 0/e :%LOS( procedure closes an opened Bile) 0/e :%LOS(L.LL procedure closes all opened Bile /andles Bor t/e session)

c ra O l, - On

, em ad .c

ra c O

le

l ae rn Uste

Oracle Database 11g: Develop PL/SQL Program Units + E 1'

In

Using t/e .vailable Declared (Cceptions in t/e U0LL:IL( Pac5age


(Cception <ame
I<V.LIDLP.09 I<V.LIDL=OD( I<V.LIDL:IL(9.<DL( I<V.LIDLOP(1.0IO< 1(.DL(11O1

Description
:ile location invalid 0/e openLmode parameter in :OP(< is invalid :ile /andle invalid :ile could not be opened or operated on as rePuested Operating s,stem error occurred during t/e read operation Operating s,stem error occurred during t/e 2rite operation UnspeciBied PL/SQL error

>1I0(L(11O1

I<0(1<.LL(11O1

%op,rig/t @ &''"A Oracle) .ll rig/ts reserved)

(Cceptions in t/e U0LL:IL( Pac5age 0/e U0LL:IL( pac5age declares BiBteen eCceptions t/at indicate an error condition in t/e operating s,stem Bile processing) 8ou ma, /ave to /andle one oB t/ese eCceptions 2/en using U0LL:IL( subprograms)

. subset oB t/e eCceptions are displa,ed in t/e slide) :or additional inBormation about t/e remaining eCceptionsA reBer to t/e Oracle Database PL/SQL Pac5ages and 0,pes 1eBerence 11g 1elease & H11)&I guide) <ote: 0/ese eCceptions must al2a,s be preBiCed 2it/ t/e pac5age name) U0LL:IL( procedures can also raise predeBined PL/SQL eCceptions suc/ as <OLD.0.L:OU<D or V.LU(L(11O1) 0/e <OLD.0.L:OU<D eCception is raised 2/en reading past t/e end oB a Bile b, using U0LL:IL() (0LLI<( or U0LL:IL() (0LLI<(S)

c ra O l, - On

, em ad .c

ra c O

le In

l ae rn Uste

Oracle Database 11g: Develop PL/SQL Program Units + E 11

:OP(< and ISLOP(< :unctions: (Cample


0/is :OP(< Bunction opens a Bile Bor input or output)

:U<%0IO< :OP(< HpLlocation I< V.1%9.1&A pLBilename I< V.1%9.1&A pLopenLmode I< V.1%9.1&I 1(0U1< U0LL:IL():IL(L08P(R

0/e ISLOP(< Bunction determines 2/et/er a Bile /andle reBers to an open Bile)

:U<%0IO< ISLOP(< HpLBile I< :IL(L08P(I 1(0U1< 6OOL(.<R

%op,rig/t @ &''"A Oracle) .ll rig/ts reserved)

:OP(< and ISLOP(< :unction Parameters: (Cample

l e

ra c O

0/e parameters include t/e Bollo2ing: pLlocation parameter: SpeciBies t/e name oB a director, alias deBined b, a %1(.0( DI1(%0O18 statementA or an operating s,stemMspeciBic pat/ speciBied b, using t/e utlLBileLdir database parameter pLBilename parameter: SpeciBies t/e name oB t/e BileA including t/e eCtensionA 2it/out an, pat/ inBormation openLmode string: SpeciBies /o2 t/e Bile is to be opened) Values are: S1S Bor reading teCt Huse (0LLI<(I S>S Bor 2riting teCt HPU0A PU0LLI<(A <(>LLI<(A PU0:A ::LUS9I S.S Bor appending teCt HPU0A PU0LLI<(A <(>LLI<(A PU0:A ::LUS9I 0/e return value Brom :OP(< is a Bile /andle 2/ose t,pe is U0LL:IL():IL(L08P() 0/e /andle must be used on subsePuent calls to routines t/at operate on t/e opened Bile) 0/e ISLOP(< Bunction parameter is t/e Bile /andle) 0/e ISLOP(< Bunction tests a Bile /andle to see 2/et/er it identiBies an opened Bile) It returns a 6oolean value oB 01U( iB t/e Bile /as been openedR ot/er2ise it returns a value oB :.LS( indicating t/at t/e Bile /as not been opened) 0/e eCample in t/e slide s/o2s /o2 to combine t/e use oB t/e t2o subprograms) :or t/e Bull s,ntaCA reBer to t/e Oracle Database PL/SQL Pac5ages and 0,pes 1eBerence 11g 1elease & H11)&I guide)

c ra O l, - On

, em ad .c

le

l ae rn Uste

Oracle Database 11g: Develop PL/SQL Program Units + E 1&

In

:OP(< and ISLOP(< :unction Parameters: (Cample HcontinuedI


%1(.0( O1 1(PL.%( P1O%(DU1( readLBileHpLdir V.1%9.1&A pLBilename V.1%9.1&I IS BLBile U0LL:IL():IL(L08P(R vLbuBBer V.1%9.1&H&''IR vLlines PLSLI<0( (1 :Z 'R 6( I< D6=SLOU0PU0)PU0LLI<(HS Start SIR I: <O0 U0LL:IL()ISLOP(<HBLBileI 09(< D6=SLOU0PU0)PU0LLI<(HS Open SIR BLBile :Z U0LL:IL():OP(< HpLdirA pLBilenameA S1SIR D6=SLOU0PU0)PU0LLI<(HS Opened SIR 6( I< LOOP U0LL:IL() (0LLI<(HBLBileA vLbuBBerIR vLlines :Z vLlines N 1R D6=SLOU0PU0)PU0LLI<(H0OL%9.1HvLlinesA S'""SITTS STTbuBBerIR (<D LOOPR (O%(P0IO< >9(< <OLD.0.L:OU<D 09(< D6=SLOU0PU0)PU0LLI<(HS KK (nd oB :ile KKSIR (<DR EE ends 6egin D6=SLOU0PU0)PU0LLI<(HvLlinesTTS lines read Brom BileSIR U0LL:IL():%LOS(HBLBileIR (<D I:R (<D readLBileR / S9O> (11O1S (O(%U0( readLBileHS1(PO10SLDI1SA Sinstructor)tCtSI

l
0/e partial output oB t/e above code is as Bollo2s:

c ra O l, - On

, em ad .c

ra c O

)))

le In

l ae rn Uste

Oracle Database 11g: Develop PL/SQL Program Units + E 1*

Using U0LL:IL(: (Cample

%1(.0( O1 1(PL.%( P1O%(DU1( salLstatusH pLdir I< V.1%9.1&A pLBilename I< V.1%9.1&I IS BLBile U0LL:IL():IL(L08P(R %U1SO1 curLemp IS S(L(%0 lastLnameA salar,A departmentLid :1O= emplo,ees O1D(1 68 departmentLidR vLne2deptno emplo,ees)departmentLidQ08P(R vLolddeptno emplo,ees)departmentLidQ08P( :Z 'R 6( I< BLBile:Z U0LL:IL():OP(< HpLdirA pLBilenameA S>SIR U0LL:IL()PU0LLI<(HBLBileA S1(PO10: (<(1.0(D O< S TT S8SD.0(IR U0LL:IL()<(>LLI<( HBLBileIR )))

%op,rig/t @ &''"A Oracle) .ll rig/ts reserved)

Using U0LL:IL(: (Cample In t/e slide eCampleA t/e salLstatus procedure creates a report oB emplo,ees Bor eac/ departmentA along 2it/ t/eir salaries) 0/e data is 2ritten to a teCt Bile b, using t/e U0LL:IL( pac5age) In t/e code eCampleA t/e Bile variable is declared as U0LL:IL():IL(L08P(A a pac5age t,pe t/at is a record 2it/ a Bield called ID oB t/e 6I<.18LI<0( (1 data t,pe) :or eCample:
08P( BileLt,pe IS 1(%O1D Hid 6I<.18LI<0( (1IR

0/e Bield oB :IL(L08P( record is private to t/e U0LL:IL( pac5age and s/ould never be reBerenced or c/anged) 0/e salLstatus procedure accepts t2o parameters: 0/e pLdir parameter Bor t/e name oB t/e director, in 2/ic/ to 2rite t/e teCt Bile 0/e pLBilename parameter to speciB, t/e name oB t/e Bile :or eCampleA to call t/e procedureA use t/e Bollo2ing:

c ra O l, - On

, em ad .c

(O(%U0( salLstatusHS1(PO10SLDI1SA Ssalreport&)tCtSI

ra c O

<ote: 0/e director, location used H1(PO10SLDI1I must be in uppercase c/aracters iB it is a director, alias created b, a %1(.0( DI1(%0O18 statement) >/en reading a Bile in a loopA t/e loop s/ould eCit 2/en it detects t/e <OLD.0.L:OU<D eCception) 0/e U0LL:IL( output is sent s,nc/ronousl,) . D6=SLOU0PU0 procedure does not produce an output until t/e procedure is completed)

le

l ae rn Uste

Oracle Database 11g: Develop PL/SQL Program Units + E 1!

In

Using U0LL:IL(: (Cample


))) :O1 empLrec I< curLemp LOOP I: empLrec)departmentLid ^\ vLolddeptno 09(< U0LL:IL()PU0LLI<( HBLBileA SD(P.10=(<0: S TT empLrec)departmentLidIR U0LL:IL()<(>LLI<( HBLBileIR (<D I:R U0LL:IL()PU0LLI<( HBLBileA S (=PLO8((: S TT empLrec)lastLname TT S earns: S TT empLrec)salar,IR vLolddeptno :Z empLrec)departmentLidR U0LL:IL()<(>LLI<( HBLBileIR (<D LOOPR U0LL:IL()PU0LLI<(HBLBileASKKK (<D O: 1(PO10 KKKSIR U0LL:IL():%LOS( HBLBileIR (O%(P0IO< >9(< U0LL:IL()I<V.LIDL:IL(9.<DL( 09(< 1.IS(L.PPLI%.0IO<L(11O1HE&'''1ASInvalid :ile)SIR >9(< U0LL:IL()>1I0(L(11O1 09(< 1.IS(L.PPLI%.0IO<L(11O1 HE&'''&A SUnable to 2rite to BileSIR (<D salLstatusR/

%op,rig/t @ &''"A Oracle) .ll rig/ts reserved)

Using U0LL:IL(: (Cample HcontinuedI 0/e Bollo2ing is a sample oB t/e salreport&)tCt output Bile:

l e

c ra O l, - On

, em ad .c

ra c O
)))

le In

l ae rn Uste

Oracle Database 11g: Develop PL/SQL Program Units + E 1+

>/at Is t/e U0LL=.IL Pac5ageJ



M S(<D Bor messages 2it/out attac/ments M S(<DL.00.%9L1.> Bor messages 2it/ binar, attac/ments M S(<DL.00.%9LV.1%9.1& Bor messages 2it/ teCt attac/ments

. utilit, Bor managing email 1ePuires t/e setting oB t/e S=0PLOU0LS(1V(1 database initiali4ation parameter Provides t/e Bollo2ing procedures:

%op,rig/t @ &''"A Oracle) .ll rig/ts reserved)

Using U0LL=.IL 0/e U0LL=.IL pac5age is a utilit, Bor managing email t/at includes commonl, used email Beatures suc/ as attac/mentsA %%A 6%%A and return receipt) 0/e U0LL=.IL pac5age is not installed b, deBault because oB t/e S=0PLOU0LS(1V(1 conBiguration rePuirement and t/e securit, eCposure t/is involves) >/en installing U0LL=.ILA ,ou s/ould ta5e steps to prevent t/e port deBined b, S=0PLOU0LS(1V(1 being s2amped b, data transmissions) 0o install U0LL=.ILA log in as a D6. user in SQLKPlus and eCecute t/e Bollo2ing scripts:
][O1.%L(L9O=(/rdbms/admin/utlmail)sPl ][O1.%L(L9O=(/rdbms/admin/prvtmail)plb

8ou s/ould deBine t/e S=0PLOU0LS(1V(1 parameter in t/e init)ora Bile database initiali4ation Bile:
S=0PLOU0LS(1V(1Zm,stmpserver)m,domain)com

c ra O l, - On

, em ad .c

ra c O

0/e S=0PLOU0LS(1V(1 parameter speciBies t/e S=0P /ost and port to 2/ic/ U0LL=.IL delivers outbound email) =ultiple servers can be speciBiedA separated b, commas) IB t/e Birst server in t/e list is unavailableA t/en U0LL=.IL tries t/e second serverA and so on) IB S=0PLOU0LS(1V(1 is not deBinedA t/en t/is invo5es a deBault setting derived Brom D6LDO=.I<A 2/ic/ is a database initiali4ation parameter speciB,ing t/e logical location oB t/e database 2it/in t/e net2or5 structure) :or eCample:
dbLdomainZm,domain)com Oracle Database 11g: Develop PL/SQL Program Units + E 1$

le

l ae rn Uste

In

Setting Up and Using t/e U0LL=.IL: Overvie2

1) Install t/e U0LL=.IL pac5age)

&) DeBine t/e S=0PLOU0LS(1V(1 Initiali4ation parameter)

*) rant user t/e rePuired privilege)

+) Send an email)

!) Invo5e a U0LL=.IL subprogram)

%op,rig/t @ &''"A Oracle) .ll rig/ts reserved)

Setting Up and Using t/e U0LL=.IL: Overvie2 In Oracle Database 11gA t/e U0LL=.IL pac5age is no2 an invo5erFs rig/ts pac5age and t/e invo5ing user 2ill need t/e connect privilege granted in t/e access control list assigned to t/e remote net2or5 /ost to 2/ic/ /e 2ants to connect) 0/e Securit, .dministrator perBorms t/is tas5) <ote :or inBormation about /o2 a user 2it/ S8SD6. capabilities grants a user t/e rePuired BineE grained privileges rePuired Bor using t/is pac5ageA reBer to t/e X=anaging :ineE rained .ccess to (Cternal <et2or5 ServicesY topic in t/e Oracle Database Securit, uide 11g 1elease & H11)&I guide and t/e Oracle Database 11g .dvanced PL/SQL instructorEled training course) Due to Bire2all restrictionsA t/e U0LL=.IL eCamples in t/is lesson cannot be demonstratedR t/ereBoreA no labs 2ere designed to use U0LL=.IL)

c ra O l, - On

, em ad .c

ra c O

le In

l ae rn Uste

Oracle Database 11g: Develop PL/SQL Program Units + E 1G

Summar, oB U0LL=.IL Subprograms

Subprogram
S(<D procedure

Description
Pac5ages an email messageA locates S=0P inBormationA and delivers t/e message to t/e S=0P server Bor Bor2arding to t/e recipients 1epresents t/e S(<D procedure overloaded Bor 1.> attac/ments 1epresents t/e S(<D procedure overloaded Bor V.1%9.1& attac/ments

S(<DL.00.%9L1.> Procedure S(<DL.00.%9LV.1%9.1& Procedure

%op,rig/t @ &''"A Oracle) .ll rig/ts reserved)

l c ra O l, - On ra c O le In l ae rn Uste e

, em ad .c

Oracle Database 11g: Develop PL/SQL Program Units + E 1#

Installing and Using U0LL=.IL


.s S8SD6.A using SQL Developer or SQLKPlus:
M Install t/e U0LL=.IL pac5age
]J/rdbms/admin/utlmail)sPl ]J/rdbms/admin/prvtmail)plb

M Set t/e S=0PLOU0LS(1V(1


.L0(1 S8S0(= S(0 S=0PLOU0LS(1V(1ZSsmtp)server)comS S%OP(ZSP:IL(

.s a developerA invo5e a U0LL=.IL procedure:

6( I< U0LL=.IL)S(<DHSotn]oracle)comSASuser]oracle)comSA message Z\ S:or latest do2nloads visit O0<SA sub3ect Z\ SO0< <e2sletterSIR (<DR

%op,rig/t @ &''"A Oracle) .ll rig/ts reserved)

Installing and Using U0LL=.IL 0/e slide s/o2s /o2 to conBigure t/e S=0PLOU0LS(1V(1 parameter to t/e name oB t/e S=0P /ost in ,our net2or5A and /o2 to install t/e U0LL=.IL pac5age t/at is not installed b, deBault) %/anging t/e S=0PLOU0LS(1V(1 parameter rePuires restarting t/e database instance) 0/ese tas5s are perBormed b, a user 2it/ S8SD6. capabilities) 0/e last eCample in t/e slide s/o2s t/e simplest 2a, to send a teCt message b, using t/e U0LL=.IL)S(<D procedure 2it/ at least a sub3ect and a message) 0/e Birst t2o rePuired parameters are t/e Bollo2ing : 0/e sender email address Hin t/is caseA otn]oracle)comI 0/e recipients email address HBor eCampleA user]oracle)comI) 0/e value can be a commaEseparated list oB addresses) 0/e U0LL=.IL)S(<D procedure provides several ot/er parametersA suc/ as ccA bccA and priorit, 2it/ deBault valuesA iB not speciBied) In t/e eCampleA t/e message parameter speciBies t/e teCt Bor t/e emailA and t/e sub3ect parameter contains t/e teCt Bor t/e sub3ect line) 0o send an 90=L message 2it/ 90=L tagsA add t/e mimeLt,pe parameter HBor eCampleA mimeLt,peZ\SteCt//tmlSI) <ote: :or details about all t/e U0LL=.IL procedure parametersA reBer to t/e Oracle Database PL/SQL Pac5ages and 0,pes 1eBerence 11g 1elease & H11)&I guide)

c ra O l, - On

, em ad .c

ra c O

le

l ae rn Uste

Oracle Database 11g: Develop PL/SQL Program Units + E 1"

In

0/e S(<D Procedure S,ntaC


Pac5ages an email message into t/e appropriate BormatA locates S=0P inBormationA and delivers t/e message to t/e S=0P server Bor Bor2arding to t/e recipients

U0LL=.IL)S(<D H senderI< recipients I< ccI< bcc sub3ect message mimeLt,pe priorit, I< I< I< I< I<

V.1%9.1& %9.1.%0(1 S(0 .<8L%SA V.1%9.1& %9.1.%0(1 S(0 .<8L%SA V.1%9.1& %9.1.%0(1 S(0 .<8L%S D(:.UL0 <ULLA V.1%9.1& %9.1.%0(1 S(0 .<8L%S D(:.UL0 <ULLA V.1%9.1& %9.1.%0(1 S(0 .<8L%S D(:.UL0 <ULLA V.1%9.1& %9.1.%0(1 S(0 .<8L%SA V.1%9.1& D(:.UL0 SteCt/plainR c/arsetZusEasciiSA PLSLI<0( (1 D(:.UL0 <ULLIR

%op,rig/t @ &''"A Oracle) .ll rig/ts reserved)

0/e S(<D Procedure

l c ra O l, - On e

0/is procedure pac5ages an email message into t/e appropriate BormatA locates S=0P inBormationA and delivers t/e message to t/e S=0P server Bor Bor2arding to t/e recipients) It /ides t/e S=0P .PI and eCposes a oneEline email Bacilit, Bor ease oB use) 0/e S(<D Procedure Parameters sender: 0/e email address oB t/e sender) recipients: 0/e email addresses oB t/e recipientHsIA separated b, commas) cc: 0/e email addresses oB t/e %% recipientHsIA separated b, commas) 0/e deBault is <ULL) bcc: 0/e email addresses oB t/e 6%% recipientHsIA separated b, commas) 0/e deBault is <ULL) sub3ect: . string to be included as email sub3ect string) 0/e deBault is <ULL) message: . teCt message bod,) mimeLt,pe: 0/e mime t,pe oB t/e messageA deBault is SteCt/plainR c/arsetZusEasciiS) priorit,: 0/e message priorit,) 0/e deBault is <ULL)

, em ad .c

ra c O

le

l ae rn Uste

Oracle Database 11g: Develop PL/SQL Program Units + E &'

In

0/e S(<DL.00.%9L1.> Procedure


0/is procedure is t/e S(<D procedure overloaded Bor 1.> attac/ments)

U0LL=.IL)S(<DL.00.%9L1.> H senderI<V.1%9.1& %9.1.%0(1 S(0 .<8L%SA recipientsI<V.1%9.1& %9.1.%0(1 S(0 .<8L%SA ccI<V.1%9.1& %9.1.%0(1 S(0 .<8L%S D(:.UL0 <ULLA bccI<V.1%9.1& %9.1.%0(1 S(0 .<8L%S D(:.UL0 <ULLA sub3ectI<V.1%9.1& %9.1.%0(1 S(0 .<8L%S D(:.UL0 <ULLA messageI<V.1%9.1& %9.1.%0(1 S(0 .<8L%S D(:.UL0 <ULLA mimeLt,peI<V.1%9.1& D(:.UL0 %9.1.%0(1 S(0 .<8L%S D(:.UL0 SteCt/plainR c/arsetZusEasciiSA priorit,I<PLSLI<0( (1 D(:.UL0 *A attac/mentI<1.>A attLinlineI<6OOL(.< D(:.UL0 01U(A attLmimeLt,peI<V.1%9.1& %9.1.%0(1 S(0 .<8L%S D(:.UL0 SteCt/plainR c/arsetZusEasciiSA attLBilenameI<V.1%9.1& %9.1.%0(1 S(0 .<8L%S D(:.UL0 <ULLIR

%op,rig/t @ &''"A Oracle) .ll rig/ts reserved)

0/e S(<DL.00.%9L1.> Procedure Parameters sender: 0/e email address oB t/e sender recipients: 0/e email addresses oB t/e recipientHsIA separated b, commas cc: 0/e email addresses oB t/e %% recipientHsIA separated b, commas) 0/e deBault is <ULL) bcc: 0/e email addresses oB t/e 6%% recipientHsIA separated b, commas) 0/e deBault is <ULL) sub3ect: . string to be included as email sub3ect string) 0/e deBault is <ULL) message: . teCt message bod, mimeLt,pe: 0/e mime t,pe oB t/e messageA deBault is SteCt/plainR c/arsetZusEasciiS priorit,: 0/e message priorit,) 0/e deBault is <ULL) attac/ment: . 1.> attac/ment attLinline: SpeciBies 2/et/er t/e attac/ment is vie2able inline 2it/ t/e message bod,) 0/e deBault is 01U() attLmimeLt,pe: 0/e mime t,pe oB t/e attac/mentA deBault is Sapplication/octetS attLBilename: 0/e string speciB,ing a Bile name containing t/e attac/ment) 0/e deBault is <ULL)

c ra O l, - On

, em ad .c

ra c O

le

l ae rn Uste

Oracle Database 11g: Develop PL/SQL Program Units + E &1

In

Sending (mail 2it/ a 6inar, .ttac/ment: (Cample


%1(.0( O1 1(PL.%( P1O%(DU1( sendLmailLlogo IS 6( I< U0LL=.IL)S(<DL.00.%9L1.>H sender Z\ Sme]oracle)comSA recipients Z\ S,ou]some2/ere)netSA message Z\ S^90=L\^6OD8\See attac/ment^/6OD8\^/90=L\SA sub3ect Z\ SOracle LogoSA mimeLt,pe Z\ SteCt//tmlS attac/ment Z\ getLimageHSoracle)giBSIA attLinline Z\ trueA attLmimeLt,pe Z\ Simage/giBSA attLBilename Z\ Soralogo)giBSIR (<DR /

%op,rig/t @ &''"A Oracle) .ll rig/ts reserved)

Sending (mail 2it/ a 6inar, .ttac/ment: (Cample 0/e slide s/o2s a procedure calling t/e U0LL=.IL)S(<DL.00.%9L1.> procedure to send a teCtual or an 90=L message 2it/ a binar, attac/ment) In addition to t/e senderA recipientsA messageA sub3ectA and mimeLt,pe parameters t/at provide values Bor t/e main part oB t/e email messageA t/e S(<DL.00.%9L1.> procedure /as t/e Bollo2ing /ig/lig/ted parameters: 0/e attac/ment parameter HrePuiredI accepts a 1.> data t,peA 2it/ a maCimum si4e oB *&AG$G binar, c/aracters) 0/e attLinline parameter HoptionalI is 6oolean HdeBault 01U(I to indicate t/at t/e attac/ment is vie2able 2it/ t/e message bod,) 0/e attLmimeLt,pe parameter HoptionalI speciBies t/e Bormat oB t/e attac/ment) IB not providedA it is set to application/octet) 0/e attLBilename parameter HoptionalI assigns an, Bile name to t/e attac/ment) It is <ULL b, deBaultA in 2/ic/ caseA t/e name is assigned a deBault name) 0/e getLimage Bunction in t/e eCample uses a 6:IL( to read t/e image data) Using a 6:IL( rePuires creating a logical director, name in t/e database b, using t/e %1(.0( DI1(%0O18 statement) 0/e code Bor getLimage is s/o2n on t/e Bollo2ing page)

c ra O l, - On

, em ad .c

ra c O

le

l ae rn Uste

Oracle Database 11g: Develop PL/SQL Program Units + E &&

In

Sending (mail 2it/ a 6inar, .ttac/ment: (Cample HcontinuedI 0/e getLimage Bunction uses t/e D6=SLLO6 pac5age to read a binar, Bile Brom t/e operating s,stem:
%1(.0( O1 1(PL.%( :U<%0IO< getLimageH Bilename V.1%9.1&A dir V.1%9.1& :Z S0(=PSI 1(0U1< 1.> IS image 1.>H*&G$GIR Bile 6:IL( :Z 6:IL(<.=(HdirA BilenameIR 6( I< D6=SLLO6):IL(OP(<HBileA D6=SLLO6):IL(L1(.DO<L8IR image :Z D6=SLLO6)SU6S01HBileIR D6=SLLO6)%LOS(HBileIR 1(0U1< imageR (<DR /

0o create t/e director, called 0(=PA eCecute t/e Bollo2ing statement in SQL Developer or SQLKPlus:
%1(.0( DI1(%0O18 temp .S Sd:atempSR

<ote 8ou need t/e %1(.0( .<8 DI1(%0O18 s,stem privilege to eCecute t/is statement) Due to Bire2all restrictions at t/e Oracle (ducation %enterA t/e eCamples on t/is page and t/e previous page are not available Bor demonstration)

l c ra O l, - On ra c O le In l ae rn Uste e

, em ad .c

Oracle Database 11g: Develop PL/SQL Program Units + E &*

0/e S(<DL.00.%9LV.1%9.1& Procedure


0/is procedure is t/e S(<D procedure overloaded Bor V.1%9.1& attac/ments)

U0LL=.IL)S(<DL.00.%9LV.1%9.1& H senderI<V.1%9.1& %9.1.%0(1 S(0 .<8L%SA recipientsI<V.1%9.1& %9.1.%0(1 S(0 .<8L%SA ccI<V.1%9.1& %9.1.%0(1 S(0 .<8L%S D(:.UL0 <ULLA bccI<V.1%9.1& %9.1.%0(1 S(0 .<8L%S D(:.UL0 <ULLA sub3ectI<V.1%9.1& %9.1.%0(1 S(0 .<8L%S D(:.UL0 <ULLA messageI<V.1%9.1& %9.1.%0(1 S(0 .<8L%S D(:.UL0 <ULLA mimeLt,peI<V.1%9.1& %9.1.%0(1 S(0 .<8L%S D(:.UL0 SteCt/plainR c/arsetZusEasciiSA priorit,I<PLSLI<0( (1 D(:.UL0 *A attac/mentI<V.1%9.1& %9.1.%0(1 S(0 .<8L%SA attLinlineI<6OOL(.< D(:.UL0 01U(A attLmimeLt,peI<V.1%9.1& %9.1.%0(1 S(0 .<8L%S D(:.UL0 SteCt/plainR c/arsetZusEasciiSA attLBilenameI<V.1%9.1&%9.1.%0(1 S(0 .<8L%S D(:.UL0 <ULLIR

%op,rig/t @ &''"A Oracle) .ll rig/ts reserved)

0/e S(<DL.00.%9LV.1%9.1& Procedure Parameters sender: 0/e email address oB t/e sender recipients: 0/e email addresses oB t/e recipientHsIA separated b, commas cc: 0/e email addresses oB t/e %% recipientHsIA separated b, commas) 0/e deBault is <ULL) bcc: 0/e email addresses oB t/e 6%% recipientHsIA separated b, commas) 0/e deBault is <ULL) sub3ect: . string to be included as email sub3ect string) 0/e deBault is <ULL) =essage: . teCt message bod, mimeLt,pe: 0/e mime t,pe oB t/e messageA deBault is SteCt/plainR c/arsetZusEasciiS priorit,: 0/e message priorit,) 0/e deBault is <ULL) attac/ment: . teCt attac/ment attLinline: SpeciBies 2/et/er t/e attac/ment is inline) 0/e deBault is 01U() attLmimeLt,pe: 0/e mime t,pe oB t/e attac/mentA deBault is SteCt/plainR c/arsetZusEasciiS attLBilename: 0/e string speciB,ing a Bile name containing t/e attac/ment) 0/e deBault is <ULL)

c ra O l, - On

, em ad .c

ra c O

le

l ae rn Uste

Oracle Database 11g: Develop PL/SQL Program Units + E &!

In

Sending (mail 2it/ a 0eCt .ttac/ment: (Cample

%1(.0( O1 1(PL.%( P1O%(DU1( sendLmailLBile IS 6( I< U0LL=.IL)S(<DL.00.%9LV.1%9.1&H sender Z\ Sme]oracle)comSA recipients Z\ S,ou]some2/ere)netSA message Z\ S^90=L\^6OD8\See attac/ment^/6OD8\^/90=L\SA sub3ect Z\ SOracle <otesSA mimeLt,pe Z\ SteCt//tmlS attac/ment Z\ getLBileHSnotes)tCtSIA attLinline Z\ BalseA attLmimeLt,pe Z\ SteCt/plainSA attLBilename Z\ Snotes)tCtSIR (<DR /

%op,rig/t @ &''"A Oracle) .ll rig/ts reserved)

Sending (mail 2it/ a 0eCt .ttac/ment 0/e slide s/o2s a procedure t/at calls t/e U0LL=.IL)S(<DL.00.%9LV.1%9.1& procedure to send a teCtual or an 90=L message 2it/ a teCt attac/ment) In addition to t/e senderA recipientsA messageA sub3ectA and mimeLt,pe parameters t/at provide values Bor t/e main part oB t/e eEmail messageA t/e S(<DL.00.%9LV.1%9.1& procedure /as t/e Bollo2ing parameters /ig/lig/ted: 0/e attac/ment parameter HrePuiredI accepts a V.1%9.1& data t,pe 2it/ a maCimum si4e oB *&AG$G binar, c/aracters) 0/e attLinline parameter HoptionalI is a 6oolean HdeBault 01U(I to indicate t/at t/e attac/ment is vie2able 2it/ t/e message bod,) 0/e attLmimeLt,pe parameter HoptionalI speciBies t/e Bormat oB t/e attac/ment) IB not providedA it is set to application/octet) 0/e attLBilename parameter HoptionalI assigns an, Bile name to t/e attac/ment) It is <ULL b, deBaultA in 2/ic/ caseA t/e name is assigned a deBault name) 0/e getLBile Bunction in t/e eCample uses a 6:IL( to read a teCt Bile Brom t/e operating s,stem directories Bor t/e value oB t/e attac/ment parameterA 2/ic/ could simpl, be populated Brom a V.1%9.1& variable) 0/e code Bor getLBile is s/o2n on t/e Bollo2ing page)

c ra O l, - On

, em ad .c

ra c O

le

l ae rn Uste

Oracle Database 11g: Develop PL/SQL Program Units + E &+

In

Sending (mail 2it/ a 0eCt .ttac/ment HcontinuedI 0/e getLBile Bunction uses t/e D6=SLLO6 pac5age to read a binar, Bile Brom t/e operating s,stemA and uses t/e U0LL1.> pac5age to convert t/e 1.> binar, data into readable teCt data in t/e Borm oB a V.1%9.1& data t,pe:
%1(.0( O1 1(PL.%( :U<%0IO< getLBileH Bilename V.1%9.1&A dir V.1%9.1& :Z S0(=PSI 1(0U1< V.1%9.1& IS contents V.1%9.1&H*&G$GIR Bile 6:IL( :Z 6:IL(<.=(HdirA BilenameIR 6( I< D6=SLLO6):IL(OP(<HBileA D6=SLLO6):IL(L1(.DO<L8IR contents :Z U0LL1.>)%.S0L0OLV.1%9.1&H D6=SLLO6)SU6S01HBileIIR D6=SLLO6)%LOS(HBileIR 1(0U1< contentsR (<DR /

<ote: .lternativel,A ,ou could read t/e contents oB t/e teCt Bile into a V.1%9.1& variable b, using t/e U0LL:IL( pac5age Bunctionalit,) 0/e preceding eCample rePuires t/e 0(=P director, to be created similar to t/e Bollo2ing statement in SQLKPlus:
%1(.0( DI1(%0O18 temp .S S/tempSR

<ote 0/e %1(.0( .<8 DI1(%0O18 s,stem privilege is rePuired to eCecute t/is statement) Due to Bire2all restrictions at t/e Oracle (ducation %enterA t/e eCamples on t/is page and t/e previous page are not available Bor demonstration)

c ra O l, - On ra c O le In l ae rn Uste

, em ad .c

Oracle Database 11g: Develop PL/SQL Program Units + E &$

Qui4
0/e OracleEsupplied U0LL:IL( pac5age is used to access teCt Biles in t/e operating s,stem oB t/e database server) 0/e database provides Bunctionalit, t/roug/ director, ob3ects to allo2 access to speciBic operating s,stem directories) 1) 0rue &) :alse

%op,rig/t @ &''"A Oracle) .ll rig/ts reserved)

.ns2er: 1 0/e OracleEsupplied U0LL:IL( pac5age is used to access teCt Biles in t/e operating s,stem oB t/e database server) 0/e database provides read and 2rite access to speciBic operating s,stem directories b, using: . %1(.0( DI1(%0O18 statement t/at associates an alias 2it/ an operating s,stem director,) 0/e database director, alias can be granted t/e 1(.D and >1I0( privileges to control t/e t,pe oB access to Biles in t/e operating s,stem) 0/e pat/s speciBied in t/e utlLBileLdir database initiali4ation parameter

c ra O l, - On

, em ad .c

ra c O

le In

l ae rn Uste

Oracle Database 11g: Develop PL/SQL Program Units + E &G

Summar,
In t/is lessonA ,ou s/ould /ave learned: 9o2 t/e D6=SLOU0PU0 pac5age 2or5s 9o2 to use U0LL:IL( to direct output to operating s,stem Biles .bout t/e main Beatures oB U0LL=.IL

%op,rig/t @ &''"A Oracle) .ll rig/ts reserved)

Summar, 0/is lesson covers a small subset oB pac5ages provided 2it/ t/e Oracle database) 8ou /ave eCtensivel, used D6=SLOU0PU0 Bor debugging purposes and displa,ing procedurall, generated inBormation on t/e screen in SQLKPlus) In t/is lessonA ,ou s/ould /ave learned /o2 to use t/e po2er Beatures provided b, t/e database to create teCt Biles in t/e operating s,stem b, using U0LL:IL() 8ou also learned /o2 to send email 2it/ or 2it/out binar, or teCt attac/ments b, using t/e U0LL=.IL pac5age) <ote: :or more inBormation about all PL/SQL pac5ages and t,pesA reBer to PL/SQL Pac5ages and 0,pes 1eBerence)

c ra O l, - On

, em ad .c

ra c O

le In

l ae rn Uste

Oracle Database 11g: Develop PL/SQL Program Units + E &#

Practice +: Overvie2
0/is practice covers /o2 to use U0LL:IL( to generate a teCt report)

%op,rig/t @ &''"A Oracle) .ll rig/ts reserved)

Practice +: Overvie2 In t/is practiceA ,ou use U0LL:IL( to generate a teCt Bile report oB emplo,ees in eac/ department)

c ra O l, - On

, em ad .c

ra c O

le In

l ae rn Uste

Oracle Database 11g: Develop PL/SQL Program Units + E &"

l c ra O l, - On ra c O le In l ae rn Uste e

, em ad .c

Using D,namic SQL

%op,rig/t @ &''"A Oracle) .ll rig/ts reserved)

l c ra O l, - On ra c O le In l ae rn Uste e

, em ad .c

Ob3ectives
.Bter completing t/is lessonA ,ou s/ould be able to do t/e Bollo2ing: Describe t/e eCecution Blo2 oB SQL statements 6uild and eCecute SQL statements d,namicall, using <ative D,namic SQL H<DSI IdentiB, situations 2/en ,ou must use t/e D6=SLSQL pac5age instead oB <DS to build and eCecute SQL statements d,namicall,

%op,rig/t @ &''"A Oracle) .ll rig/ts reserved)

Lesson .im In t/is lessonA ,ou learn to construct and eCecute SQL statements d,namicall,Ut/at isA at run time using t/e <ative D,namic SQL statements in PL/SQL)

c ra O l, - On

, em ad .c

ra c O

le In

l ae rn Uste

Oracle Database 11g: Develop PL/SQL Program Units $ E &

Lesson .genda
Using <ative D,namic SQL H<DSI Using t/e D6=SLSQL pac5age

%op,rig/t @ &''"A Oracle) .ll rig/ts reserved)

l c ra O l, - On ra c O le In l ae rn Uste e

, em ad .c

Oracle Database 11g: Develop PL/SQL Program Units $ E *

(Cecution :lo2 oB SQL


.ll SQL statements go t/roug/ some or all oB t/e Bollo2ing stages:
M M M M Parse 6ind (Cecute :etc/

Some stages ma, not be relevant Bor all statements:


M 0/e Betc/ p/ase is applicable to Pueries) M :or embedded SQL statements suc/ as S(L(%0A D=LA =(1 (A %O==I0A S.V(POI<0A and 1OLL6.%?A t/e parse and bind p/ases are done at compile time) M :or d,namic SQL statementsA all p/ases are perBormed at run time)

%op,rig/t @ &''"A Oracle) .ll rig/ts reserved)

Steps to Process SQL Statements .ll SQL statements /ave to go t/roug/ various stages) 9o2everA some stages ma, not be relevant Bor all statements) 0/e Bollo2ing are t/e 5e, stages: Parse: (ver, SQL statement must be parsed) Parsing t/e statement includes c/ec5ing t/e statementFs s,ntaC and validating t/e statementA ensuring t/at all reBerences to ob3ects are correct and t/at t/e relevant privileges to t/ose ob3ects eCist) 6ind: .Bter parsingA t/e Oracle server ma, need values Brom or Bor an, bind variable in t/e statement) 0/e process oB obtaining t/ese values is called binding variables) 0/is stage ma, be s5ipped iB t/e statement does not contain bind variables) (Cecute: .t t/is pointA t/e Oracle server /as all necessar, inBormation and resourcesA and t/e statement is eCecuted) :or nonEPuer, statementsA t/is is t/e last p/ase) :etc/: In t/e Betc/ stageA 2/ic/ is applicable to PueriesA t/e ro2s are selected and ordered HiB rePuested b, t/e Puer,IA and eac/ successive Betc/ retrieves anot/er ro2 oB t/e resultA until t/e last ro2 /as been Betc/ed)

c ra O l, - On

, em ad .c

ra c O

le

l ae rn Uste

Oracle Database 11g: Develop PL/SQL Program Units $ E !

In

>or5ing 2it/ D,namic SQL


Use d,namic SQL to create a SQL statement 2/ose structure ma, c/ange during run time) D,namic SQL: Is constructed and stored as a c/aracter stringA string variableA or string eCpression 2it/in t/e application Is a SQL statement 2it/ var,ing column dataA or diBBerent conditions 2it/ or 2it/out place/olders Hbind variablesI (nables DDLA D%LA or sessionEcontrol statements to be 2ritten and eCecuted Brom PL/SQL Is eCecuted 2it/ <ative D,namic SQL statements or t/e D6=SLSQL pac5age

%op,rig/t @ &''"A Oracle) .ll rig/ts reserved)

D,namic SQL 0/e embedded SQL statements available in PL/SQL are limited to S(L(%0A I<S(10A UPD.0(A D(L(0(A =(1 (A %O==I0A and 1OLL6.%?A all oB 2/ic/ are parsed at compile timeUt/at isA t/e, /ave a BiCed structure) 8ou need to use d,namic SQL Bunctionalit, iB ,ou rePuire: 0/e structure oB a SQL statement to be altered at run time .ccess to data deBinition language HDDLI statements and ot/er SQL Bunctionalit, in PL/SQL 0o perBorm t/ese 5inds oB tas5s in PL/SQLA ,ou must construct SQL statements d,namicall, in c/aracter strings and eCecute t/em using eit/er oB t/e Bollo2ing: <ative D,namic SQL statements 2it/ (O(%U0( I==(DI.0( 0/e D6=SLSQL pac5age

c ra O l, - On

, em ad .c

ra c O

0/e process oB using SQL statements t/at are not embedded in ,our source program and are constructed in strings and eCecuted at run time is 5no2n as Xd,namic SQL)Y 0/e SQL statements are created d,namicall, at run time and can access and use PL/SQL variables) :or eCampleA ,ou create a procedure t/at uses d,namic SQL to operate on a table 2/ose name is not 5no2n until run timeA or eCecute a DDL statement Hsuc/ as %1(.0( 0.6L(IA a data control statement Hsuc/ as 1.<0IA or a session control statement Hsuc/ as .L0(1 S(SSIO<I)

le

l ae rn Uste

Oracle Database 11g: Develop PL/SQL Program Units $ E +

In

Using D,namic SQL


Use d,namic SQL 2/en t/e Bull teCt oB t/e d,namic SQL statement is un5no2n until run timeR t/ereBoreA its s,ntaC is c/ec5ed at run time rat/er t/an at compile time) Use d,namic SQL 2/en one oB t/e Bollo2ing items is un5no2n at precompile time:
M 0eCt oB t/e SQL statement suc/ as commandsA clausesA and so on M 0/e number and data t,pes oB /ost variables M 1eBerences to database ob3ects suc/ as tablesA columnsA indeCesA sePuencesA usernamesA and vie2s

Use d,namic SQL to ma5e ,our PL/SQL programs more general and BleCible)

%op,rig/t @ &''"A Oracle) .ll rig/ts reserved)

Using D,namic SQL In PL/SQLA ,ou need d,namic SQL to eCecute t/e Bollo2ing SQL statements 2/ere t/e Bull teCt is un5no2n at compile time suc/ as: . S(L(%0 statement t/at includes an identiBier t/at is un5no2n at compile time Hsuc/ as a table nameI . >9(1( clause in 2/ic/ t/e column name is un5no2n at compile time <ote

ra c O

:or additional inBormation about d,namic SQLA see t/e Bollo2ing resources: ProK%/%NN ProgrammerFs uide 11g 1elease & H11)&I documentation guide E Lesson 1*A Oracle D,namic SQLA covers t/e Bour available met/ods t/at ,ou can use to deBine d,namic SQL statements) It brieBl, describes t/e capabilities and limitations oB eac/ met/odA and t/en oBBers guidelines Bor c/oosing t/e rig/t met/od) Later sections in t/e same guide s/o2 ,ou /o2 to use t/e met/odsA and include eCample programs t/at ,ou can stud,) E Lesson 1+A Oracle D,namic SQL: =et/od !A contains ver, detailed inBormation about =et/od ! 2/en deBining d,namic SQL statements) Oracle PL/SQL Programming boo5 b, Steven :euerstein and 6ill Prib,l) Lesson 1$A D,namic SQL and D,namic PL/SQLA contains additional inBormation about d,namic SQL)

c ra O l, - On

, em ad .c

le

l ae rn Uste

Oracle Database 11g: Develop PL/SQL Program Units $ E $

In

<ative D,namic SQL H<DSI


Provides native support Bor d,namic SQL directl, in t/e PL/SQL language) Provides t/e abilit, to eCecute SQL statements 2/ose structure is un5no2n until eCecution time) IB t/e d,namic SQL statement is a S(L(%0 statement t/at returns multiple ro2sA <DS gives ,ou t/e Bollo2ing c/oices: M Use t/e (O(%U0( I==(DI.0( statement 2it/ t/e 6UL?
%OLL(%0 I<0O clause M Use t/e OP(<E:O1A :(0%9A and %LOS( statements

In Oracle Database 11gA <DS supports statements larger t/an *& ?6 b, accepting a %LO6 argument)

%op,rig/t @ &''"A Oracle) .ll rig/ts reserved)

<ative D,namic SQL <ative D,namic SQL provides t/e abilit, to d,namicall, eCecute SQL statements 2/ose structure is constructed at eCecution time) 0/e Bollo2ing statements /ave been added or eCtended in PL/SQL to support <ative D,namic SQL: (O(%U0( I==(DI.0(: Prepares a statementA eCecutes itA returns variablesA and t/en deallocates resources OP(<E:O1: Prepares and eCecutes a statement using a cursor variable :(0%9: 1etrieves t/e results oB an opened statement b, using t/e cursor variable %LOS(: %loses t/e cursor used b, t/e cursor variable and deallocates resources 8ou can use bind variables in t/e d,namic parameters in t/e (O(%U0( I==(DI.0( and OP(< statements) <ative D,namic SQL includes t/e Bollo2ing capabilities: DeBine a d,namic SQL statement) 9andle I<A I< OU0A and OU0 bind variables t/at are bound b, positionA not b, name)

c ra O l, - On

, em ad .c

ra c O

le In

l ae rn Uste

Oracle Database 11g: Develop PL/SQL Program Units $ E G

Using t/e (O(%U0( I==(DI.0( Statement


Use t/e (O(%U0( I==(DI.0( statement Bor <DS or PL/SQL anon,mous bloc5s:
(O(%U0( I==(DI.0( d,namicLstring VI<0O bdeBineLvariable VA deBineLvariableW ))) T recordcW VUSI< VI<TOU0TI< OU0W bindLargument VA VI<TOU0TI< OU0W bindLargumentW ))) WR

I<0O is used Bor singleEro2 Pueries and speciBies t/e variables or records into 2/ic/ column values are retrieved) USI< is used to /old all bind arguments) 0/e deBault parameter mode is I<)

%op,rig/t @ &''"A Oracle) .ll rig/ts reserved)

Using t/e (O(%U0( I==(DI.0( Statement 0/e (O(%U0( I==(DI.0( statement can be used to eCecute SQL statements or PL/SQL anon,mous bloc5s) 0/e s,ntactical elements include t/e Bollo2ing: d,namicLstring is a string eCpression t/at represents a d,namic SQL statement H2it/out terminatorI or a PL/SQL bloc5 H2it/ terminatorI) deBineLvariable is a PL/SQL variable t/at stores t/e selected column value) record is a userEdeBined or Q1O>08P( record t/at stores a selected ro2) bindLargument is an eCpression 2/ose value is passed to t/e d,namic SQL statement or PL/SQL bloc5) 0/e I<0O clause speciBies t/e variables or record into 2/ic/ column values are retrieved) It is used onl, Bor singleEro2 Pueries) :or eac/ value retrieved b, t/e Puer,A t/ere must be a correspondingA t,peEcompatible variable or Bield in t/e I<0O clause) 0/e USI< clause /olds all bind arguments) 0/e deBault parameter mode is I<) 8ou can use numericA c/aracterA and string literals as bind argumentsA but ,ou cannot use 6oolean literals H01U(A :.LS(A and <ULLI) <ote: Use OP(<E:O1A :(0%9A and %LOS( Bor a multiro2 Puer,) 0/e s,ntaC s/o2n in t/e slide is not complete because support eCists Bor bul5Eprocessing operations H2/ic/ is a topic t/at is not covered in t/is courseI)

c ra O l, - On

, em ad .c

ra c O

le

l ae rn Uste

Oracle Database 11g: Develop PL/SQL Program Units $ E #

In

.vailable =et/ods Bor Using <DS

=et/od d =et/od 1 =et/od & =et/od * =et/od !

SQL Statement 0,pe


<onEPuer, 2it/out /ost variables

<DS SQL Statements Used


(O(%U0( I==(DI.0( 2it/out t/e USI< and I<0O clauses (O(%U0( I==(DI.0( 2it/ a USI< clause (O(%U0( I==(DI.0( 2it/ t/e USI< and I<0O clauses Use t/e D6=SLSQL pac5age

<onEPuer, 2it/ 5no2n number oB input /ost variables Quer, 2it/ 5no2n number oB selectElist items and input /ost variables Quer, 2it/ un5no2n number oB selectE list items or input /ost variables

%op,rig/t @ &''"A Oracle) .ll rig/ts reserved)

.vailable =et/ods Bor Using <DS 0/e Bour available met/ods Bor <DS t/at are listed in t/e slide are increasingl, general) 0/at isA =et/od & encompasses =et/od 1A =et/od * encompasses =et/ods 1 and &A and =et/od ! encompasses =et/ods 1A &A and *) 9o2everA eac/ met/od is most useBul Bor /andling a certain 5ind oB SQL statementA as Bollo2s: =et/od 1: 0/is met/od lets ,our program accept or build a d,namic SQL statementA and t/en immediatel, eCecute it using t/e (O(%U0( I==(DI.0( command) 0/e SQL statement must not be a Puer, HS(L(%0 statementI and must not contain an, place/olders Bor input /ost variables) :or eCampleA t/e Bollo2ing /ost strings PualiB,: D(L(0( :1O= (=PLO8((S >9(1( D(P0<O Z &' 1.<0 S(L(%0 O< (=PLO8((S 0O scott

c ra O l, - On

, em ad .c

ra c O

>it/ =et/od 1A t/e SQL statement is parsed ever, time it is eCecuted) <ote (Camples oB nonEPueries include data deBinition language HDDLsI statementsA UPD.0(sA I<S(10sA or D(L(0(s) 0/e term selectElist item includes column names and eCpressions suc/ as S.L K 1)1' and =.OHS.LI)

le

l ae rn Uste

Oracle Database 11g: Develop PL/SQL Program Units $ E "

In

.vailable =et/ods Bor Using <DS HcontinuedI =et/od &: 0/is met/od lets ,our program accept or build a d,namic SQL statementA and t/en process it using t/e P1(P.1( and (O(%U0( commands) 0/e SQL statement must not be a Puer,) 0/e number oB place/olders Bor input /ost variables and t/e data t,pes oB t/e input /ost variables must be 5no2n at precompile time) :or eCampleA t/e Bollo2ing /ost strings Ball into t/is categor,: I<S(10 I<0O (=PLO8((S H:I1S0L<.=(A L.S0L<.=(A ;O6LIDI V.LU(S H:empLBirstLnameA :empLlastLnameA:3obLidI D(L(0( :1O= (=PLO8((S >9(1( (=PLO8((LID Z :empLnumber

>it/ =et/od &A t/e SQL statement is parsed 3ust onceA but can be eCecuted man, times 2it/ diBBerent values Bor t/e /ost variables) SQL data deBinition statements suc/ as %1(.0( and 1.<0 are eCecuted 2/en t/e, are prepared) =et/od *: 0/is met/od lets ,our program accept or build a d,namic Puer,A and t/en process it using t/e P1(P.1( command 2it/ t/e D(%L.1(A OP(<A :(0%9A and %LOS( cursor commands) 0/e number oB selectElist itemsA t/e number oB place/olders Bor input /ost variablesA and t/e data t,pes oB t/e input /ost variables must be 5no2n at precompile time) :or eCampleA t/e Bollo2ing /ost strings PualiB,: S(L(%0 D(P.10=(<0LIDA =I<HS.L.18IA =.OHS.L.18I :1O= (=PLO8((S 1OUP 68 D(P.10=(<0LID S(L(%0 L.S0L<.=(A (=PLO8((LID :1O= (=PLO8((S >9(1( D(P.10=(<0LID Z :deptLnumber

=et/od !: 0/is met/od lets ,our program accept or build a d,namic SQL statementA and t/en process it using descriptors) . descriptor is an area oB memor, used b, ,our program and Oracle to /old a complete description oB t/e variables in a d,namic SQL statement) 0/e number oB selectElist itemsA t/e number oB place/olders Bor input /ost variablesA and t/e data t,pes oB t/e input /ost variables can be un5no2n until run time) :or eCampleA t/e Bollo2ing /ost strings Ball into t/is categor,: I<S(10 I<0O (=PLO8((S H^un5no2n\I V.LU(S H^un5no2n\I S(L(%0 ^un5no2n\ :1O= (=PLO8((S >9(1( D(P.10=(<0LID Z &'

ra c O

=et/od ! is rePuired Bor d,namic SQL statements t/at contain an un5no2n number oB selectElist items or input /ost variables) >it/ t/is met/odA ,ou use t/e D6=SLSQL pac5ageA 2/ic/ is covered later in t/is lesson) Situations t/at rePuire using =et/od ! are rare) <ote :or additional inBormation about t/e Bour d,namic SQL met/odsA see t/e Bollo2ing lessons in t/e ProK%/%NN ProgrammerFs uide 11g 1elease & H11)&I documentation guide) Lesson 1*A Oracle D,namic SQL Lesson 1+A Oracle D,namic SQL: =et/od !

c ra O l, - On

, em ad .c

le

l ae rn Uste

Oracle Database 11g: Develop PL/SQL Program Units $ E 1'

In

D,namic SQL 2it/ a DDL Statement: (Camples

EE %reate a table using d,namic SQL %1(.0( O1 1(PL.%( P1O%(DU1( createLtableH pLtableLname V.1%9.1&A pLcolLspecs V.1%9.1&I IS 6( I< (O(%U0( I==(DI.0( S%1(.0( 0.6L( S TT pLtableLname TT S HS TT pLcolLspecs TT SISR (<DR /

EE %all t/e procedure 6( I< createLtableHS(=PLO8((L<.=(SSA Sid <U=6(1H!I P1I=.18 ?(8A name V.1%9.1&H!'ISIR (<DR /

%op,rig/t @ &''"A Oracle) .ll rig/ts reserved)

D,namic SQL 2it/ a DDL Statement 0/e code eCamples s/o2 t/e creation oB a createLtable procedure t/at accepts t/e table name and column deBinitions HspeciBicationsI as parameters) 0/e procedure call s/o2s t/e creation oB a table called (=PLO8((L<.=(S 2it/ t2o columns: .n ID column 2it/ a <U=6(1 data t,pe used as a primar, 5e, . name column oB up to !' c/aracters Bor t/e emplo,ee name .n, DDL statement can be eCecuted b, using t/e s,ntaC s/o2n in t/e slideA 2/et/er t/e statement is d,namicall, constructed or speciBied as a literal string) 8ou can create and eCecute a statement t/at is stored in a PL/SQL string variableA as in t/e Bollo2ing eCample:
%1(.0( O1 1(PL.%( P1O%(DU1( addLcolHpLtableLname V.1%9.1&A pLcolLspecV.1%9.1&I IS vLstmt V.1%9.1&H1''I :Z S.L0(1 0.6L( S TT pLtableLname TT S .DD STT pLcolLspecR 6( I< (O(%U0( I==(DI.0( vLstmtR (<DR /

c ra O l, - On

, em ad .c

ra c O

le

0o add a ne2 column to a tableA enter t/e Bollo2ing:

(O(%U0( addLcolHSemplo,eeLnamesSA Ssalar, numberH#A&ISI

l ae rn Uste

Oracle Database 11g: Develop PL/SQL Program Units $ E 11

In

D,namic SQL 2it/ D=L Statements


EE Delete ro2s Brom an, table: %1(.0( :U<%0IO< delLro2sHpLtableLname V.1%9.1&I 1(0U1< <U=6(1 IS 6( I< (O(%U0( I==(DI.0( SD(L(0( :1O= STT pLtableLnameR 1(0U1< SQLQ1O>%OU<0R (<DR / 6( I< D6=SLOU0PU0)PU0LLI<(H delLro2sHS(=PLO8((L<.=(SSITT S ro2s deleted)SIR (<DR /

EE Insert a ro2 into a table 2it/ t2o columns: %1(.0( P1O%(DU1( addLro2HpLtableLname V.1%9.1&A pLid <U=6(1A pLname V.1%9.1&I IS 6( I< (O(%U0( I==(DI.0( SI<S(10 I<0O STT pLtableLname TT S V.LU(S H:1A :&IS USI< pLidA pLnameR (<DR

%op,rig/t @ &''"A Oracle) .ll rig/ts reserved)

D,namic SQL 2it/ D=L Statements 0/e Birst code eCample in t/e slide deBines a d,namic SQL statement using =et/od 1Ut/at isA nonPuer, 2it/out /ost variables) 0/e eCamples in t/e slide demonstrate t/e Bollo2ing: 0/e delLro2s Bunction deletes ro2s Brom a speciBied table and returns t/e number oB ro2s deleted b, using t/e implicit SQL cursor Q1O>%OU<0 attribute) (Cecuting t/e Bunction is s/o2n belo2 t/e eCample Bor creating a Bunction) 0/e addLro2 procedure s/o2s /o2 to provide input values to a d,namic SQL statement 2it/ t/e USI< clause) 0/e bind variable names :1 and :& are not importantR /o2everA t/e order oB t/e parameter names HpLid and pLnameI in t/e USI< clause is associated 2it/ t/e bind variables b, positionA in t/e order oB t/eir respective appearance) 0/ereBoreA t/e PL/SQL parameter pLid is assigned to t/e :1 place/olderA and t/e pLname parameter is assigned to t/e :& place/older) Place/older or bind variable names can be alp/anumeric but must be preceded 2it/ a colon) <ote: 0/e (O(%U0( I==(DI.0( statement prepares HparsesI and immediatel, eCecutes t/e d,namic SQL statement) D,namic SQL statements are al2a,s parsed) .lsoA note t/at a %O==I0 operation is not perBormed in eit/er oB t/e eCamples) 0/ereBoreA t/e operations can be undone 2it/ a 1OLL6.%? statement)

c ra O l, - On

, em ad .c

ra c O

le

l ae rn Uste

Oracle Database 11g: Develop PL/SQL Program Units $ E 1&

In

D,namic SQL 2it/ a SingleE1o2 Quer,: (Cample


%1(.0( :U<%0IO< getLempH pLempLid <U=6(1 I 1(0U1< emplo,eesQ1O>08P( IS 1vLstmt V.1%9.1&H&''IR vLemprec emplo,eesQ1O>08P(R 6( I< vLstmt :Z SS(L(%0 K :1O= emplo,ees S TT S>9(1( emplo,eeLid Z :pLempLidSR (O(%U0( I==(DI.0( vLstmt I<0O vLemprec USI< pLempLid R 1(0U1< vLemprecR (<DR &/ D(%L.1( vLemprec emplo,eesQ1O>08P( :Z getLempH1''IR 6( I< D6=SLOU0PU0)PU0LLI<(HS(mp: STT vLemprec)lastLnameIR (<DR /

%op,rig/t @ &''"A Oracle) .ll rig/ts reserved)

D,namic SQL 2it/ a SingleE1o2 Quer, 0/e code eCample in t/e slide is an eCample oB deBining a d,namic SQL statement using =et/od * 2it/ a single ro2 PueriedUt/at isA Puer, 2it/ a 5no2n number oB selectElist items and input /ost variables) 0/e singleEro2 Puer, eCample demonstrates t/e getLemp Bunction t/at retrieves an (=PLO8((S record into a variable speciBied in t/e I<0O clause) It also s/o2s /o2 to provide input values Bor t/e >9(1( clause) 0/e anon,mous bloc5 is used to eCecute t/e getLemp Bunction and return t/e result into a local (=PLO8((S record variable) 0/e eCample could be en/anced to provide alternative >9(1( clauses depending on input parameter valuesA ma5ing it more suitable Bor d,namic SQL processing) <ote: :or an eCample oB XD,namic SQL 2it/ a =ultiro2 Quer,: (CampleY using 1(: %U1SO1SA see t/e demoL'$L1*La in t/e //ome/oracle/labs/plpu/demo Bolder) :or an eCample on using 1(: %U1SO1SA see t/e demoL'$L1*Lb in t/e //ome/oracle/labs/plpu/demo Bolder) 1(: %U1SO1S are covered in t/e Oracle Database 11g: .dvanced PL/SQL *Eda, class)

c ra O l, - On

, em ad .c

ra c O

le

l ae rn Uste

Oracle Database 11g: Develop PL/SQL Program Units $ E 1*

In

(Cecuting a PL/SQL .non,mous 6loc5 D,namicall,


%1(.0( :U<%0IO< annualLsalH pLempLid <U=6(1I 1(0U1< <U=6(1 IS vLplsPl varc/ar&H&''I :Z SD(%L.1( STT S recLemp emplo,eesQ1O>08P(R STT S6( I< STT S recLemp :Z getLempH:empidIR S TT & S :res :Z recLemp)salar, K 1&R S TT S(<DRSR1 vLresult <U=6(1R 6( I< (O(%U0( I==(DI.0( vLplsPl USI< I< pLempLidA OU0 vLresultR & 1(0U1< vLresultR (<DR / (O(%U0( D6=SLOU0PU0)PU0LLI<(HannualLsalH1''II

%op,rig/t @ &''"A Oracle) .ll rig/ts reserved)

D,namicall, (Cecuting a PL/SQL 6loc5 0/e annualLsal Bunction d,namicall, constructs an anon,mous PL/SQL bloc5) 0/e PL/SQL bloc5 contains bind variables Bor: 0/e input oB t/e emplo,ee ID using t/e :empid place/older 0/e output result computing t/e annual emplo,eesF salar, using t/e place/older called :res <ote: 0/is eCample demonstrates /o2 to use t/e OU0 result s,ntaC Hin t/e USI< clause oB t/e (O(%U0( I==(DI.0( statementI to obtain t/e result calculated b, t/e PL/SQL bloc5) 0/e procedure output variables and Bunction return values can be obtained in a similar 2a, Brom a d,namicall, eCecuted anon,mous PL/SQL bloc5)

0/e output oB t/e slide eCample is as Bollo2s:

c ra O l, - On

, em ad .c

ra c O

le In

l ae rn Uste

Oracle Database 11g: Develop PL/SQL Program Units $ E 1!

Using <ative D,namic SQL to %ompile PL/SQL %ode


%ompile PL/SQL code 2it/ t/e .L0(1 statement: .L0(1 P1O%(DU1( name %O=PIL( .L0(1 :U<%0IO< name %O=PIL( .L0(1 P.%?. ( name %O=PIL( SP(%I:I%.0IO< .L0(1 P.%?. ( name %O=PIL( 6OD8
%1(.0( P1O%(DU1( compileLplsPlHpLname V.1%9.1&A pLplsPlLt,pe V.1%9.1&A pLoptions V.1%9.1& :Z <ULLI IS vLstmt varc/ar&H&''I :Z S.L0(1 STT pLplsPlLt,pe TT S STT pLname TT S %O=PIL(SR 6( I< I: pLoptions IS <O0 <ULL 09(< vLstmt :Z vLstmt TT S S TT pLoptionsR (<D I:R (O(%U0( I==(DI.0( vLstmtR (<DR /

%op,rig/t @ &''"A Oracle) .ll rig/ts reserved)

Using <ative D,namic SQL to %ompile PL/SQL %ode 0/e compileLplsPl procedure in t/e eCample can be used to compile diBBerent PL/SQL code using t/e .L0(1 DDL statement) :our basic Borms oB t/e .L0(1 statement are s/o2n to compile: . procedure . Bunction . pac5age speciBication . pac5age bod, <ote: IB ,ou leave out t/e 5e,2ord SP(%I:I%.0IO< or 6OD8 2it/ t/e .L0(1 P.%?. ( statementA t/en t/e speciBication and bod, are bot/ compiled)

9ere are eCamples oB calling t/e procedure in t/e slide Bor eac/ oB t/e Bour casesA respectivel,:
(O(% (O(% (O(% (O(%

c ra O l, - On

, em ad .c

ra c O

le

compileLplsPl compileLplsPl compileLplsPl compileLplsPl

9ere is an eCample oB compiling 2it/ debug enabled Bor t/e getLemp Bunction:
(O(% compileLplsPl HSgetLempSA SBunctionSA SdebugSI

l ae rn Uste

HSlistLemplo,eesSA SprocedureSI HSgetLempSA SBunctionSI HSm,pac5SA Spac5ageSA SspeciBicationSI HSm,pac5SA Spac5ageSA Sbod,SI

Oracle Database 11g: Develop PL/SQL Program Units $ E 1+

In

Lesson .genda
Using <ative D,namic SQL H<DSI Using t/e D6=SLSQL pac5age

%op,rig/t @ &''"A Oracle) .ll rig/ts reserved)

l c ra O l, - On ra c O le In l ae rn Uste e

, em ad .c

Oracle Database 11g: Develop PL/SQL Program Units $ E 1$

Using t/e D6=SLSQL Pac5age


0/e D6=SLSQL pac5age is used to 2rite d,namic SQL in stored procedures and to parse DDL statements) 8ou must use t/e D6=SLSQL pac5age to eCecute a d,namic SQL statement t/at /as an un5no2n number oB input or output variablesA also 5no2n as =et/od !) In most casesA <DS is easier to use and perBorms better t/an D6=SLSQL eCcept 2/en dealing 2it/ =et/od !) :or eCampleA ,ou must use t/e D6=SLSQL pac5age in t/e Bollo2ing situations:

M 8ou do not 5no2 t/e S(L(%0 list at compile time M 8ou do not 5no2 /o2 man, columns a S(L(%0 statement 2ill returnA or 2/at t/eir data t,pes 2ill be

%op,rig/t @ &''"A Oracle) .ll rig/ts reserved)

Using t/e D6=SLSQL Pac5age Using D6=SLSQLA ,ou can 2rite stored procedures and anon,mous PL/SQL bloc5s t/at use d,namic SQLA suc/ as eCecuting DDL statements in PL/SQLUBor eCampleA eCecuting a D1OP 0.6L( statement) 0/e operations provided b, t/is pac5age are perBormed under t/e current userA not under t/e pac5age o2ner S8S)

ra c O

=et/od !: =et/od ! reBers to situations 2/ereA in a d,namic SQL statementA t/e number oB columns selected Bor a Puer, or t/e number oB bind variables set is not 5no2n until run time) In t/is caseA ,ou s/ould use t/e D6=SLSQL pac5age) >/en generating d,namic SQLA ,ou can eit/er use t/e D6=SLSQL supplied pac5age 2/en dealing 2it/ =et/od ! situationsA or ,ou can use native d,namic SQL) 6eBore Oracle Database 11gA eac/ oB t/ese met/ods /ad Bunctional limitations) In Oracle Database 11gA Bunctionalit, is added to bot/ met/ods to ma5e t/em more complete) 0/e Beatures Bor eCecuting d,namic SQL Brom PL/SQL /ad some restrictions in Oracle Database 1'g) D6=SLSQL 2as needed Bor =et/od ! scenarios but it could not /andle t/e Bull range oB data t,pes and its cursor representation 2as not usable b, a client to t/e database) <ative d,namic SQL 2as more convenient Bor nonM=et/od ! scenariosA but it did not support statements bigger t/an *& ?6) Oracle Database 11g removes t/ese and ot/er restrictions to ma5e t/e support oB d,namic SQL Brom PL/SQL Bunctionall, complete)

c ra O l, - On

, em ad .c

le

l ae rn Uste

Oracle Database 11g: Develop PL/SQL Program Units $ E 1G

In

Using t/e D6=SLSQL Pac5age Subprograms


(Camples oB t/e pac5age procedures and Bunctions: OP(<L%U1SO1 P.1S( 6I<DLV.1I.6L( (O(%U0( :(0%9L1O>S %LOS(L%U1SO1

%op,rig/t @ &''"A Oracle) .ll rig/ts reserved)

Using t/e D6=SLSQL Pac5age Subprograms 0/e D6=SLSQL pac5age provides t/e Bollo2ing subprograms to eCecute d,namic SQL: OP(<L%U1SO1 to open a ne2 cursor and return a cursor ID number P.1S( to parse t/e SQL statement) (ver, SQL statement must be parsed b, calling t/e P.1S( procedures) Parsing t/e statement c/ec5s t/e statementFs s,ntaC and associates it 2it/ t/e cursor in ,our program) 8ou can parse an, D=L or DDL statement) DDL statements are immediatel, eCecuted 2/en parsed) 6I<DLV.1I.6L( to bind a given value to a bind variable identiBied b, its name in t/e statement being parsed) 0/is is not needed iB t/e statement does not /ave bind variables) (O(%U0( to eCecute t/e SQL statement and return t/e number oB ro2s processed :(0%9L1O>S to retrieve t/e neCt ro2 Bor a Puer, Huse in a loop Bor multiple ro2sI %LOS(L%U1SO1 to close t/e speciBied cursor <ote: Using t/e D6=SLSQL pac5age to eCecute DDL statements can result in a deadloc5) :or eCampleA t/e most li5el, reason is t/at t/e pac5age is being used to drop a procedure t/at ,ou are still using)

c ra O l, - On

, em ad .c

ra c O

le

l ae rn Uste

Oracle Database 11g: Develop PL/SQL Program Units $ E 1#

In

Using t/e D6=SLSQL Pac5age Subprograms HcontinuedI 0/e P.1S( Procedure Parameters 0/e L.< U. (L:L. parameter oB t/e P.1S( procedure determines /o2 Oracle /andles t/e SQL statementUt/at isA using be/avior associated 2it/ a speciBic Oracle database version) Using <.0IV( Hor 1I Bor t/is parameter speciBies using t/e normal be/avior associated 2it/ t/e database to 2/ic/ t/e program is connected) IB t/e L.< U. (L:L. parameter is set to V$ Hor 'IA t/at speciBies version $ be/avior) IB t/e L.< U. (L:L. parameter is set to VG Hor &IA t/at speciBies Oracle database version G be/avior) <ote: :or additional inBormationA see t/e Oracle Database PL/SQL Pac5ages and 0,pes 1eBerence 11g 1elease & H11)&I guide)

l c ra O l, - On ra c O le In l ae rn Uste e

, em ad .c

Oracle Database 11g: Develop PL/SQL Program Units $ E 1"

Using D6=SLSQL 2it/ a D=L Statement: Deleting 1o2s


%1(.0( O1 1(PL.%( :U<%0IO< deleteLallLro2s HpLtableLname V.1%9.1&I 1(0U1< <U=6(1 IS vLcurLidI<0( (1R vLro2sLdel<U=6(1R 6( I< vLcurLid :Z D6=SLSQL)OP(<L%U1SO1R D6=SLSQL)P.1S(HvLcurLidA SD(L(0( :1O= STT pLtableLnameA D6=SLSQL)<.0IV(IR vLro2sLdel :Z D6=SLSQL)(O(%U0( HvLcurLidIR D6=SLSQL)%LOS(L%U1SO1HvLcurLidIR 1(0U1< vLro2sLdelR (<DR / %1(.0( 0.6L( tempLemp .S S(L(%0 K :1O= emplo,eesR 6( I< D6=SLOU0PU0)PU0LLI<(HS1o2s Deleted: S TT deleteLallLro2sHStempLempSIIR (<DR /

%op,rig/t @ &''"A Oracle) .ll rig/ts reserved)

Using D6=SLSQL 2it/ a D=L Statement In t/e slideA t/e table name is passed into t/e deleteLallLro2s Bunction) 0/e Bunction uses d,namic SQL to delete ro2s Brom t/e speciBied tableA and returns a count representing t/e number oB ro2s t/at are deleted aBter successBul eCecution oB t/e statement) 0o process a D=L statement d,namicall,A perBorm t/e Bollo2ing steps: 1) Use OP(<L%U1SO1 to establis/ an area in memor, to process a SQL statement) &) Use P.1S( to establis/ t/e validit, oB t/e SQL statement) *) Use t/e (O(%U0( Bunction to run t/e SQL statement) 0/is Bunction returns t/e number oB ro2s processed) !) Use %LOS(L%U1SO1 to close t/e cursor)

ra c O

0/e steps to eCecute a DDL statement are similarR but step * is optional because a DDL statement is immediatel, eCecuted 2/en t/e P.1S( is successBull, doneUt/at isA t/e statement s,ntaC and semantics are correct) IB ,ou use t/e (O(%U0( Bunction 2it/ a DDL statementA t/en it does not do an,t/ing and returns a value oB ' Bor t/e number oB ro2s processed because DDL statements do not process ro2s)

c ra O l, - On

, em ad .c

le

l ae rn Uste

Oracle Database 11g: Develop PL/SQL Program Units $ E &'

In

Using D6=SLSQL 2it/ a Parameteri4ed D=L Statement


%1(.0( P1O%(DU1( insertLro2 HpLtableLname V.1%9.1&A pLid V.1%9.1&A pLname V.1%9.1&A pLregion <U=6(1I IS vLcurLidI<0( (1R vLstmtV.1%9.1&H&''IR vLro2sLadded <U=6(1R 6( I< vLstmt :Z SI<S(10 I<0O STT pLtableLname TT S V.LU(S H:cidA :cnameA :ridISR vLcurLid :Z D6=SLSQL)OP(<L%U1SO1R D6=SLSQL)P.1S(HvLcurLidA vLstmtA D6=SLSQL)<.0IV(IR D6=SLSQL)6I<DLV.1I.6L(HvLcurLidA S:cidSA pLidIR D6=SLSQL)6I<DLV.1I.6L(HvLcurLidA S:cnameSA pLnameIR D6=SLSQL)6I<DLV.1I.6L(HvLcurLidA S:ridSA pLregionIR vLro2sLadded :Z D6=SLSQL)(O(%U0(HvLcurLidIR D6=SLSQL)%LOS(L%U1SO1HvLcurLidIR D6=SLOU0PU0)PU0LLI<(HvLro2sLaddedTTS ro2 addedSIR (<DR /

%op,rig/t @ &''"A Oracle) .ll rig/ts reserved)

Using D6=SLSQL 2it/ a Parameteri4ed D=L Statement

l e

0/e eCample in t/e slide perBorms t/e D=L operation to insert a ro2 into a speciBied table) 0/e eCample demonstrates t/e eCtra step rePuired to associate values to bind variables t/at eCist in t/e SQL statement) :or eCampleA a call to t/e procedure s/o2n in t/e slide is:
(O(%U0( insertLro2HScountriesSA SL6SA SLebanonSA !I

ra c O

.Bter t/e statement is parsedA ,ou must call t/e D6=SLSQL)6I<DLV.1I.6L( procedure to assign values Bor eac/ bind variable t/at eCists in t/e statement) 0/e binding oB values must be done beBore eCecuting t/e code) 0o process a S(L(%0 statement d,namicall,A perBorm t/e Bollo2ing steps aBter opening and beBore closing t/e cursor: 1) (Cecute D6=SLSQL)D(:I<(L%OLU=< Bor eac/ column selected) &) (Cecute D6=SLSQL)6I<DLV.1I.6L( Bor eac/ bind variable in t/e Puer,) *) :or eac/ ro2A perBorm t/e Bollo2ing steps: a) (Cecute D6=SLSQL):(0%9L1O>S to retrieve a ro2 and return t/e number oB ro2s Betc/ed) Stop additional processing 2/en a 4ero value is returned) b) (Cecute D6=SLSQL)%OLU=<LV.LU( to retrieve eac/ selected column value into eac/ PL/SQL variable Bor processing)

c ra O l, - On

, em ad .c

le

.lt/oug/ t/is coding process is not compleCA it is more time consuming to 2rite and is prone to error compared 2it/ using t/e <ative D,namic SQL approac/)

l ae rn Uste

Oracle Database 11g: Develop PL/SQL Program Units $ E &1

In

Qui4
0/e Bull teCt oB t/e d,namic SQL statement mig/t be un5no2n until run timeR t/ereBoreA its s,ntaC is c/ec5ed at run time rat/er t/an at compile time) 1) 0rue &) :alse

%op,rig/t @ &''"A Oracle) .ll rig/ts reserved)

.ns2er: 1

l c ra O l, - On e

, em ad .c

ra c O

le In

l ae rn Uste

Oracle Database 11g: Develop PL/SQL Program Units $ E &&

Summar,
In t/is lessonA ,ou s/ould /ave learned /o2 to: Describe t/e eCecution Blo2 oB SQL statements 6uild and eCecute SQL statements d,namicall, using <ative D,namic SQL H<DSI IdentiB, situations 2/en ,ou must use t/e D6=SLSQL pac5age instead oB <DS to build and eCecute SQL statements d,namicall,

%op,rig/t @ &''"A Oracle) .ll rig/ts reserved)

Summar, In t/is lessonA ,ou discovered /o2 to d,namicall, create an, SQL statement and eCecute it using t/e <ative D,namic SQL statements) D,namicall, eCecuting SQL and PL/SQL code eCtends t/e capabilities oB PL/SQL be,ond Puer, and transactional operations) :or earlier releases oB t/e databaseA ,ou could ac/ieve similar results 2it/ t/e D6=SLSQL pac5age)

c ra O l, - On

, em ad .c

ra c O

le In

l ae rn Uste

Oracle Database 11g: Develop PL/SQL Program Units $ E &*

Practice $ Overvie2: Using <ative D,namic SQL


0/is practice covers t/e Bollo2ing topics: %reating a pac5age t/at uses <ative D,namic SQL to create or drop a table and to populateA modiB,A and delete ro2s Brom a table %reating a pac5age t/at compiles t/e PL/SQL code in ,our sc/ema

%op,rig/t @ &''"A Oracle) .ll rig/ts reserved)

Practice $: Overvie2 In t/is practiceA ,ou 2rite code to perBorm t/e Bollo2ing tas5s: %reate a pac5age t/at uses <ative D,namic SQL to create or drop a tableA and to populateA modiB,A and delete ro2s Brom t/e table) %reate a pac5age t/at compiles t/e PL/SQL code in ,our sc/emaA eit/er all t/e PL/SQL code or onl, code t/at /as an I<V.LID status in t/e US(1LO6;(%0S table)

c ra O l, - On

, em ad .c

ra c O

le In

l ae rn Uste

Oracle Database 11g: Develop PL/SQL Program Units $ E &!

Design %onsiderations Bor PL/SQL %ode

%op,rig/t @ &''"A Oracle) .ll rig/ts reserved)

l c ra O l, - On ra c O le In l ae rn Uste e

, em ad .c

Ob3ectives
.Bter completing t/is lessonA ,ou s/ould be able to do t/e Bollo2ing: %reate standard constants and eCceptions >rite and call local subprograms %ontrol t/e runEtime privileges oB a subprogram PerBorm autonomous transactions Pass parameters b, reBerence using a <O%OP8 /int Use t/e P.1.LL(L (<.6L( /int Bor optimi4ation

Use t/e crossEsession PL/SQL Bunction result cac/e Use t/e D(0(1=I<IS0I% clause 2it/ Bunctions Use t/e 1(0U1<I< clause and bul5 binding 2it/ D=L

%op,rig/t @ &''"A Oracle) .ll rig/ts reserved)

Lesson .im In t/is lessonA ,ou learn to use pac5age speciBications to standardi4e names Bor constant values and eCceptions) 8ou learn /o2 to create subprograms in t/e Declaration section oB an, PL/SQL bloc5 Bor using locall, in t/e bloc5) 0/e .U09ID compiler directive is discussed to s/o2 /o2 ,ou can manage runEtime privileges oB t/e PL/SQL codeA and create independent transactions b, using t/e .U0O<O=OUS 01.<S.%0IO< directive Bor subprograms) 0/is lesson also covers some perBormance considerations t/at can be applied to PL/SQL applicationsA suc/ as bul5 binding operations 2it/ a single SQL statementA t/e 1(0U1<I< clauseA and t/e <O%OP8 and P.1.LL(L (<.6L( /ints)

c ra O l, - On

, em ad .c

ra c O

le In

l ae rn Uste

Oracle Database 11g: Develop PL/SQL Program Units G E &

Lesson .genda
Standardi4ing constants and eCceptionsA using local subprogramsA controlling t/e runEtime privileges oB a subprogramA and perBorming autonomous transactions Using t/e <O%OP8 and t/e P.1.LL(L (<.6L( /intsA t/e crossEsession PL/SQL Bunction result cac/eA and t/e D(0(1=I<IS0I% clause Using t/e 1(0U1<I< clause and bul5 binding 2it/ D=L

%op,rig/t @ &''"A Oracle) .ll rig/ts reserved)

l c ra O l, - On ra c O le In l ae rn Uste e

, em ad .c

Oracle Database 11g: Develop PL/SQL Program Units G E *

Standardi4ing %onstants and (Cceptions


%onstants and eCceptions are t,picall, implemented using a bodiless pac5age Ht/at isA a pac5age speciBicationI) Standardi4ing /elps to:
M M M M Develop programs t/at are consistent Promote a /ig/er degree oB code reuse (ase code maintenance Implement compan, standards across entire applications

Start 2it/ standardi4ation oB:


M (Cception names M %onstant deBinitions

%op,rig/t @ &''"A Oracle) .ll rig/ts reserved)

Standardi4ing %onstants and (Cceptions >/en several developers are 2riting t/eir o2n eCception /andlers in an applicationA t/ere could be inconsistencies in t/e /andling oB error situations) Unless certain standards are ad/ered toA t/e situation can become conBusing because oB t/e diBBerent approac/es Bollo2ed in /andling t/e same error or because oB t/e displa, oB conBlicting error messages t/at conBuse users) 0o overcome t/eseA ,ou can: Implement compan, standards t/at use a consistent approac/ to error /andling across t/e entire application %reate predeBinedA generic eCception /andlers t/at produce consistenc, in t/e application >rite and call programs t/at produce consistent error messages .ll good programming environments promote naming and coding standards) In PL/SQLA a good place to start implementing naming and coding standards is 2it/ commonl, used constants and eCceptions t/at occur in t/e application domain) 0/e PL/SQL pac5age speciBication construct is an eCcellent component to support standardi4ation because all identiBiers declared in t/e pac5age speciBication are public) 0/e, are visible to t/e subprograms t/at are developed b, t/e o2ner oB t/e pac5age and all code 2it/ (O(%U0( rig/ts to t/e pac5age speciBication)

c ra O l, - On

, em ad .c

ra c O

le

l ae rn Uste

Oracle Database 11g: Develop PL/SQL Program Units G E !

In

Standardi4ing (Cceptions
%reate a standardi4ed errorE/andling pac5age t/at includes all named and programmerEdeBined eCceptions to be used in t/e application)
%1(.0( O1 1(PL.%( P.%?. ( errorLp5g IS eLB5Lerr (O%(P0IO<R eLsePLnbrLerr (O%(P0IO<R P1. =. (O%(P0IO<LI<I0 HeLB5LerrA E&&"&IR P1. =. (O%(P0IO<LI<I0 HeLsePLnbrLerrA E&&GGIR ))) (<D errorLp5gR /

%op,rig/t @ &''"A Oracle) .ll rig/ts reserved)

Standardi4ing (Cceptions In t/e eCample in t/e slideA t/e errorLp5g pac5age is a standardi4ed eCception pac5age) It declares a set oB programmerEdeBined eCception identiBiers) 6ecause man, oB t/e Oracle database predeBined eCceptions do not /ave identiB,ing namesA t/e eCample pac5age s/o2n in t/e slide uses t/e P1. =. (O%(P0IO<LI<I0 directive to associate selected eCception names 2it/ an Oracle database error number) 0/is enables ,ou to reBer to an, oB t/e eCceptions in a standard 2a, in ,our applicationsA as in t/e Bollo2ing eCample:
6( I< D(L(0( :1O= departments >9(1( departmentLid Z deptnoR ))) (O%(P0IO< >9(< errorLp5g)eLB5Lerr 09(< ))) >9(< O09(1S 09(< ))) (<DR /

c ra O l, - On

, em ad .c

ra c O

le

l ae rn Uste

Oracle Database 11g: Develop PL/SQL Program Units G E +

In

Standardi4ing (Cception 9andling


%onsider 2riting a subprogram Bor common eCception /andling to: Displa, errors based on SQL%OD( and SQL(11= values Bor eCceptions 0rac5 runEtime errors easil, b, using parameters in ,our code to identiB,:
M 0/e procedure in 2/ic/ t/e error occurred M 0/e location Hline numberI oB t/e error M 1.IS(L.PPLI%.0IO<L(11O1 using stac5 trace capabilitiesA 2it/ t/e t/ird argument set to 01U(

%op,rig/t @ &''"A Oracle) .ll rig/ts reserved)

Standardi4ing (Cception 9andling Standardi4ed eCception /andling can be implemented eit/er as a standEalone subprogram or a subprogram added to t/e pac5age t/at deBines t/e standard eCceptions) %onsider creating a pac5age 2it/: (ver, named eCception t/at is to be used in t/e application .ll unnamedA programmerEdeBined eCceptions t/at are used in t/e application) 0/ese are error numbers M&'''' t/roug/ M&'""") . program to call 1.IS(L.PPLI%.0IO<L(11O1 based on pac5age eCceptions . program to displa, an error based on t/e values oB SQL%OD( and SQL(11= .dditional ob3ectsA suc/ as error log tablesA and programs to access t/e tables . common practice is to use parameters t/at identiB, t/e name oB t/e procedure and t/e location in 2/ic/ t/e error /as occurred) 0/is enables ,ou to 5eep trac5 oB runEtime errors more easil,) .n alternative is to use t/e 1.IS(L.PPLI%.0IO<L(11O1 builtEin procedure to 5eep a stac5 trace oB eCceptions t/at can be used to trac5 t/e call sePuence leading to t/e error) 0o do t/isA set t/e t/ird optional argument to 01U() :or eCample:

c ra O l, - On

, em ad .c

ra c O

le

1.IS(L.PPLI%.0IO<L(11O1HE&'''1A S=, Birst errorSA 01U(IR

0/is is meaningBul 2/en more t/an one eCception is raised in t/is manner)

l ae rn Uste

Oracle Database 11g: Develop PL/SQL Program Units G E $

In

Standardi4ing %onstants
:or programs t/at use local variables 2/ose values s/ould not c/ange: %onvert t/e variables to constants to reduce maintenance and debugging %reate one central pac5age speciBication and place all constants in it

%1(.0( O1 1(PL.%( P.%?. ( constantLp5g IS cLorderLreceived %O<S0.<0 V.1%9.1H&I :Z SO1SR cLorderLs/ipped cLminLsal (<D constantLp5gR %O<S0.<0 V.1%9.1H&I :Z SOSSR %O<S0.<0 <U=6(1H*I :Z "''R

%op,rig/t @ &''"A Oracle) .ll rig/ts reserved)

Standardi4ing %onstants 6, deBinitionA a variableFs value c/angesA 2/ereas a constantFs value cannot be c/anged) IB ,ou /ave programs t/at use local variables 2/ose values s/ould not and do not c/angeA t/en convert t/e variables to constants) 0/is can /elp 2it/ t/e maintenance and debugging oB ,our code) %onsider creating a single s/ared pac5age 2it/ all ,our constants in it) 0/is ma5es maintenance and c/ange oB t/e constants muc/ easier) 0/is procedure or pac5age can be loaded on s,stem startup Bor better perBormance) 0/e eCample in t/e slide s/o2s t/e constantLp5g pac5age containing a Be2 constants) 1eBer to an, oB t/e pac5age constants in ,our application as rePuired) 9ere is an eCample:

ra c O

6( I< UPD.0( emplo,ees S(0 salar, Z salar, N &'' >9(1( salar, ^Z constantLp5g)cLminLsalR (<DR /

c ra O l, - On

, em ad .c

le

l ae rn Uste

Oracle Database 11g: Develop PL/SQL Program Units G E G

In

Local Subprograms
. local subprogram is a P1O%(DU1( or :U<%0IO< deBined at t/e end oB t/e declarative section in a subprogram)
%1(.0( P1O%(DU1( emplo,eeLsalHpLid <U=6(1I IS vLemp emplo,eesQ1O>08P(R :U<%0IO< taCHpLsalar, V.1%9.1&I 1(0U1< <U=6(1 IS 6( I< 1(0U1< pLsalar, K ')#&+R (<D taCR 6( I< S(L(%0 K I<0O vLemp :1O= (=PLO8((S >9(1( emplo,eeLid Z pLidR D6=SLOU0PU0)PU0LLI<(HS0aC: STT taCHvLemp)salar,IIR (<DR / (O(%U0( emplo,eeLsalH1''I

%op,rig/t @ &''"A Oracle) .ll rig/ts reserved)

Local Subprograms Local subprograms can drive topEdo2n design) 0/e, reduce t/e si4e oB a module b, removing redundant code) 0/is is one oB t/e main reasons Bor creating a local subprogram) IB a module needs t/e same routine several timesA but onl, t/is module needs t/e routineA t/en deBine it as a local subprogram) 8ou can deBine a named PL/SQL bloc5 in t/e declarative section oB an, PL/SQL programA procedureA BunctionA or anon,mous bloc5 provided t/at it is declared at t/e end oB t/e Declaration section) Local subprograms /ave t/e Bollo2ing c/aracteristics: 0/e, are onl, accessible to t/e bloc5 in 2/ic/ t/e, are deBined) 0/e, are compiled as part oB t/eir enclosing bloc5s)

ra c O

0/e beneBits oB local subprograms are: 1eduction oB repetitive code Improved code readabilit, and ease oB maintenance Less administration because t/ere is one program to maintain instead oB t2o

c ra O l, - On

, em ad .c

le

0/e concept is simple) 0/e eCample s/o2n in t/e slide illustrates t/is 2it/ a basic eCample oB an income taC calculation oB an emplo,eeFs salar,)

l ae rn Uste

Oracle Database 11g: Develop PL/SQL Program Units G E #

In

DeBinerFs 1ig/ts Versus Invo5erFs 1ig/ts


DeBinerFs rig/ts: Programs eCecute 2it/ t/e privileges oB t/e creating user) User does not rePuire privileges on underl,ing ob3ects t/at t/e procedure accesses) User rePuires privilege onl, to eCecute a procedure)
Invo5erFs rig/ts: Programs eCecute 2it/ t/e privileges oB t/e calling user) User rePuires privileges on t/e underl,ing ob3ects t/at t/e procedure accesses)

%op,rig/t @ &''"A Oracle) .ll rig/ts reserved)

DeBinerFs 1ig/ts Versus Invo5erFs 1ig/ts DeBinerFs 1ig/ts =odel 6, deBaultA all programs eCecuted 2it/ t/e privileges oB t/e user 2/o created t/e subprogram) 0/is is 5no2n as t/e deBinerFs rig/ts modelA 2/ic/: .llo2s a caller oB t/e program t/e privilege to eCecute t/e procedureA but no privileges on t/e underl,ing ob3ects t/at t/e procedure accesses 1ePuires t/e o2ner to /ave all t/e necessar, ob3ect privileges Bor t/e ob3ects t/at t/e procedure reBerences :or eCampleA iB user Scott creates a PL/SQL subprogram getLemplo,ees t/at is subsePuentl, invo5ed b, Sara/A t/en t/e getLemplo,ees procedure runs 2it/ t/e privileges oB t/e deBiner Scott) Invo5erFs 1ig/ts =odel In t/e invo5erFs rig/ts modelA 2/ic/ 2as introduced in Oracle#iA programs are eCecuted 2it/ t/e privileges oB t/e calling user) . user oB a procedure running 2it/ invo5erFs rig/ts rePuires privileges on t/e underl,ing ob3ects t/at t/e procedure reBerences) :or eCampleA iB ScottFs PL/SQL subprogram getLemplo,ees is invo5ed b, Sara/A t/en t/e getLemplo,ees procedure runs 2it/ t/e privileges oB t/e invo5er Sara/)

c ra O l, - On

, em ad .c

ra c O

le

l ae rn Uste

Oracle Database 11g: Develop PL/SQL Program Units G E "

In

SpeciB,ing Invo5erFs 1ig/ts: Setting .U09ID to %U11(<0LUS(1


%1(.0( O1 1(PL.%( P1O%(DU1( addLdeptH pLid <U=6(1A pLname V.1%9.1&I .U09ID %U11(<0LUS(1 IS 6( I< I<S(10 I<0O departments V.LU(S HpLidA pLnameA <ULLA <ULLIR (<DR

>/en used 2it/ standEalone BunctionsA proceduresA or pac5ages: <ames used in PueriesA D=LA <ative D,namic SQLA and D6=SLSQL pac5age are resolved in t/e invo5erFs sc/ema %alls to ot/er pac5agesA BunctionsA and procedures are resolved in t/e deBinerFs sc/ema

%op,rig/t @ &''"A Oracle) .ll rig/ts reserved)

SpeciB,ing Invo5erFs 1ig/ts 8ou can set t/e invo5erFs rig/ts Bor diBBerent PL/SQL subprogram constructs as Bollo2s:
%1(.0( %1(.0( %1(.0( %1(.0(

:U<%0IO< name 1(0U1< t,pe .U09ID %U11(<0LUS(1 IS))) P1O%(DU1( name .U09ID %U11(<0LUS(1 IS_ P.%?. ( name .U09ID %U11(<0LUS(1 IS_ 08P( name .U09ID %U11(<0LUS(1 IS O6;(%0_

0/e deBault is .U09ID D(:I<(1A 2/ic/ speciBies t/at t/e subprogram eCecutes 2it/ t/e privileges oB its o2ner) =ost supplied PL/SQL pac5ages suc/ as D6=SLLO6A D6=SL1O>IDA and so onA are invo5erErig/ts pac5ages) <ame 1esolution :or a deBinerFs rig/ts procedureA all eCternal reBerences are resolved in t/e deBinerFs sc/ema) :or an invo5erFs rig/ts procedureA t/e resolution oB eCternal reBerences depends on t/e 5ind oB statement in 2/ic/ t/e, appear: <ames used in PueriesA data manipulation language HD=LI statementsA d,namic SQLA and D6=SLSQL are resolved in t/e invo5erFs sc/ema) .ll ot/er statementsA suc/ as calls to pac5agesA BunctionsA and proceduresA are resolved in t/e deBinerFs sc/ema)

c ra O l, - On

, em ad .c

ra c O

le

l ae rn Uste

Oracle Database 11g: Develop PL/SQL Program Units G E 1'

In

.utonomous 0ransactions
.re independent transactions started b, anot/er main transaction .re speciBied 2it/ P1. =. .U0O<O=OUSL01.<S.%0IO<
=ain 0ransaction .utonomous HindependentI 0ransaction

1 G

P1O%(DU1( proc1 IS empLid <U=6(1R 6( I< empLid :Z 1&*!R %O==I0R I<S(10 ))) proc&R

P1O%(DU1( proc& IS P1. =. .U0O<O=OUSL01.<S.%0IO<R deptLid 6( I< <U=6(1 :Z "'R

&
D(L(0( ))) %O==I0R (<D proc1R

! +

UPD.0( ))) I<S(10 ))) %O==I0R (<D proc&R

%op,rig/t @ &''"A Oracle) .ll rig/ts reserved)

.utonomous 0ransactions . transaction is a series oB statements doing a logical unit oB 2or5 t/at completes or Bails as an integrated unit) OBtenA one transaction starts anot/er t/at ma, need to operate outside t/e scope oB t/e transaction t/at started it) 0/at isA in an eCisting transactionA a rePuired independent transaction ma, need to commit or roll bac5 c/anges 2it/out aBBecting t/e outcome oB t/e starting transaction) :or eCampleA in a stoc5 purc/ase transactionA t/e customerFs inBormation must be committed regardless oB 2/et/er t/e overall stoc5 purc/ase completes) OrA 2/ile running t/at same transactionA ,ou 2ant to log messages to a table even iB t/e overall transaction rolls bac5) Since Oracle#iA autonomous transactions 2ere added to ma5e it possible to create an independent transaction) .n autonomous transaction H.0I is an independent transaction started b, anot/er main transaction H=0I) 0/e slide depicts t/e be/avior oB an .0: 1) 0/e main transaction begins) &) . proc& procedure is called to start t/e autonomous transaction) *) 0/e main transaction is suspended) !) 0/e autonomous transactional operation begins) +) 0/e autonomous transaction ends 2it/ a commit or roll bac5 operation) $) 0/e main transaction is resumed) G) 0/e main transaction ends)

c ra O l, - On

, em ad .c
EE 1ePuired

ra c O

le

l ae rn Uste

Oracle Database 11g: Develop PL/SQL Program Units G E 11

In

:eatures oB .utonomous 0ransactions


.re independent oB t/e main transaction Suspend t/e calling transaction until t/e autonomous transactions are completed .re not nested transactions Do not roll bac5 iB t/e main transaction rolls bac5 (nable t/e c/anges to become visible to ot/er transactions upon a commit .re started and ended b, individual subprograms and not b, nested or anon,mous PL/SQL bloc5s

%op,rig/t @ &''"A Oracle) .ll rig/ts reserved)

:eatures oB .utonomous 0ransactions .utonomous transactions eC/ibit t/e Bollo2ing Beatures: .lt/oug/ called 2it/in a transactionA autonomous transactions are independent oB t/at transaction) 0/at isA t/e, are not nested transactions) IB t/e main transaction rolls bac5A autonomous transactions do not) %/anges made b, an autonomous transaction become visible to ot/er transactions 2/en t/e autonomous transaction commits) >it/ t/eir stac5Eli5e Bunctionalit,A onl, t/e XtopY transaction is accessible at an, given time) .Bter completionA t/e autonomous transaction is poppedA and t/e calling transaction is resumed) 0/ere are no limits ot/er t/an resource limits on /o2 man, autonomous transactions can be recursivel, called) .utonomous transactions must be eCplicitl, committed or rolled bac5R ot/er2iseA an error is returned 2/en attempting to return Brom t/e autonomous bloc5) 8ou cannot use P1. =. to mar5 all subprograms in a pac5age as autonomous) Onl, individual routines can be mar5ed autonomous) 8ou cannot mar5 a nested or anon,mous PL/SQL bloc5 as autonomous)

c ra O l, - On

, em ad .c

ra c O

le

l ae rn Uste

Oracle Database 11g: Develop PL/SQL Program Units G E 1&

In

Using .utonomous 0ransactions: (Cample


%1(.0( 0.6L( usage HcardLid <U=6(1A loc <U=6(1I / %1(.0( 0.6L( tCn HaccLid <U=6(1A amount <U=6(1I / %1(.0( O1 1(PL.%( P1O%(DU1( logLusage HpLcardLid <U=6(1A pLloc <U=6(1I IS P1. =. .U0O<O=OUSL01.<S.%0IO<R 6( I< I<S(10 I<0O usage V.LU(S HpLcardLidA pLlocIR %O==I0R (<D logLusageR / %1(.0( O1 1(PL.%( P1O%(DU1( ban5LtransHpLcardnbr <U=6(1ApLloc <U=6(1I IS 6( I< I<S(10 I<0O tCn V.LU(S H"''1A 1'''IR logLusage HpLcardnbrA pLlocIR (<D ban5LtransR / (O(%U0( ban5LtransH+'A &'''I

%op,rig/t @ &''"A Oracle) .ll rig/ts reserved)

Using .utonomous 0ransactions 0o deBine autonomous transactionsA ,ou use P1. =. .U0O<O=OUSL01.<S.%0IO<) P1. =. instructs t/e PL/SQL compiler to mar5 a routine as autonomous HindependentI) In t/is conteCtA t/e term XroutineY includes topElevel Hnot nestedI anon,mous PL/SQL bloc5sR localA standEaloneA and pac5aged Bunctions and proceduresR met/ods oB a SQL ob3ect t,peR and database triggers) 8ou can code P1. =. an,2/ere in t/e declarative section oB a routine) 9o2everA Bor readabilit,A it is best placed at t/e top oB t/e Declaration section) In t/e eCample in t/e slideA ,ou trac5 2/ere t/e ban5card is usedA regardless oB 2/et/er t/e transaction is successBul) 0/e Bollo2ing are t/e beneBits oB autonomous transactions: .Bter startingA an autonomous transaction is Bull, independent) It s/ares no loc5sA resourcesA or commit dependencies 2it/ t/e main transactionA so ,ou can log eventsA increment retr, countersA and so on even iB t/e main transaction rolls bac5) =ore importantl,A autonomous transactions /elp ,ou build modularA reusable soBt2are components) :or eCampleA stored procedures can start and Binis/ autonomous transactions on t/eir o2n) . calling application need not 5no2 about a procedureFs autonomous operationsA and t/e procedure need not 5no2 about t/e applicationFs transaction conteCt) 0/at ma5es autonomous transactions less errorEprone t/an regular transactions and easier to use)

c ra O l, - On

, em ad .c

ra c O

le

l ae rn Uste

Oracle Database 11g: Develop PL/SQL Program Units G E 1*

In

Using .utonomous 0ransactions HcontinuedI 0/e output oB t/e previous slide eCamplesA t/e 0O< and US. ( tables are as Bollo2s:

0o run t/e code on t/e previous pageA enter t/e Bollo2ing code: (O(%U0( ban5LtransH+'A &'''I Use t/e Data tab in t/e 0ables node oB t/e Ob3ect <avigator tree to displa, t/e values in t/e 0O< and US. ( tables as Bollo2s:

l c ra O l, - On ra c O le In l ae rn Uste e

, em ad .c

Oracle Database 11g: Develop PL/SQL Program Units G E 1!

Lesson .genda
Standardi4ing constants and eCceptionsA using local subprogramsA controlling t/e runEtime privileges oB a subprogramA and perBorming autonomous transactions Using t/e <O%OP8 and t/e P.1.LL(L (<.6L( /intsA t/e crossEsession PL/SQL Bunction result cac/eA and t/e D(0(1=I<IS0I% clause Using t/e 1(0U1<I< clause and bul5 binding 2it/ D=L

%op,rig/t @ &''"A Oracle) .ll rig/ts reserved)

l c ra O l, - On ra c O le In l ae rn Uste e

, em ad .c

Oracle Database 11g: Develop PL/SQL Program Units G E 1+

Using t/e <O%OP8 9int


.llo2s t/e PL/SQL compiler to pass OU0 and I< OU0 parameters b, reBerence rat/er t/an b, value (n/ances perBormance b, reducing over/ead 2/en passing parameters

D(%L.1( 08P(recLempLt,pe IS 0.6L( O: emplo,eesQ1O>08P(R recLemp recLempLt,peR P1O%(DU1( populateHpLtab I< OU0 <O%OP8 emptabt,peIIS 6( I< ))) (<DR 6( I< populateHrecLempIR (<DR /

%op,rig/t @ &''"A Oracle) .ll rig/ts reserved)

Using t/e <O%OP8 9int <ote t/at PL/SQL subprograms support t/ree parameterEpassing modes: I<A OU0A and I< OU0) 6, deBault: 0/e I< parameter is passed b, reBerence) . pointer to t/e I< actual parameter is passed to t/e corresponding Bormal parameter) SoA bot/ t/e parameters reBerence t/e same memor, locationA 2/ic/ /olds t/e value oB t/e actual parameter) 0/e OU0 and I< OU0 parameters are passed b, value) 0/e value oB t/e OU0 or I< OU0 actual parameter is copied into t/e corresponding Bormal parameter) 0/enA iB t/e subprogram eCits normall,A t/e values assigned to t/e OU0 and I< OU0 Bormal parameters are copied into t/e corresponding actual parameters) %op,ing parameters t/at represent large data structures Hsuc/ as collectionsA recordsA and instances oB ob3ect t,pesI 2it/ OU0 and I< OU0 parameters slo2s do2n eCecution and uses up memor,) 0o prevent t/is over/eadA ,ou can speciB, t/e <O%OP8 /intA 2/ic/ enables t/e PL/SQL compiler to pass t/e OU0 and I< OU0 parameters b, reBerence) 0/e slide s/o2s an eCample oB declaring an I< OU0 parameter 2it/ t/e <O%OP8 /int)

c ra O l, - On

, em ad .c

ra c O

le

l ae rn Uste

Oracle Database 11g: Develop PL/SQL Program Units G E 1$

In

(BBects oB t/e <O%OP8 9int


IB t/e subprogram eCits 2it/ an eCception t/at is not /andled:
M 8ou cannot rel, on t/e values oB t/e actual parameters passed to a <O%OP8 parameter M .n, incomplete modiBications are not Xrolled bac5Y

0/e remote procedure call H1P%I protocol enables ,ou to pass parameters onl, b, value)

%op,rig/t @ &''"A Oracle) .ll rig/ts reserved)

(BBects oB t/e <O%OP8 9int .s a tradeEoBB Bor better perBormanceA t/e <O%OP8 /int enables ,ou to trade 2ellEdeBined eCception semantics Bor better perBormance) Its use aBBects eCception /andling in t/e Bollo2ing 2a,s: 6ecause <O%OP8 is a /int and not a directiveA t/e compiler can pass <O%OP8 parameters to a subprogram b, value or b, reBerence) SoA iB t/e subprogram eCits 2it/ an un/andled eCceptionA ,ou cannot rel, on t/e values oB t/e <O%OP8 actual parameters) 6, deBaultA iB a subprogram eCits 2it/ an un/andled eCceptionA t/e values assigned to its OU0 and I< OU0 Bormal parameters are not copied to t/e corresponding actual parametersA and t/e c/anges appear to roll bac5) 9o2everA 2/en ,ou speciB, <O%OP8A assignments to t/e Bormal parameters immediatel, aBBect t/e actual parameters as 2ell) SoA iB t/e subprogram eCits 2it/ an un/andled eCceptionA t/e Hpossibl, unBinis/edI c/anges are not Xrolled bac5)Y %urrentl,A t/e 1P% protocol enables ,ou to pass parameters onl, b, value) SoA eCception semantics can c/ange 2it/out notiBication 2/en ,ou partition applications) :or eCampleA iB ,ou move a local procedure 2it/ <O%OP8 parameters to a remote siteA t/ose parameters are no longer passed b, reBerence)

c ra O l, - On

, em ad .c

ra c O

le

l ae rn Uste

Oracle Database 11g: Develop PL/SQL Program Units G E 1G

In

>/en Does t/e PL/SQL %ompiler Ignore t/e <O%OP8 9intJ


0/e <O%OP8 /int /as no eBBect iB: 0/e actual parameter:
M Is an element oB associative arra,s HindeCEb, tablesI M Is constrained HBor eCampleA b, scale or <O0 <ULLI M .nd Bormal parameter are recordsA 2/ere one or bot/ records 2ere declared b, using Q1O>08P( or Q08P(A and constraints on corresponding Bields in t/e records diBBer M 1ePuires an implicit data t,pe conversion

0/e subprogram is involved in an eCternal or remote procedure call

%op,rig/t @ &''"A Oracle) .ll rig/ts reserved)

>/en Does t/e PL/SQL %ompiler Ignore t/e <O%OP8 9intJ In t/e Bollo2ing casesA t/e PL/SQL compiler ignores t/e <O%OP8 /int and uses t/e b,Evalue parameterEpassing met/od H2it/ no error generatedI: 0/e actual parameter is an element oB associative arra,s HindeCEb, tablesI) 0/is restriction does not appl, to entire associative arra,s) 0/e actual parameter is constrained Hb, scale or <O0 <ULLI) 0/is restriction does not eCtend to constrained elements or attributes) .lsoA it does not appl, to si4eEconstrained c/aracter strings) 0/e actual and Bormal parameters are recordsR one or bot/ records 2ere declared b, using Q1O>08P( or Q08P(A and constraints on corresponding Bields in t/e records diBBer) 0/e actual and Bormal parameters are recordsR t/e actual parameter 2as declared Himplicitl,I as t/e indeC oB a cursor :O1 loopA and constraints on corresponding Bields in t/e records diBBer) Passing t/e actual parameter rePuires an implicit data t,pe conversion) 0/e subprogram is involved in an eCternal or remote procedure call)

c ra O l, - On

, em ad .c

ra c O

le

l ae rn Uste

Oracle Database 11g: Develop PL/SQL Program Units G E 1#

In

Using t/e P.1.LL(LL(<.6L( 9int


%an be used in Bunctions as an optimi4ation /int Indicates t/at a Bunction can be used in a paralleli4ed Puer, or paralleli4ed D=L statement

%1(.0( O1 1(PL.%( :U<%0IO< B& HpLp1 <U=6(1I 1(0U1< <U=6(1 P.1.LL(LL(<.6L( IS 6( I< 1(0U1< pLp1 K &R (<D B&R

%op,rig/t @ &''"A Oracle) .ll rig/ts reserved)

Using t/e P.1.LL(LL(<.6L( 9int 0/e P.1.LL(LL(<.6L( 5e,2ord can be used in t/e s,ntaC Bor declaring a Bunction) It is an optimi4ation /int t/at indicates t/at t/e Bunction can be used in a paralleli4ed Puer, or paralleli4ed D=L statement) OracleFs parallel eCecution Beature divides t/e 2or5 oB eCecuting a SQL statement across multiple processes) :unctions called Brom a SQL statement t/at is run in parallel can /ave a separate cop, run in eac/ oB t/ese processesA 2it/ eac/ cop, called Bor onl, t/e subset oB ro2s t/at are /andled b, t/at process) :or D=L statementsA beBore Oracle#iA t/e paralleli4ation optimi4ation loo5ed to see 2/et/er a Bunction 2as noted as /aving all Bour oB 1<DSA ><DSA 1<PSA and ><PS speciBied in a P1. =. 1(S01I%0L1(:(1(<%(S declarationR t/ose Bunctions t/at 2ere mar5ed as neit/er reading nor 2riting to eit/er t/e database or pac5age variables could run in parallel) .gainA t/ose Bunctions deBined 2it/ a %1(.0( :U<%0IO< statement /ad t/eir code implicitl, eCamined to determine 2/et/er t/e, 2ere actuall, pure enoug/R paralleli4ed eCecution mig/t occur even t/oug/ a P1. =. cannot be speciBied on t/ese Bunctions) 0/e P.1.LL(LL(<.6L( 5e,2ord is placed aBter t/e return value t,pe in t/e declaration oB t/e BunctionA as s/o2n in t/e eCample in t/e slide) <ote: 0/e Bunction s/ould not use session stateA suc/ as pac5age variablesA because t/ose variables ma, not be s/ared among t/e parallel eCecution servers)

c ra O l, - On

, em ad .c

ra c O

le

l ae rn Uste

Oracle Database 11g: Develop PL/SQL Program Units G E 1"

In

Using t/e %rossESession PL/SQL :unction 1esult %ac/e


(ac/ time a resultEcac/ed PL/SQL Bunction is called 2it/ diBBerent parameter valuesA t/ose parameters and t/eir results are stored in cac/e) 0/e Bunction result cac/e is stored in a s/ared global area HS .IA ma5ing it available to an, session t/at runs ,our application) SubsePuent calls to t/e same Bunction 2it/ t/e same parameters uses t/e result Brom cac/e) PerBormance and scalabilit, are improved) 0/is Beature is used 2it/ Bunctions t/at are called BrePuentl, and dependent on inBormation t/at c/anges inBrePuentl,)

%op,rig/t @ &''"A Oracle) .ll rig/ts reserved)

%rossESession PL/SQL :unction 1esult %ac/e Starting in Oracle Database 11gA ,ou can use t/e PL/SQL crossEsession Bunction result cac/ing mec/anism) 0/is cac/ing mec/anism provides ,ou 2it/ a languageEsupported and s,stemE managed means Bor storing t/e results oB PL/SQL Bunctions in a s/ared global area HS .IA 2/ic/ is available to ever, session t/at runs ,our application) 0/e cac/ing mec/anism is bot/ eBBicient and eas, to useA and it relieves ,ou oB t/e burden oB designing and developing ,our o2n cac/es and cac/eEmanagement policies) (ac/ time a resultEcac/ed PL/SQL Bunction is called 2it/ diBBerent parameter valuesA t/ose parameters and t/eir results are stored in t/e cac/e) SubsePuentl,A 2/en t/e same Bunction is called 2it/ t/e same parameter valuesA t/e result is retrieved Brom t/e cac/eA instead oB being recomputed) IB a database ob3ect t/at 2as used to compute a cac/ed result is updatedA t/e cac/ed result becomes invalid and must be recomputed) Use t/e resultEcac/ing Beature 2it/ Bunctions t/at are called BrePuentl, and are dependent on inBormation t/at never c/anges or c/anges inBrePuentl,)

c ra O l, - On

, em ad .c

ra c O

le

<ote: :or additional inBormation about %rossESession PL/SQL :unction 1esult %ac/eA reBer to t/e Oracle Database 11g .dvanced PL/SQL courseA t/e Oracle Database 11g SQL and PL/SQL <e2 :eatures courseA or t/e Oracle Database PL/SQL Language 1eBerence 11g 1elease & H11)&I guide)

l ae rn Uste

Oracle Database 11g: Develop PL/SQL Program Units G E &'

In

(nabling 1esultE%ac/ing Bor a :unction


8ou can ma5e a Bunction resultEcac/ed as Bollo2s: Include t/e 1(SUL0L%.%9( clause in t/e Bollo2ing:
M 0/e Bunction declaration M 0/e Bunction deBinition

Include an optional 1(LI(SLO< clause to speciB, an, tables or vie2s on 2/ic/ t/e Bunction results depend)

%op,rig/t @ &''"A Oracle) .ll rig/ts reserved)

(nabling 1esultE%ac/ing Bor a :unction 0o enable resultEcac/ing Bor a PL/SQL BunctionA use t/e 1(SUL0L%.%9( clause) >/en a resultEcac/ed Bunction is calledA t/e s,stem c/ec5s t/e Bunction result cac/e) IB t/e cac/e contains t/e result Brom a previous call to t/e Bunction 2it/ t/e same parameter valuesA t/e s,stem returns t/e cac/ed result to t/e caller and does not reeCecute t/e Bunction bod,) IB t/e cac/e does not contain t/e resultA t/e s,stem eCecutes t/e Bunction bod, and adds t/e result HBor t/ese parameter valuesI to t/e cac/e beBore returning control to t/e caller) 0/e cac/e can accumulate man, resultsUone result Bor ever, uniPue combination oB parameter values 2it/ 2/ic/ eac/ resultEcac/ed Bunction /as been called) IB t/e s,stem needs more memor,A it ages out HdeletesI one or more cac/ed results)

<ote: IB Bunction eCecution results in an un/andled eCceptionA t/e eCception result is not stored in t/e cac/e)

c ra O l, - On

, em ad .c

ra c O

le

l ae rn Uste

Oracle Database 11g: Develop PL/SQL Program Units G E &1

In

Declaring and DeBining a 1esultE%ac/ed :unction: (Cample

%1(.0( O1 1(PL.%( :U<%0IO< empL/ireLdate HpLempLid <U=6(1I 1(0U1< V.1%9.1 1(SUL0L%.%9( 1(LI(SLO< Hemplo,eesI IS vLdateL/ired D.0(R 6( I< S(L(%0 /ireLdate I<0O vLdateL/ired :1O= 91)(mplo,ees >9(1( (mplo,eeLID Z pLempLIDR 1(0U1< toLc/arHvLdateL/iredIR (<DR

%op,rig/t @ &''"A Oracle) .ll rig/ts reserved)

Declaring and DeBining a 1esultE%ac/ed :unction: (Cample IB a Bunction depends on settings t/at mig/t var, Brom session to session suc/ as <LSLD.0(L:O1=.0 and 0I=( 7O<(A ma5e t/e Bunction resultEcac/ed onl, iB ,ou can modiB, it to /andle t/e various settings) In t/e eCample in t/e slideA t/e empL/ireLdate Bunction uses t/e toLc/ar Bunction to convert a D.0( item to a V.1%9.1 item) empL/ireLdate does not speciB, a Bormat mas5A so t/e Bormat mas5 deBaults to t/e one t/at <LSLD.0(L:O1=.0 speciBies) IB sessions t/at call empL/ireLdate /ave diBBerent <LSLD.0(L:O1=.0 settingsA cac/ed results can /ave diBBerent Bormats) IB a cac/ed result computed b, one session ages outA and anot/er session recomputes itA t/e Bormat mig/t var, even Bor t/e same parameter value) IB a session gets a cac/ed result 2/ose Bormat diBBers Brom its o2n BormatA t/at result 2ill probabl, be incorrect) Some possible solutions to t/is problem are: %/ange t/e return t,pe oB empL/ireLdate to D.0( and /ave eac/ session call t/e toLc/ar Bunction) IB a common Bormat is acceptable to all sessionsA speciB, a Bormat mas5A removing t/e dependenc, on <LSLD.0(L:O1=.0UBor eCampleA toLc/arHdateL/iredA Smm/dd/,,SIR)

c ra O l, - On

, em ad .c

ra c O

le

l ae rn Uste

Oracle Database 11g: Develop PL/SQL Program Units G E &&

In

Declaring and DeBining a 1esultE%ac/ed :unction: (Cample HcontinuedI .dd a Bormat mas5 parameter to 9ireDate as Bollo2s:
%1(.0( O1 1(PL.%( :U<%0IO< empL/ireLdate HpLempLid <U=6(1A Bmt V.1%9.1I 1(0U1< V.1%9.1 1(SUL0L%.%9( 1(LI(SLO< Hemplo,eesI IS vLdateL/ired D.0(R 6( I< S(L(%0 /ireLdate I<0O vLdateL/ired :1O= emplo,ees >9(1( emplo,eeLid Z pLempLidR 1(0U1< toLc/arHvLdateL/iredA BmtIR (<DR

l c ra O l, - On ra c O le In l ae rn Uste e

, em ad .c

Oracle Database 11g: Develop PL/SQL Program Units G E &*

Using t/e D(0(1=I<IS0I% %lause 2it/ :unctions


SpeciB, D(0(1=I<IS0I% to indicate t/at t/e Bunction returns t/e same result value 2/enever it is called 2it/ t/e same values Bor its arguments) 0/is /elps t/e optimi4er avoid redundant Bunction calls) IB a Bunction 2as called previousl, 2it/ t/e same argumentsA t/e optimi4er can elect to use t/e previous result) Do not speciB, D(0(1=I<IS0I% Bor a Bunction 2/ose result depends on t/e state oB session variables or sc/ema ob3ects)

%op,rig/t @ &''"A Oracle) .ll rig/ts reserved)

Using t/e D(0(1=I<IS0I% %lause 2it/ :unctions 8ou can use t/e D(0(1=I<IS0I% Bunction clause to indicate t/at t/e Bunction returns t/e same result value 2/enever it is called 2it/ t/e same values Bor its arguments)

ra c O

8ou must speciB, t/is 5e,2ord iB ,ou intend to call t/e Bunction in t/e eCpression oB a BunctionE based indeC or Brom t/e Puer, oB a materiali4ed vie2 t/at is mar5ed 1(:1(S9 :.S0 or (<.6L( QU(18 1(>1I0() >/en Oracle Database encounters a deterministic Bunction in one oB t/ese conteCtsA it attempts to use previousl, calculated results 2/en possible rat/er t/an reeCecuting t/e Bunction) IB ,ou subsePuentl, c/ange t/e semantics oB t/e BunctionA ,ou must manuall, rebuild all dependent BunctionEbased indeCes and materiali4ed vie2s) Do not speciB, t/is clause to deBine a Bunction t/at uses pac5age variables or t/at accesses t/e database in an, 2a, t/at mig/t aBBect t/e return result oB t/e Bunction) 0/e results oB doing so 2ill not be captured iB Oracle Database c/ooses not to reeCecute t/e Bunction) <ote Do not speciB, D(0(1=I<IS0I% Bor a Bunction 2/ose result depends on t/e state oB session variables or sc/ema ob3ects because results mig/t var, across calls) InsteadA consider ma5ing t/e Bunction resultEcac/ed) :or more inBormation about t/e D(0(1=I<IS0I% clauseA reBer to t/e Oracle Database SQL Language 1eBerence 11g 1elease 1 H11)1I guide)

c ra O l, - On

, em ad .c

le

l ae rn Uste

Oracle Database 11g: Develop PL/SQL Program Units G E &!

In

Lesson .genda
Standardi4ing constants and eCceptionsA using local subprogramsA controlling t/e runEtime privileges oB a subprogramA and perBorming autonomous transactions Using t/e <O%OP8 and t/e P.1.LL(L (<.6L( /intsA t/e crossEsession PL/SQL Bunction result cac/eA and t/e D(0(1=I<IS0I% clause Using t/e 1(0U1<I< clause and bul5 binding 2it/ D=L

%op,rig/t @ &''"A Oracle) .ll rig/ts reserved)

l c ra O l, - On ra c O le In l ae rn Uste e

, em ad .c

Oracle Database 11g: Develop PL/SQL Program Units G E &+

Using t/e 1(0U1<I< %lause


Improves perBormance b, returning column values 2it/ I<S(10A UPD.0(A and D(L(0( statements (liminates t/e need Bor a S(L(%0 statement

%1(.0( O1 1(PL.%( P1O%(DU1( updateLsalar,HpLempLid <U=6(1I IS vLnameemplo,ees)lastLnameQ08P(R vLne2Lsal emplo,ees)salar,Q08P(R 6( I< UPD.0( emplo,ees S(0 salar, Z salar, K 1)1 >9(1( emplo,eeLid Z pLempLid 1(0U1<I< lastLnameA salar, I<0O vLnameA vLne2LsalR D6=SLOU0PU0)PU0LLI<(HvLname TT S ne2 salar, is S TT vLne2LsalIR (<D updateLsalar,R /

%op,rig/t @ &''"A Oracle) .ll rig/ts reserved)

Using t/e 1(0U1<I< %lause

l c ra O l, - On e

OBtenA applications need inBormation about t/e ro2 aBBected b, a SQL operationUBor eCampleA to generate a report or to ta5e a subsePuent action) 0/e I<S(10A UPD.0(A and D(L(0( statements can include a 1(0U1<I< clauseA 2/ic/ returns column values Brom t/e aBBected ro2 into PL/SQL variables or /ost variables) 0/is eliminates t/e need to S(L(%0 t/e ro2 aBter an I<S(10 or UPD.0(A or beBore a D(L(0() .s a resultA Be2er net2or5 round tripsA less server %PU timeA Be2er cursorsA and less server memor, are rePuired) 0/e eCample in t/e slide s/o2s /o2 to update t/e salar, oB an emplo,ee andA at t/e same timeA retrieve t/e emplo,eeFs last name and ne2 salar, into a local PL/SQL variable) 0o test t/e code eCampleA issue t/e Bollo2ing commands t/at c/ec5 t/e salar, oB emplo,eeLid 1'# beBore updating it) <eCtA t/e procedure is invo5ed passing t/e emplo,eeLid 1'# as t/e parameter)

, em ad .c

ra c O

le In

l ae rn Uste

Oracle Database 11g: Develop PL/SQL Program Units G E &$

Using 6ul5 6inding


6inds 2/ole arra,s oB values in a single operationA rat/er t/an using a loop to perBorm a :(0%9A I<S(10A UPD.0(A and D(L(0( operation multiple times

PL/SQL runEtime engine


PL/SQL bloc5 :O1.LL 3 I< 1))1''' I<S(10 HidA datesI V.LU(S HidsH3IA datesH3IIR ))) Procedural statement eCecutor

SQL engine
SQL statement eCecutor

%op,rig/t @ &''"A Oracle) .ll rig/ts reserved)

Using 6ul5 6inding 0/e Oracle server uses t2o engines to run PL/SQL bloc5s and subprograms: 0/e PL/SQL runEtime engineA 2/ic/ runs procedural statements but passes t/e SQL statements to t/e SQL engine 0/e SQL engineA 2/ic/ parses and eCecutes t/e SQL statement andA in some casesA returns data to t/e PL/SQL engine During eCecutionA ever, SQL statement causes a conteCt s2itc/ bet2een t/e t2o enginesA 2/ic/ results in a perBormance penalt, Bor eCcessive amounts oB SQL processing) 0/is is t,pical oB applications t/at /ave a SQL statement in a loop t/at uses values Brom indeCed collections) %ollections include nested tablesA var,ing arra,sA indeCEb, tablesA and /ost arra,s)

ra c O

PerBormance can be substantiall, improved b, minimi4ing t/e number oB conteCt s2itc/es t/roug/ t/e use oB bul5 binding) 6ul5 binding causes an entire collection to be bound in one callA a conteCt s2itc/A to t/e SQL engine) 0/at isA a bul5 bind process passes t/e entire collection oB values bac5 and Bort/ bet2een t/e t2o engines in a single conteCt s2itc/A compared 2it/ incurring a conteCt s2itc/ Bor eac/ collection element in an iteration oB a loop) 0/e more ro2s aBBected b, a SQL statementA t/e greater t/e perBormance gain 2it/ bul5 binding)

c ra O l, - On

, em ad .c

le

l ae rn Uste

Oracle Database 11g: Develop PL/SQL Program Units G E &G

In

6ul5 6inding: S,ntaC and ?e,2ords


0/e :O1.LL 5e,2ord instructs t/e PL/SQL engine to bul5 bind input collections beBore sending t/em to t/e SQL engine)

:O1.LL indeC I< lo2erLbound )) upperLbound VS.V( (O%(P0IO<SW sPlLstatementR

0/e 6UL? %OLL(%0 5e,2ord instructs t/e SQL engine to bul5 bind output collections beBore returning t/em to t/e PL/SQL engine)

))) 6UL? %OLL(%0 I<0O collectionLnameVAcollectionLnameW )))

%op,rig/t @ &''"A Oracle) .ll rig/ts reserved)

6ul5 6inding: S,ntaC and ?e,2ords Use bul5 binds to improve t/e perBormance oB: D=L statements t/at reBerence collection elements S(L(%0 statements t/at reBerence collection elements %ursor :O1 loops t/at reBerence collections and t/e 1(0U1<I< I<0O clause 0/e :O1.LL 5e,2ord instructs t/e PL/SQL engine to bul5 bind input collections beBore sending t/em to t/e SQL engine) .lt/oug/ t/e :O1.LL statement contains an iteration sc/emeA it is not a :O1 loop) 0/e 6UL? %OLL(%0 5e,2ord instructs t/e SQL engine to bul5 bind output collectionsA beBore returning t/em to t/e PL/SQL engine) 0/is enables ,ou to bind locations into 2/ic/ SQL can return t/e retrieved values in bul5) 0/usA ,ou can use t/ese 5e,2ords in t/e S(L(%0 I<0OA :(0%9 I<0OA and 1(0U1<I< I<0O clauses) 0/e S.V( (O%(P0IO<S 5e,2ord is optional) 9o2everA iB some oB t/e D=L operations succeed and some BailA ,ou 2ould 2ant to trac5 or report on t/ose t/at Bail) Using t/e S.V( (O%(P0IO<S 5e,2ord causes Bailed operations to be stored in a cursor attribute called Q6UL?L(O%(P0IO<SA 2/ic/ is a collection oB records indicating t/e bul5 D=L iteration number and corresponding error code)

c ra O l, - On

, em ad .c

ra c O

le

l ae rn Uste

Oracle Database 11g: Develop PL/SQL Program Units G E &#

In

6ul5 6inding: S,ntaC and ?e,2ords HcontinuedI 9andling :O1.LL (Cceptions 2it/ t/e Q6UL?L(O%(P0IO<S .ttribute 0o manage eCceptions and /ave t/e bul5 bind complete despite errorsA add t/e 5e,2ords S.V( (O%(P0IO<S to ,our :O1.LL statement aBter t/e boundsA beBore t/e D=L statement) .ll eCceptions raised during t/e eCecution are saved in t/e cursor attribute Q6UL?L(O%(P0IO<SA 2/ic/ stores a collection oB records) (ac/ record /as t2o Bields: Q6UL?L(O%(P0IO<SHII)(11O1LI<D(O /olds t/e XiterationY oB t/e :O1.LL statement during 2/ic/ t/e eCception 2as raised and Q6UL?L(O%(P0IO<SHiI)(11O1L%OD( /olds t/e corresponding Oracle error code) Values stored in Q6UL?L(O%(P0IO<S reBer to t/e most recentl, eCecuted :O1.LL statement) Its subscripts range Brom 1 to Q6UL?L(O%(P0IO<S)%OU<0) <ote: :or additional inBormation about bul5 binding and /andling bul5Ebinding eCceptionsA reBer to t/e Oracle Database PL/SQL UserSs uide and 1eBerence 11g 1elease & H11)&I)

l c ra O l, - On ra c O le In l ae rn Uste e

, em ad .c

Oracle Database 11g: Develop PL/SQL Program Units G E &"

6ul5 6inding :O1.LL: (Cample

%1(.0( P1O%(DU1( raiseLsalar,HpLpercent <U=6(1I IS 08P( numlistLt,pe IS 0.6L( O: <U=6(1 I<D(O 68 6I<.18LI<0( (1R vLid numlistLt,peR EE collection 6( I< vLidH1I:Z 1''R vLidH&I:Z 1'&R vLidH*I:Z 1'!R vLidH!I :Z 11'R EE bul5Ebind t/e PL/SQL table :O1.LL i I< vLid):I1S0 )) vLid)L.S0 UPD.0( emplo,ees S(0 salar, Z H1 N pLpercent/1''I K salar, >9(1( emplo,eeLid Z vLidHiIR (<DR /

(O(%U0( raiseLsalar,H1'I

%op,rig/t @ &''"A Oracle) .ll rig/ts reserved)

6ul5 6inding :O1.LL: (Cample

l c ra O l, - On e

<ote: 6eBore ,ou can run t/e eCample in t/e slideA ,ou must disable t/e updateL3obL/istor, trigger as Bollo2s:
.L0(1 01I (1 updateL3obL/istor, DIS.6L(R

, em ad .c

In t/e eCample in t/e slideA t/e PL/SQL bloc5 increases t/e salar, Bor emplo,ees 2it/ IDs 1''A 1'&A 1'!A or 11') It uses t/e :O1.LL 5e,2ord to bul5 bind t/e collection) >it/out bul5 bindingA t/e PL/SQL bloc5 2ould /ave sent a SQL statement to t/e SQL engine Bor eac/ emplo,ee record t/at is updated) IB t/ere are man, emplo,ee records to updateA t/en t/e large number oB conteCt s2itc/es bet2een t/e PL/SQL engine and t/e SQL engine can aBBect perBormance) 9o2everA t/e :O1.LL 5e,2ord bul5 binds t/e collection to improve perBormance) <ote: . looping construct is no longer rePuired 2/en using t/is Beature)

ra c O

le In

l ae rn Uste

Oracle Database 11g: Develop PL/SQL Program Units G E *'

6ul5 6inding :O1.LL: (Cample HcontinuedI .n .dditional %ursor .ttribute Bor D=L Operations .not/er cursor attribute added to support bul5 operations is Q6UL?L1O>%OU<0) 0/e Q6UL?L1O>%OU<0 attribute is a composite structure designed Bor use 2it/ t/e :O1.LL statement) 0/is attribute acts li5e an indeCEb, table) Its it/ element stores t/e number oB ro2s processed b, t/e it/ eCecution oB an UPD.0( or D(L(0( statement) IB t/e it/ eCecution aBBects no ro2sA t/en Q6UL?L1O>%OU<0HiIreturns 4ero) 9ere is an eCample:
%1(.0( 0.6L( numLtable Hn <U=6(1IR D(%L.1( 08P( numLlistLt,pe IS 0.6L( O: <U=6(1 I<D(O 68 6I<.18LI<0( (1R vLnums numLlistLt,peR 6( I< vLnumsH1I :Z 1R vLnumsH&I :Z *R vLnumsH*I :Z +R vLnumsH!I :Z GR vLnumsH+I :Z 11R :O1.LL i I< vLnums):I1S0 )) vLnums)L.S0 I<S(10 I<0O vLnumLtable HnI V.LU(S HvLnumsHiIIR :O1 i I< vLnums):I1S0 )) vLnums)L.S0 LOOP dbmsLoutput)putLlineHSInserted S TT SQLQ6UL?L1O>%OU<0HiI TT S ro2HsIS TT S on iteration S TT iIR (<D LOOPR (<DR / D1OP 0.6L( numLtableR

0/e Bollo2ing results are produced b, t/is eCample:

c ra O l, - On

, em ad .c

ra c O

le In

l ae rn Uste

Oracle Database 11g: Develop PL/SQL Program Units G E *1

Using 6UL? %OLL(%0 I<0O 2it/ Queries


0/e S(L(%0 statement supports t/e 6UL? %OLL(%0 I<0O s,ntaC)
%1(.0( P1O%(DU1( getLdepartmentsHpLloc <U=6(1I IS 08P( deptLtabLt,pe IS 0.6L( O: departmentsQ1O>08P(R vLdepts deptLtabLt,peR 6( I< S(L(%0 K 6UL? %OLL(%0 I<0O vLdepts :1O= departments >9(1( locationLid Z pLlocR :O1 i I< 1 )) vLdepts)%OU<0 LOOP D6=SLOU0PU0)PU0LLI<(HvLdeptsHiI)departmentLid TTS STT vLdeptsHiI)departmentLnameIR (<D LOOPR (<DR

%op,rig/t @ &''"A Oracle) .ll rig/ts reserved)

Using 6UL? %OLL(%0 I<0O 2it/ Queries Starting 2it/ Oracle Database 1'gA 2/en using a S(L(%0 statement in PL/SQLA ,ou can use t/e bul5 collection s,ntaC s/o2n in t/e eCample in t/e slide) 0/usA ,ou can Puic5l, obtain a set oB ro2s 2it/out using a cursor mec/anism) 0/e eCample reads all t/e department ro2s Bor a speciBied region into a PL/SQL tableA 2/ose contents are displa,ed 2it/ t/e :O1 loop t/at Bollo2s t/e S(L(%0 statement)

c ra O l, - On

, em ad .c

ra c O

le In

l ae rn Uste

Oracle Database 11g: Develop PL/SQL Program Units G E *&

Using 6UL? %OLL(%0 I<0O 2it/ %ursors


0/e :(0%9 statement /as been en/anced to support t/e 6UL? %OLL(%0 I<0O s,ntaC)
%1(.0( O1 1(PL.%( P1O%(DU1( getLdepartmentsHpLloc <U=6(1I IS %U1SO1 curLdept IS S(L(%0 K :1O= departments >9(1( locationLid Z pLlocR 08P( deptLtabLt,pe IS 0.6L( O: curLdeptQ1O>08P(R vLdepts deptLtabLt,peR 6( I< OP(< curLdeptR :(0%9 curLdept 6UL? %OLL(%0 I<0O vLdeptsR %LOS( curLdeptR :O1 i I< 1 )) vLdepts)%OU<0 LOOP D6=SLOU0PU0)PU0LLI<(HvLdeptsHiI)departmentLid TTS STT vLdeptsHiI)departmentLnameIR (<D LOOPR (<DR

%op,rig/t @ &''"A Oracle) .ll rig/ts reserved)

Using 6UL? %OLL(%0 I<0O 2it/ %ursors In Oracle Database 1'gA 2/en using cursors in PL/SQLA ,ou can use a Borm oB t/e :(0%9 statement t/at supports t/e bul5 collection s,ntaC s/o2n in t/e eCample in t/e slide) 0/is eCample s/o2s /o2 6UL? %OLL(%0 I<0O can be used 2it/ cursors) 8ou can also add a LI=I0 clause to control t/e number oB ro2s Betc/ed in eac/ operation) 0/e code eCample in t/e slide could be modiBied as Bollo2s:
%1(.0( O1 1(PL.%( P1O%(DU1( getLdepartmentsHpLloc <U=6(1A pLnro2s <U=6(1I IS %U1SO1 deptLcsr IS S(L(%0 K :1O= departments >9(1( locationLid Z pLlocR 08P( deptLtabt,pe IS 0.6L( O: deptLcsrQ1O>08P(R depts deptLtabt,peR 6( I< OP(< deptLcsrR :(0%9 deptLcsr 6UL? %OLL(%0 I<0O depts LI=I0 nro2sR %LOS( deptLcsrR D6=SLOU0PU0)PU0LLI<(Hdepts)%OU<0TTS ro2s readSIR (<DR

c ra O l, - On

, em ad .c

ra c O

le

l ae rn Uste

Oracle Database 11g: Develop PL/SQL Program Units G E **

In

Using 6UL? %OLL(%0 I<0O 2it/ a 1(0U1<I< %lause


%1(.0( O1 1(PL.%( P1O%(DU1( raiseLsalar,HpLrate <U=6(1I IS 08P( emplistLt,pe IS 0.6L( O: <U=6(1R 08P( numlistLt,pe IS 0.6L( O: emplo,ees)salar,Q08P( I<D(O 68 6I<.18LI<0( (1R vLempLids emplistLt,pe :Z emplistLt,peH1''A1'1A1'&A1'!IR vLne2Lsals numlistLt,peR 6( I< :O1.LL i I< vLempLids):I1S0 )) vLempLids)L.S0 UPD.0( emplo,ees S(0 commissionLpct Z pLrate K salar, >9(1( emplo,eeLid Z vLempLidsHiI 1(0U1<I< salar, 6UL? %OLL(%0 I<0O vLne2LsalsR :O1 i I< 1 ))vLne2Lsals)%OU<0 LOOP D6=SLOU0PU0)PU0LLI<(HvLne2LsalsHiIIR (<D LOOPR (<DR

%op,rig/t @ &''"A Oracle) .ll rig/ts reserved)

Using 6UL? %OLL(%0 I<0O 2it/ a 1(0U1<I< %lause 6ul5 binds can be used to improve t/e perBormance oB :O1 loops t/at reBerence collections and return D=L) IB ,ou /aveA or plan to /aveA PL/SQL code t/at does t/isA t/en ,ou can use t/e :O1.LL 5e,2ord along 2it/ t/e 1(0U1<I< and 6UL? %OLL(%0 I<0O 5e,2ords to improve perBormance) In t/e eCample s/o2n in t/e slideA t/e salar, inBormation is retrieved Brom t/e (=PLO8((S table and collected into t/e ne2Lsals arra,) 0/e ne2Lsals collection is returned in bul5 to t/e PL/SQL engine) 0/e eCample in t/e slide s/o2s an incomplete :O1 loop t/at is used to iterate t/roug/ t/e ne2 salar, data received Brom t/e UPD.0( operation and t/en process t/e results)

c ra O l, - On

, em ad .c

ra c O

le In

l ae rn Uste

Oracle Database 11g: Develop PL/SQL Program Units G E *!

Using 6ul5 6inds in Sparse %ollections


%urrent releases:
1& !'
IndeC b, PLSLI<0( (1 :O1 .LL ) ) ) I< I<DI%(S O:

G! 1 & * ! +

*+ $

Prior releases:
IndeC b, 6I<.18LI<0( (1

1& !' 1 & *

G! ! +

*+ $

%op,rig/t @ &''"A Oracle) .ll rig/ts reserved)

:O1.LL Support Bor Sparse %ollections In earlier releasesA PL/SQL did not allo2 sparse collections to be used 2it/ t/e :O1.LL statement) IB t/e S.V( (O%(P0IO<S 5e,2ord 2as not speciBiedA t/e statement 2as terminated 2/en t/e Birst deleted element 2as encountered) (ven 2/en S.V( (O%(P0IO< 2as usedA t/e PL/SQL engine tried to iterate over all elements HeCisting and nonEeCistingI) 0/is substantiall, degraded t/e perBormance oB t/e D=L operation iB t/e relative percentage oB t/e deleted elements 2as /ig/) >/en ,ou use t/e 5e,2ord I<DI%(S Havailable 2it/ Oracle Database 1'g and laterIA ,ou can successBull, loop over a sparse collection 2it/ t/e :O1.LL statement) 0/is s,ntaC binds sparse collections more eBBicientl, and it also supports a more general approac/ 2/ere an indeC arra, can be speciBied to iterate over t/e collections) Using sparse collection and indeC arra,s in bul5 operations improves perBormance)

c ra O l, - On

, em ad .c

ra c O

le In

l ae rn Uste

Oracle Database 11g: Develop PL/SQL Program Units G E *+

Using 6ul5 6inds in Sparse %ollections


EE 0/e I<DI%(S O: s,ntaC allo2s t/e bound arra,s EE t/emselves to be sparse) :O1.LL indeCLname I< I<DI%(S O: sparseLarra,Lname 6(0>((< LO>(1L6OU<D .<D UPP(1L6OU<D EE optional S.V( (O%(P0IO<S EE optionalA but recommended I<S(10 I<0O tableLname V.LU(S sparseLarra,HindeCLnameIR )))

EE 0/e V.LU(S O: s,ntaC lets ,ou indicate a subset EE oB t/e binding arra,s) :O1.LL indeCLname I< V.LU(S O: indeCLarra,Lname S.V( (O%(P0IO<S EE optionalAbut recommended I<S(10 I<0O tableLname V.LU(S bindingLarra,LnameHindeCLnameIR )))

%op,rig/t @ &''"A Oracle) .ll rig/ts reserved)

:O1.LL Support Bor Sparse %ollections HcontinuedI 8ou can use t/e I<DI%(S O: and V.LU(S O: s,ntaC 2it/ t/e :O1.LL statement) 0/e bul5 bind Bor sparse arra, s,ntaC can be used in all D=L s,ntaCes) In t/e s,ntaCA t/e indeC arra, must be denseA and t/e binding arra,s ma, be dense or sparse and t/e indicated elements must eCist)

c ra O l, - On

, em ad .c

ra c O

le In

l ae rn Uste

Oracle Database 11g: Develop PL/SQL Program Units G E *$

Using 6ul5 6inds in Sparse %ollections


0/e t,pical application Bor t/is Beature is an order entr, and order processing s,stem 2/ere: Users enter orders t/roug/ t/e >eb Orders are placed in a staging table beBore validation Data is later validated based on compleC business rules Husuall, implemented programmaticall, using PL/SQLI Invalid orders are separated Brom valid ones Valid orders are inserted into a permanent table Bor processing

%op,rig/t @ &''"A Oracle) .ll rig/ts reserved)

Using 6ul5 6inds in Sparse %ollections 0/is Beature can be used in an, application t/at starts 2it/ a dense PL/SQL table oB records or table oB scalar t/at are populated using a bul5 collect) 0/is is used as t/e binding arra,) . dense arra, HpointerIA 2/ose elements denote t/e indices oB t/e binding arra,A is made sparse based on t/e application logic) 0/is pointer arra, is t/en used in t/e :O1.LL statement to perBorm bul5 D=L 2it/ t/e binding arra,s) .n, eCceptions encountered can be saved and Burt/er processed in t/e eCceptionE/andling sectionA per/aps b, using anot/er :O1.LL statement)

c ra O l, - On

, em ad .c

ra c O

le In

l ae rn Uste

Oracle Database 11g: Develop PL/SQL Program Units G E *G

Using 6ul5 6ind 2it/ IndeC .rra,

%1(.0( O1 1(PL.%( P1O%(DU1( insLemp& .S 08P( emptabLt,pe IS 0.6L( O: emplo,eesQ1O>08P(R vLemp emptabLt,peR 08P( valuesLoBLtabLt,pe IS 0.6L( O: PLSLI<0( (1 I<D(O 68 PLSLI<0( (1R vLnumvaluesLoBLtabLt,peR ))) 6( I< ))) :O1.LL 5 I< V.LU(S O: vLnum I<S(10 I<0O ne2Lemplo,ees V.LU(S vLempH5IR (<DR

%op,rig/t @ &''"A Oracle) .ll rig/ts reserved)

Using 6ul5 6ind 2it/ IndeC .rra, 8ou can use an indeC collection oB PLSLI<0( (1 or 6I<.18LI<0( (1 Hor one oB its subt,pesI 2/ose values are t/e indeCes oB t/e collections involved in t/e bul5Ebind D=L operation using :O1.LL) 0/ese indeC collections can t/en be used in a :O1.LL statement to process bul5 D=L using t/e V.LU(S O: clause) In t/e eCample s/o2n aboveA VL<U= is a collection 2/ose t,pe is PLSLI<0( (1) In t/e eCampleA ,ou are creating a procedure I<SL(=P&A 2/ic/ identiBies onl, one emplo,ee Bor eac/ occurrence oB t/e Birst letter oB t/e last name) 0/is procedure t/en inserts into t/e <(>L(=PLO8((S table created earlier using t/e :O1.LL))I< V.LU(S O: s,ntaC)

c ra O l, - On

, em ad .c

ra c O

le In

l ae rn Uste

Oracle Database 11g: Develop PL/SQL Program Units G E *#

Qui4
0/e <O%OP8 /int allo2s t/e PL/SQL compiler to pass OU0 and I< OU0 parameters b, reBerence rat/er t/an b, value) 0/is en/ances perBormance b, reducing over/ead 2/en passing parameters) 1) 0rue &) :alse

%op,rig/t @ &''"A Oracle) .ll rig/ts reserved)

.ns2er: 1 PL/SQL subprograms support t/ree parameterEpassing modes: I<A OU0A and I< OU0)

6, deBault: 0/e I< parameter is passed b, reBerence) . pointer to t/e I< actual parameter is passed to t/e corresponding Bormal parameter) SoA bot/ t/e parameters reBerence t/e same memor, locationA 2/ic/ /olds t/e value oB t/e actual parameter) 0/e OU0 and I< OU0 parameters are passed b, value) 0/e value oB t/e OU0 or I< OU0 actual parameter is copied into t/e corresponding Bormal parameter) 0/enA iB t/e subprogram eCits normall,A t/e values assigned to t/e OU0 and I< OU0 Bormal parameters are copied into t/e corresponding actual parameters)

ra c O

%op,ing parameters t/at represent large data structures Hsuc/ as collectionsA recordsA and instances oB ob3ect t,pesI 2it/ OU0 and I< OU0 parameters slo2s do2n eCecution and uses up memor,) 0o prevent t/is over/eadA ,ou can speciB, t/e <O%OP8 /intA 2/ic/ enables t/e PL/SQL compiler to pass OU0 and I< OU0 parameters b, reBerence)

c ra O l, - On

, em ad .c

le

l ae rn Uste

Oracle Database 11g: Develop PL/SQL Program Units G E *"

In

Summar,
In t/is lessonA ,ou s/ould /ave learned /o2 to: %reate standard constants and eCceptions >rite and call local subprograms %ontrol t/e runEtime privileges oB a subprogram PerBorm autonomous transactions Pass parameters b, reBerence using a <O%OP8 /int Use t/e P.1.LL(L (<.6L( /int Bor optimi4ation

Use t/e crossEsession PL/SQL Bunction result cac/e Use t/e D(0(1=I<IS0I% clause 2it/ Bunctions Use t/e 1(0U1<I< clause and bul5 binding 2it/ D=L

%op,rig/t @ &''"A Oracle) .ll rig/ts reserved)

Summar, 0/e lesson provides insig/ts into managing ,our PL/SQL code b, deBining constants and eCceptions in a pac5age speciBication) 0/is enables a /ig/ degree oB reuse and standardi4ation oB code) Local subprograms can be used to simpliB, and modulari4e a bloc5 oB code 2/ere t/e subprogram Bunctionalit, is repeatedl, used in t/e local bloc5) 0/e runEtime securit, privileges oB a subprogram can be altered b, using deBinerFs or invo5erFs rig/ts) .utonomous transactions can be eCecuted 2it/out aBBecting an eCisting main transaction) 8ou s/ould understand /o2 to obtain perBormance gains b, using t/e <O%OP8 /intA bul5 binding and t/e 1(0U1<I< clauses in SQL statementsA and t/e P.1.LL(LL(<.6L( /int Bor optimi4ation oB Bunctions)

c ra O l, - On

, em ad .c

ra c O

le In

l ae rn Uste

Oracle Database 11g: Develop PL/SQL Program Units G E !'

Practice G: Overvie2
0/is practice covers t/e Bollo2ing topics: %reating a pac5age t/at uses bul5 Betc/ operations %reating a local subprogram to perBorm an autonomous transaction to audit a business operation

%op,rig/t @ &''"A Oracle) .ll rig/ts reserved)

Practice G: Overvie2 In t/is practiceA ,ou create a pac5age t/at perBorms a bul5 Betc/ oB emplo,ees in a speciBied department) 0/e data is stored in a PL/SQL table in t/e pac5age) 8ou also provide a procedure to displa, t/e contents oB t/e table) 8ou add an addLemplo,ee procedure to t/e pac5age t/at inserts ne2 emplo,ees) 0/e procedure uses a local autonomous subprogram to 2rite a log record eac/ time t/e addLemplo,ee procedure is calledA 2/et/er it successBull, adds a record or not)

c ra O l, - On

, em ad .c

ra c O

le In

l ae rn Uste

Oracle Database 11g: Develop PL/SQL Program Units G E !1

l c ra O l, - On ra c O le In l ae rn Uste e

, em ad .c

%reating 0riggers

%op,rig/t @ &''"A Oracle) .ll rig/ts reserved)

l c ra O l, - On ra c O le In l ae rn Uste e

, em ad .c

Ob3ectives
.Bter completing t/is lessonA ,ou s/ould be able to do t/e Bollo2ing: Describe database triggers and t/eir uses Describe t/e diBBerent t,pes oB triggers %reate database triggers Describe database triggerEBiring rules 1emove database triggers Displa, trigger inBormation

%op,rig/t @ &''"A Oracle) .ll rig/ts reserved)

Lesson .im In t/is lessonA ,ou learn /o2 to create and use database triggers)

c ra O l, - On

, em ad .c

ra c O

le In

l ae rn Uste

Oracle Database 11g: Develop PL/SQL Program Units # E &

>/at .re 0riggersJ


. trigger is a PL/SQL bloc5 t/at is stored in t/e database and Bired HeCecutedI in response to a speciBied event) 0/e Oracle database automaticall, eCecutes a trigger 2/en speciBied conditions occur)

%op,rig/t @ &''"A Oracle) .ll rig/ts reserved)

>or5ing 2it/ 0riggers: Overvie2 0riggers are similar to stored procedures) . trigger stored in t/e database contains PL/SQL in t/e Borm oB an anon,mous bloc5A a call statementA or a compound trigger bloc5) 9o2everA procedures and triggers diBBer in t/e 2a, t/at t/e, are invo5ed) . procedure is eCplicitl, run b, a userA applicationA or trigger) 0riggers are implicitl, Bired b, t/e Oracle database 2/en a triggering event occursA no matter 2/ic/ user is connected or 2/ic/ application is being used)

c ra O l, - On

, em ad .c

ra c O

le In

l ae rn Uste

Oracle Database 11g: Develop PL/SQL Program Units # E *

DeBining 0riggers
. trigger can be deBined on t/e tableA vie2A sc/ema Hsc/ema o2nerIA or database Hall usersI)

0able

Sc/ema Ho2nerI

Vie2
%op,rig/t @ &''"A Oracle) .ll rig/ts reserved)

Database H.ll usersI

l c ra O l, - On ra c O le In l ae rn Uste e

, em ad .c

Oracle Database 11g: Develop PL/SQL Program Units # E !

0rigger (vent 0,pes


8ou can 2rite triggers t/at Bire 2/enever one oB t/e Bollo2ing operations occurs in t/e database: . database manipulation HD=LI statement HD(L(0(A I<S(10A or UPD.0(I) . database deBinition HDDLI statement H%1(.0(A .L0(1A or D1OPI) . database operation suc/ as S(1V(1(11O1A LO O<A LO O::A S0.10UPA or S9U0DO><)

%op,rig/t @ &''"A Oracle) .ll rig/ts reserved)

0riggering (vent or Statement . triggering event or statement is t/e SQL statementA database eventA or user event t/at causes a trigger to Bire) . triggering event can be one or more oB t/e Bollo2ing: .n I<S(10A UPD.0(A or D(L(0( statement on a speciBic table Hor vie2A in some casesI . %1(.0(A .L0(1A or D1OP statement on an, sc/ema ob3ect . database startup or instance s/utdo2n . speciBic error message or an, error message . user logon or logoBB

c ra O l, - On

, em ad .c

ra c O

le In

l ae rn Uste

Oracle Database 11g: Develop PL/SQL Program Units # E +

.pplication and Database 0riggers


Database trigger Hcovered in t/is courseI:
M :ires 2/enever a D=LA a DLLA or s,stem event occurs on a sc/ema or database

.pplication trigger:
M :ires 2/enever an event occurs 2it/in a particular application

.pplication 0rigger

Database 0rigger

%op,rig/t @ &''"A Oracle) .ll rig/ts reserved)

0,pes oB 0riggers .pplication triggers eCecute implicitl, 2/enever a particular data manipulation language HD=LI event occurs 2it/in an application) .n eCample oB an application t/at uses triggers eCtensivel, is an application developed 2it/ Oracle :orms Developer) Database triggers eCecute implicitl, 2/en an, oB t/e Bollo2ing events occur: D=L operations on a table D=L operations on a vie2A 2it/ an I<S0(.D O: trigger DDL statementsA suc/ as %1(.0( and .L0(1

ra c O

0/is is t/e case no matter 2/ic/ user is connected or 2/ic/ application is used) Database triggers also eCecute implicitl, 2/en some user actions or database s,stem actions occur HBor eCampleA 2/en a user logs on or t/e D6. s/uts do2n t/e databaseI) Database triggers can be s,stem triggers on a database or a sc/ema Hcovered in t/e neCt lessonI) :or databasesA triggers Bire Bor eac/ event Bor all usersR Bor a sc/emaA t/e, Bire Bor eac/ event Bor t/at speciBic user) Oracle :orms can deBineA storeA and run triggers oB a diBBerent sort) 9o2everA do not conBuse Oracle :orms triggers 2it/ t/e triggers discussed in t/is lesson)

c ra O l, - On

, em ad .c

le

l ae rn Uste

Oracle Database 11g: Develop PL/SQL Program Units # E $

In

6usiness .pplication Scenarios Bor Implementing 0riggers


8ou can use triggers Bor: Securit, .uditing Data integrit, 1eBerential integrit, 0able replication %omputing derived data automaticall, (vent logging

%op,rig/t @ &''"A Oracle) .ll rig/ts reserved)

6usiness .pplication Scenarios Bor Implementing 0riggers Develop database triggers in order to en/ance Beatures t/at cannot ot/er2ise be implemented b, t/e Oracle server or as alternatives to t/ose provided b, t/e Oracle server) Securit,: 0/e Oracle server allo2s table access to users or roles) 0riggers allo2 table access according to data values) .uditing: 0/e Oracle server trac5s data operations on tables) 0riggers trac5 values Bor data operations on tables) Data integrit,: 0/e Oracle server enBorces integrit, constraints) 0riggers implement compleC integrit, rules) 1eBerential integrit,: 0/e Oracle server enBorces standard reBerential integrit, rules) 0riggers implement nonstandard Bunctionalit,) 0able replication: 0/e Oracle server copies tables as,nc/ronousl, into snaps/ots) 0riggers cop, tables s,nc/ronousl, into replicas) Derived data: 0/e Oracle server computes derived data values manuall,) 0riggers compute derived data values automaticall,) (vent logging: 0/e Oracle server logs events eCplicitl,) 0riggers log events transparentl,)

c ra O l, - On

, em ad .c

ra c O

le

l ae rn Uste

Oracle Database 11g: Develop PL/SQL Program Units # E G

In

.vailable 0rigger 0,pes


Simple D=L triggers
M 6(:O1( M .:0(1 M I<S0(.D O:

%ompound triggers <onED=L triggers


M DDL event triggers M Database event triggers

%op,rig/t @ &''"A Oracle) .ll rig/ts reserved)

<ote In t/is lessonA 2e 2ill discuss t/e 6(:O1(A .:0(1A and I<S0(.D O: triggers) 0/e ot/er trigger t,pes are discussed in t/e lesson titled X%reating %ompoundA DDLA and (vent Database 0riggers)Y

c ra O l, - On

, em ad .c

ra c O

le In

l ae rn Uste

Oracle Database 11g: Develop PL/SQL Program Units # E #

0rigger (vent 0,pes and 6od,


. trigger event t,pe determines 2/ic/ D=L statement causes t/e trigger to eCecute) 0/e possible events are:
M I<S(10 M UPD.0( VO: columnW M D(L(0(

. trigger bod, determines 2/at action is perBormed and is a PL/SQL bloc5 or a %.LL to a procedure)

%op,rig/t @ &''"A Oracle) .ll rig/ts reserved)

0riggering (vent 0,pes 0/e triggering event or statement can be an I<S(10A UPD.0(A or D(L(0( statement on a table) >/en t/e triggering event is an UPD.0( statementA ,ou can include a column list to identiB, 2/ic/ columns must be c/anged to Bire t/e trigger) 8ou cannot speciB, a column list Bor an I<S(10 or Bor a D(L(0( statement because it al2a,s aBBects entire ro2s)
) ) ) UPD.0( O: salar, ) ) )

0/e triggering event can contain oneA t2oA or all t/ree oB t/ese D=L operations) ) ) ) I<S(10 or UPD.0( or D(L(0( ) ) ) I<S(10 or UPD.0( O: 3obLid ) ) )

ra c O

0/e trigger bod, deBines t/e actionUt/at isA 2/at needs to be done 2/en t/e triggering event is issued) 0/e PL/SQL bloc5 can contain SQL and PL/SQL statementsA and can deBine PL/SQL constructs suc/ as variablesA cursorsA eCceptionsA and so on) 8ou can also call a PL/SQL procedure or a ;ava procedure) <ote: 0/e si4e oB a trigger cannot be greater t/an *& ?6)

c ra O l, - On

, em ad .c

le

l ae rn Uste

Oracle Database 11g: Develop PL/SQL Program Units # E "

In

%reating D=L 0riggers Using t/e %1(.0( 01I (1 Statement


%1(.0( VO1 1(PL.%(W 01I (1 triggerLname timing ME 2/en to Bire t/e trigger event1 VO1 event& O1 event*W O< ob3ectLname V1(:(1(<%I< OLD .S old T <(> .S ne2W :O1 (.%9 1O> ME deBault is statement level trigger >9(< HconditionIWW D(%L.1(W 6( I< ))) triggerLbod, ME eCecutable statements V(O%(P0IO< ) ) )W (<D VtriggerLnameWR

timing Z

6(:O1( T .:0(1 T I<S0(.D O:

event Z I<S(10 T D(L(0( T UPD.0( T UPD.0( O: columnLlist

%op,rig/t @ &''"A Oracle) .ll rig/ts reserved)

%reating D=L 0riggers 0/e components oB t/e trigger s,ntaC are: triggerLname uniPuel, identiBies t/e trigger) timing indicates 2/en t/e trigger Bires in relation to t/e triggering event) Values are 6(:O1(A .:0(1A and I<S0(.D O:) event identiBies t/e D=L operation causing t/e trigger to Bire) Values are I<S(10A UPD.0( VO: columnWA and D(L(0() ob3ectLname indicates t/e table or vie2 associated 2it/ t/e trigger) :or ro2 triggersA ,ou can speciB,: E . 1(:(1(<%I< clause to c/oose correlation names Bor reBerencing t/e old and ne2 values oB t/e current ro2 HdeBault values are OLD and <(>I E :O1 (.%9 1O> to designate t/at t/e trigger is a ro2 trigger E . >9(< clause to appl, a conditional predicateA in parent/esesA 2/ic/ is evaluated Bor eac/ ro2 to determine 2/et/er or not to eCecute t/e trigger bod, 0/e triggerLbod, is t/e action perBormed b, t/e triggerA implemented as eit/er oB t/e Bollo2ing: E .n anon,mous bloc5 2it/ a D(%L.1( or 6( I<A and an (<D E . %.LL clause to invo5e a standEalone or pac5aged stored procedureA suc/ as:

c ra O l, - On

, em ad .c

ra c O

le

%.LL m,LprocedureR

l ae rn Uste

Oracle Database 11g: Develop PL/SQL Program Units # E 1'

In

SpeciB,ing t/e 0rigger :iring H0imingI


8ou can speciB, t/e trigger timing as to 2/et/er to run t/e triggerFs action beBore or aBter t/e triggering statement: 6(:O1(: (Cecutes t/e trigger bod, beBore t/e triggering D=L event on a table) .:0(1: (Cecute t/e trigger bod, aBter t/e triggering D=L event on a table) I<S0(.D O:: (Cecute t/e trigger bod, instead oB t/e triggering statement) 0/is is used Bor vie2s t/at are not ot/er2ise modiBiable)

%op,rig/t @ &''"A Oracle) .ll rig/ts reserved)

0rigger 0iming 0/e 6(:O1( trigger timing is BrePuentl, used in t/e Bollo2ing situations: 0o determine 2/et/er t/e triggering statement s/ould be allo2ed to complete H0/is eliminates unnecessar, processing and enables a rollbac5 in cases 2/ere an eCception is raised in t/e triggering action)I 0o derive column values beBore completing an I<S(10 or UPD.0( statement 0o initiali4e global variables or BlagsA and to validate compleC business rules 0/e .:0(1 triggers are BrePuentl, used in t/e Bollo2ing situations: 0o complete t/e triggering statement beBore eCecuting t/e triggering action 0o perBorm diBBerent actions on t/e same triggering statement iB a 6(:O1( trigger is alread, present 0/e I<S0(.D O: triggers provide a transparent 2a, oB modiB,ing vie2s t/at cannot be modiBied directl, t/roug/ SQL D=L statements because a vie2 is not al2a,s modiBiable) 8ou can 2rite appropriate D=L statements inside t/e bod, oB an I<S0(.D O: trigger to perBorm actions directl, on t/e underl,ing tables oB vie2s) IB it is practicalA replace t/e set oB individual triggers 2it/ diBBerent timing points 2it/ a single compound trigger t/at eCplicitl, codes t/e actions in t/e order ,ou intend) IB t2o or more triggers are deBined 2it/ t/e same timing pointA and t/e order in 2/ic/ t/e, Bire is importantA t/en ,ou can control t/e Biring order using t/e :OLLO>S and P1(%(D(S clauses)

c ra O l, - On

, em ad .c

ra c O

le

l ae rn Uste

Oracle Database 11g: Develop PL/SQL Program Units # E 11

In

StatementELevel 0riggers Versus 1o2ELevel 0riggers

StatementELevel 0riggers
Is t/e deBault 2/en creating a trigger

1o2ELevel 0riggers
Use t/e :O1 (.%9 1O> clause 2/en creating a trigger) :ires once Bor eac/ ro2 aBBected b, t/e triggering event Does not Bire iB t/e triggering event does not aBBect an, ro2s

:ires once Bor t/e triggering event

:ires once even iB no ro2s are aBBected

%op,rig/t @ &''"A Oracle) .ll rig/ts reserved)

0,pes oB D=L 0riggers 8ou can speciB, t/at t/e trigger 2ill be eCecuted once Bor ever, ro2 aBBected b, t/e triggering statement Hsuc/ as a multiple ro2 UPD.0(I or once Bor t/e triggering statementA no matter /o2 man, ro2s it aBBects) Statement 0rigger . statement trigger is Bired once on be/alB oB t/e triggering eventA even iB no ro2s are aBBected at all) Statement triggers are useBul iB t/e trigger action does not depend on t/e data Brom ro2s t/at are aBBected or on data provided b, t/e triggering event itselB HBor eCampleA a trigger t/at perBorms a compleC securit, c/ec5 on t/e current userI) 1o2 0rigger . ro2 trigger Bires eac/ time t/e table is aBBected b, t/e triggering event) IB t/e triggering event aBBects no ro2sA a ro2 trigger is not eCecuted) 1o2 triggers are useBul iB t/e trigger action depends on data oB t/e ro2s t/at are aBBected or on data provided b, t/e triggering event itselB) <ote: 1o2 triggers use correlation names to access t/e old and ne2 column values oB t/e ro2 being processed b, t/e trigger)

c ra O l, - On

, em ad .c

ra c O

le

l ae rn Uste

Oracle Database 11g: Develop PL/SQL Program Units # E 1&

In

%reating D=L 0riggers Using SQL Developer

%op,rig/t @ &''"A Oracle) .ll rig/ts reserved)

l c ra O l, - On ra c O le In l ae rn Uste e

, em ad .c

Oracle Database 11g: Develop PL/SQL Program Units # E 1*

0riggerE:iring SePuence: SingleE1o2 =anipulation


Use t/e Bollo2ing Biring sePuence Bor a trigger on a table 2/en a single ro2 is manipulated:
I<S(10 I<0O departments HdepartmentLidAdepartmentLnameA locationLidI V.LU(S H!''A S%O<SUL0I< SA &!''IR
6(:O1( statement trigger

)))

6(:O1( ro2 trigger

.:0(1 ro2 trigger

.:0(1 statement trigger

%op,rig/t @ &''"A Oracle) .ll rig/ts reserved)

0riggerE:iring SePuence: SingleE1o2 =anipulation %reate a statement trigger or a ro2 trigger based on t/e rePuirement t/at t/e trigger must Bire once Bor eac/ ro2 aBBected b, t/e triggering statementA or 3ust once Bor t/e triggering statementA regardless oB t/e number oB ro2s aBBected) >/en t/e triggering D=L statement aBBects a single ro2A bot/ t/e statement trigger and t/e ro2 trigger Bire eCactl, once) (Cample 0/e SQL statement in t/e slide does not diBBerentiate statement triggers Brom ro2 triggers because eCactl, one ro2 is inserted into t/e table using t/e s,ntaC Bor t/e I<S(10 statement s/o2n in t/e slide)

c ra O l, - On

, em ad .c

ra c O

le In

l ae rn Uste

Oracle Database 11g: Develop PL/SQL Program Units # E 1!

0riggerE:iring SePuence: =ultiro2 =anipulation


Use t/e Bollo2ing Biring sePuence Bor a trigger on a table 2/en man, ro2s are manipulated:
UPD.0( emplo,ees S(0 salar, Z salar, K 1)1 >9(1( departmentLid Z *'R
6(:O1( statement trigger 6(:O1( ro2 trigger .:0(1 ro2 trigger

)))
6(:O1( ro2 trigger .:0(1 ro2 trigger

)))

.:0(1 statement trigger

%op,rig/t @ &''"A Oracle) .ll rig/ts reserved)

0riggerE:iring SePuence: =ultiro2 =anipulation >/en t/e triggering D=L statement aBBects man, ro2sA t/e statement trigger Bires eCactl, onceA and t/e ro2 trigger Bires once Bor ever, ro2 aBBected b, t/e statement)

(Cample 0/e SQL statement in t/e slide causes a ro2Elevel trigger to Bire a number oB times ePual to t/e number oB ro2s t/at satisB, t/e >9(1( clause Ht/at isA t/e number oB emplo,ees reporting to department *'I)

c ra O l, - On

, em ad .c

ra c O

le In

l ae rn Uste

Oracle Database 11g: Develop PL/SQL Program Units # E 1+

%reating a D=L Statement 0rigger (Cample: S(%U1(L(=P

I<S(10 I<0O (=PLO8((S)))R

D=L statement Bires trigger .pplication S(%U1(L(=P trigger

(=PLO8((S table

%1(.0( O1 1(PL.%( 01I (1 secureLemp 6(:O1( I<S(10 O< emplo,ees 6( I< I: H0OL%9.1HS8SD.0(ASD8SI I< HSS.0SASSU<SII O1 H0OL%9.1HS8SD.0(AS99&!:=ISI <O0 6(0>((< S'#:''S .<D S1#:''SI 09(< 1.IS(L.PPLI%.0IO<L(11O1HE&'+''A S8ou ma, insertS TTS into (=PLO8((S table onl, during S TTS normal business /ours)SIR (<D I:R (<DR

%op,rig/t @ &''"A Oracle) .ll rig/ts reserved)

%reating a D=L Statement 0rigger In t/e eCample in t/e slideA t/e S(%U1(L(=P database trigger is a 6(:O1( statement trigger t/at prevents t/e I<S(10 operation Brom succeeding iB t/e business condition is violated) In t/is caseA t/e trigger restricts inserts into t/e (=PLO8((S table during certain business /oursA =onda, t/roug/ :rida,) IB a user attempts to insert a ro2 into t/e (=PLO8((S table on Saturda,A t/en t/e user sees an error messageA t/e trigger BailsA and t/e triggering statement is rolled bac5) 1emember t/at t/e 1.IS(L.PPLI%.0IO<L(11O1 is a serverEside builtEin procedure t/at returns an error to t/e user and causes t/e PL/SQL bloc5 to Bail) >/en a database trigger BailsA t/e triggering statement is automaticall, rolled bac5 b, t/e Oracle server)

c ra O l, - On

, em ad .c

ra c O

le In

l ae rn Uste

Oracle Database 11g: Develop PL/SQL Program Units # E 1$

0esting 0rigger S(%U1(L(=P

I<S(10 I<0O emplo,ees Hemplo,eeLidA lastLnameA BirstLnameA emailA /ireLdateA 3obLidA salar,A departmentLidI V.LU(S H*''A SSmit/SA S1obSA S1S=I09SA S8SD.0(A SI0LP1O SA !+''A $'IR

%op,rig/t @ &''"A Oracle) .ll rig/ts reserved)

0esting S(%U1(L(=P 0o test t/e triggerA insert a ro2 into t/e (=PLO8((S table during nonbusiness /ours) >/en t/e date and time are out oB t/e business /ours speciBied in t/e triggerA ,ou receive t/e error message s/o2n in t/e slide)

c ra O l, - On

, em ad .c

ra c O

le In

l ae rn Uste

Oracle Database 11g: Develop PL/SQL Program Units # E 1G

Using %onditional Predicates


%1(.0( O1 1(PL.%( 01I (1 secureLemp 6(:O1( I<S(10 O1 UPD.0( O1 D(L(0( O< emplo,ees 6( I< I: H0OL%9.1HS8SD.0(ASD8SI I< HSS.0SASSU<SII O1 H0OL%9.1HS8SD.0(AS99&!SI <O0 6(0>((< S'#S .<D S1#SI 09(< I: D(L(0I< 09(< 1.IS(L.PPLI%.0IO<L(11O1H E&'+'&AS8ou ma, delete Brom (=PLO8((S tableSTT Sonl, during normal business /ours)SIR (LSI: I<S(10I< 09(< 1.IS(L.PPLI%.0IO<L(11O1H E&'+''AS8ou ma, insert into (=PLO8((S tableSTT Sonl, during normal business /ours)SIR (LSI: UPD.0I< HSS.L.18SI 09(< 1.IS(L.PPLI%.0IO<L(11O1HE&'+'*A S8ou ma, STT Supdate S.L.18 onl, normal during business /ours)SIR (LS( 1.IS(L.PPLI%.0IO<L(11O1HE&'+'!AS8ou ma,STT S update (=PLO8((S table onl, duringSTT S normal business /ours)SIR (<D I:R (<D I:R (<DR

%op,rig/t @ &''"A Oracle) .ll rig/ts reserved)

Detecting t/e D=L Operation 0/at :ired a 0rigger IB more t/an one t,pe oB D=L operation can Bire a trigger HBor eCampleA O< I<S(10 O1 D(L(0( O1 UPD.0( O: (mpLtabIA t/e trigger bod, can use t/e conditional predicates I<S(10I< A D(L(0I< A and UPD.0I< to c/ec5 2/ic/ t,pe oB statement Bired t/e trigger) 8ou can combine several triggering events into one b, ta5ing advantage oB t/e special conditional predicates I<S(10I< A UPD.0I< A and D(L(0I< 2it/in t/e trigger bod,)

(Cample %reate one trigger to restrict all data manipulation events on t/e (=PLO8((S table to certain business /oursA # .= to $ P=A =onda, t/roug/ :rida,)

c ra O l, - On

, em ad .c

ra c O

le In

l ae rn Uste

Oracle Database 11g: Develop PL/SQL Program Units # E 1#

%reating a D=L 1o2 0rigger


%1(.0( O1 1(PL.%( 01I (1 restrictLsalar, 6(:O1( I<S(10 O1 UPD.0( O: salar, O< emplo,ees :O1 (.%9 1O> 6( I< I: <O0 H:<(>)3obLid I< HS.DLP1(SSA S.DLVPSII .<D :<(>)salar, \ 1+''' 09(< 1.IS(L.PPLI%.0IO<L(11O1 HE&'&'&A S(mplo,ee cannot earn more t/an [1+A''')SIR (<D I:R (<DR

UPD.0( emplo,ees S(0 salar, Z 1++'' >9(1( lastLname Z S1ussellSR

%op,rig/t @ &''"A Oracle) .ll rig/ts reserved)

%reating a D=L 1o2 0rigger 8ou can create a 6(:O1( ro2 trigger in order to prevent t/e triggering operation Brom succeeding iB a certain condition is violated)

In t/e Birst eCample in t/e slideA a trigger is created to allo2 onl, emplo,ees 2/ose 3ob IDs are eit/er .DLP1(S or .DLVP to earn a salar, oB more t/an 1+A''') IB ,ou tr, to update t/e salar, oB emplo,ee 1ussell 2/ose emplo,ee ID is S.L=.<A t/e trigger raises t/e eCception displa,ed in t/e slide) <ote: 6eBore eCecuting t/e Birst code eCample in t/e slideA ma5e sure ,ou disable t/e secureLemp and secureLemplo,ees triggers)

c ra O l, - On

, em ad .c

ra c O

le In

l ae rn Uste

Oracle Database 11g: Develop PL/SQL Program Units # E 1"

Using OLD and <(> QualiBiers


>/en a ro2Elevel trigger BiresA t/e PL/SQL runEtime engine creates and populates t2o data structures:
M OLD: Stores t/e original values oB t/e record processed b, t/e trigger M <(>: %ontains t/e ne2 values

<(> and OLD /ave t/e same structure as a record declared using t/e Q1O>08P( on t/e table to 2/ic/ t/e trigger is attac/ed)
Old Value
<ULL Value beBore update Value beBore delete

Data Operations
I<S(10 UPD.0( D(L(0(

<e2 Value
Inserted value Value aBter update <ULL

%op,rig/t @ &''"A Oracle) .ll rig/ts reserved)

Using OLD and <(> QualiBiers >it/in a 1O> triggerA ,ou can reBerence t/e value oB a column beBore and aBter t/e data c/ange b, preBiCing it 2it/ t/e OLD and <(> PualiBiers) <ote 0/e OLD and <(> PualiBiers are available onl, in 1O> triggers) PreBiC t/ese PualiBiers 2it/ a colon H:I in ever, SQL and PL/SQL statement) 0/ere is no colon H:I preBiC iB t/e PualiBiers are reBerenced in t/e >9(< restricting condition) 1o2 triggers can decrease t/e perBormance iB ,ou perBorm man, updates on larger tables)

c ra O l, - On

, em ad .c

ra c O

le In

l ae rn Uste

Oracle Database 11g: Develop PL/SQL Program Units # E &'

Using OLD and <(> QualiBiers: (Cample


%1(.0( 0.6L( auditLemp H userLnameV.1%9.1&H*'IA timeLstampdateA id<U=6(1H$IA oldLlastLname V.1%9.1&H&+IA ne2LlastLname V.1%9.1&H&+IA oldLtitleV.1%9.1&H1'IA ne2LtitleV.1%9.1&H1'IA oldLsalar,<U=6(1H#A&IA ne2Lsalar,<U=6(1H#A&I I / %1(.0( O1 1(PL.%( 01I (1 auditLempLvalues .:0(1 D(L(0( O1 I<S(10 O1 UPD.0( O< emplo,ees :O1 (.%9 1O> 6( I< I<S(10 I<0O auditLempHuserLnameA timeLstampA idA oldLlastLnameA ne2LlastLnameA oldLtitleA ne2LtitleA oldLsalar,A ne2Lsalar,I V.LU(S HUS(1A S8SD.0(A :OLD)emplo,eeLidA :OLD)lastLnameA :<(>)lastLnameA :OLD)3obLidA :<(>)3obLidA :OLD)salar,A :<(>)salar,IR (<DR

%op,rig/t @ &''"A Oracle) .ll rig/ts reserved)

Using OLD and <(> QualiBiers: (Cample In t/e eCample in t/e slideA t/e .UDI0L(=PLV.LU(S trigger is created on t/e (=PLO8((S table) 0/e trigger adds ro2s to a user tableA .UDI0L(=PA logging a userFs activit, against t/e (=PLO8((S table) 0/e trigger records t/e values oB several columns bot/ beBore and aBter t/e data c/anges b, using t/e OLD and <(> PualiBiers 2it/ t/e respective column name)

c ra O l, - On

, em ad .c

ra c O

le In

l ae rn Uste

Oracle Database 11g: Develop PL/SQL Program Units # E &1

Using OLD and <(> QualiBiers: (Cample


I<S(10 I<0O emplo,ees Hemplo,eeLidA lastLnameA 3obLidA salar,A emailA /ireLdateI V.LU(S H"""A S0emp empSA SS.L1(PSA $'''A S0(=P(=PSA 01U<%HS8SD.0(II / UPD.0( emplo,ees S(0 salar, Z G'''A lastLname Z SSmit/S >9(1( emplo,eeLid Z """ / S(L(%0 K :1O= auditLempR

%op,rig/t @ &''"A Oracle) .ll rig/ts reserved)

Using OLD and <(> QualiBiers: (Cample t/e Using .UDI0L(=P 0able %reate a trigger on t/e (=PLO8((S table to add ro2s to a user tableA .UDI0L(=PA logging a userFs activit, against t/e (=PLO8((S table) 0/e trigger records t/e values oB several columns bot/ beBore and aBter t/e data c/anges b, using t/e OLD and <(> PualiBiers 2it/ t/e respective column name) 0/e Bollo2ing is t/e result oB inserting t/e emplo,ee record into t/e (=PLO8((S table:

))) 0/e Bollo2ing is t/e result oB updating t/e salar, Bor emplo,ee XSmit/Y:

c ra O l, - On

, em ad .c

ra c O
)))

le In

l ae rn Uste

Oracle Database 11g: Develop PL/SQL Program Units # E &&

Using t/e >9(< %lause to :ire a 1o2 0rigger 6ased on a %ondition

%1(.0( O1 1(PL.%( 01I (1 deriveLcommissionLpct 6(:O1( I<S(10 O1 UPD.0( O: salar, O< emplo,ees :O1 (.%9 1O> >9(< H<(>)3obLid Z SS.L1(PSI 6( I< I: I<S(10I< 09(< :<(>)commissionLpct :Z 'R (LSI: :OLD)commissionLpct IS <ULL 09(< :<(>)commissionLpct :Z 'R (LS( :<(>)commissionLpct :Z :OLD)commissionLpctN')'+R (<D I:R (<DR /

%op,rig/t @ &''"A Oracle) .ll rig/ts reserved)

1estricting a 1o2 0rigger: (Cample Optionall,A ,ou can include a trigger restriction in t/e deBinition oB a ro2 trigger b, speciB,ing a 6oolean SQL eCpression in a >9(< clause) IB ,ou include a >9(< clause in t/e triggerA t/en t/e eCpression in t/e >9(< clause is evaluated Bor eac/ ro2 t/at t/e trigger aBBects) IB t/e eCpression evaluates to 01U( Bor a ro2A t/en t/e trigger bod, eCecutes on be/alB oB t/at ro2) 9o2everA iB t/e eCpression evaluates to :.LS( or <O0 01U( Bor a ro2 Hun5no2nA as 2it/ nullsIA t/en t/e trigger bod, does not eCecute Bor t/at ro2) 0/e evaluation oB t/e >9(< clause does not /ave an eBBect on t/e eCecution oB t/e triggering SQL statement Hin ot/er 2ordsA t/e triggering statement is not rolled bac5 iB t/e eCpression in a >9(< clause evaluates to :.LS(I) <ote: . >9(< clause cannot be included in t/e deBinition oB a statement trigger) In t/e eCample in t/e slideA a trigger is created on t/e (=PLO8((S table to calculate an emplo,eeFs commission 2/en a ro2 is added to t/e (=PLO8((S tableA or 2/en an emplo,eeFs salar, is modiBied) 0/e <(> PualiBier cannot be preBiCed 2it/ a colon in t/e >9(< clause because t/e >9(< clause is outside t/e PL/SQL bloc5s)

c ra O l, - On

, em ad .c

ra c O

le

l ae rn Uste

Oracle Database 11g: Develop PL/SQL Program Units # E &*

In

Summar, oB t/e 0rigger (Cecution =odel


1) (Cecute all 6(:O1( S0.0(=(<0 triggers) &) Loop Bor eac/ ro2 aBBected b, t/e SQL statement:
a) (Cecute all 6(:O1( 1O> triggers Bor t/at ro2) b) (Cecute t/e D=L statement and perBorm integrit, constraint c/ec5ing Bor t/at ro2) c) (Cecute all .:0(1 1O> triggers Bor t/at ro2)

*) (Cecute all .:0(1 S0.0(=(<0 triggers)

%op,rig/t @ &''"A Oracle) .ll rig/ts reserved)

0rigger (Cecution =odel . single D=L statement can potentiall, Bire up to Bour t,pes oB triggers: 6(:O1( and .:0(1 statement triggers 6(:O1( and .:0(1 ro2 triggers

. triggering event or a statement 2it/in t/e trigger can cause one or more integrit, constraints to be c/ec5ed) 9o2everA ,ou can deBer constraint c/ec5ing until a %O==I0 operation is perBormed) 0riggers can also cause ot/er triggersU5no2n as cascading triggersUto Bire) .ll actions and c/ec5s perBormed as a result oB a SQL statement must succeed) IB an eCception is raised 2it/in a trigger and t/e eCception is not eCplicitl, /andledA t/en all actions perBormed because oB t/e original SQL statement are rolled bac5 Hincluding actions perBormed b, Biring triggersI) 0/is guarantees t/at integrit, constraints can never be compromised b, triggers) >/en a trigger BiresA t/e tables reBerenced in t/e trigger action ma, undergo c/anges b, ot/er usersF transactions) In all casesA a readEconsistent image is guaranteed Bor t/e modiBied values t/at t/e trigger needs to read HPuer,I or 2rite HupdateI) <ote: Integrit, c/ec5ing can be deBerred until t/e %O==I0 operation is perBormed)

c ra O l, - On

, em ad .c

ra c O

le

l ae rn Uste

Oracle Database 11g: Develop PL/SQL Program Units # E &!

In

Implementing an Integrit, %onstraint 2it/ an .Bter 0rigger


EE Integrit, constraint violation error M&""1 raised) UPD.0( emplo,ees S(0 departmentLid Z """ >9(1( emplo,eeLid Z 1G'R %1(.0( O1 1(PL.%( 01I (1 emplo,eeLdeptLB5Ltrg .:0(1 UPD.0( O: departmentLid O< emplo,ees :O1 (.%9 1O> 6( I< I<S(10 I<0O departments V.LU(SH:ne2)departmentLidA SDept STT:ne2)departmentLidA <ULLA <ULLIR (O%(P0IO< >9(< DUPLV.LLO<LI<D(O 09(< <ULLR EE mas5 eCception iB department eCists (<DR /

EE SuccessBul aBter trigger is Bired UPD.0( emplo,ees S(0 departmentLid Z """ >9(1( emplo,eeLid Z 1G'R

%op,rig/t @ &''"A Oracle) .ll rig/ts reserved)

Implementing an Integrit, %onstraint 2it/ an .Bter 0rigger 0/e eCample in t/e slide eCplains a situation in 2/ic/ t/e integrit, constraint can be ta5en care oB b, using an .:0(1 trigger) 0/e (=PLO8((S table /as a Boreign 5e, constraint on t/e D(P.10=(<0LID column oB t/e D(P.10=(<0S table) In t/e Birst SQL statementA t/e D(P.10=(<0LID oB t/e emplo,ee 1G' is modiBied to """) 6ecause department """ does not eCist in t/e D(P.10=(<0S tableA t/e statement raises eCception M&&"1 Bor t/e integrit, constraint violation) 0/e (=PLO8((LD(P0L:?L01 trigger is created and it inserts a ne2 ro2 into t/e D(P.10=(<0S table b, using :<(>)D(P.10=(<0LID Bor t/e value oB t/e ne2 departmentFs D(P.10=(<0LID) 0/e trigger Bires 2/en t/e UPD.0( statement modiBies t/e D(P.10=(<0LID oB emplo,ee 1G' to """) >/en t/e Boreign 5e, constraint is c/ec5edA it is successBul because t/e trigger inserted t/e department """ into t/e D(P.10=(<0S table) 0/ereBoreA no eCception occurs unless t/e department alread, eCists 2/en t/e trigger attempts to insert t/e ne2 ro2) 9o2everA t/e (O%(P0IO< /andler traps and mas5s t/e eCception allo2ing t/e operation to succeed) <ote: .lt/oug/ t/e eCample s/o2n in t/e slide is some2/at contrived due to t/e limited data in t/e 91 sc/emaA t/e point is t/at iB ,ou deBer t/e constraint c/ec5 until t/e commitA ,ou t/en /ave t/e abilit, to engineer a trigger to detect t/at constraint Bailure and repair it prior to t/e commit action)

c ra O l, - On

, em ad .c

ra c O

le

l ae rn Uste

Oracle Database 11g: Develop PL/SQL Program Units # E &+

In

I<S0(.D O: 0riggers

.pplication

I<S(10 I<0O m,Lvie2 )))R


I<S(10 0.6L( 1

I<S0(.D O: trigger UPD.0( =8LVI(>

%op,rig/t @ &''"A Oracle) .ll rig/ts reserved)

I<S0(.D O: 0riggers Use I<S0(.D O: triggers to modiB, data in 2/ic/ t/e D=L statement /as been issued against an in/erentl, unEupdatable vie2) 0/ese triggers are called I<S0(.D O: triggers becauseA unli5e ot/er triggersA t/e Oracle server Bires t/e trigger instead oB eCecuting t/e triggering statement) 0/ese triggers are used to perBorm I<S(10A UPD.0(A and D(L(0( operations directl, on t/e underl,ing tables) 8ou can 2rite I<S(10A UPD.0(A and D(L(0( statements against a vie2A and t/e I<S0(.D O: trigger 2or5s invisibl, in t/e bac5ground to ma5e t/e rig/t actions ta5e place) . vie2 cannot be modiBied b, normal D=L statements iB t/e vie2 Puer, contains set operatorsA group BunctionsA clauses suc/ as 1OUP 68A %O<<(%0 68A S0.10A t/e DIS0I<%0 operatorA or 3oins) :or eCampleA iB a vie2 consists oB more t/an one tableA an insert to t/e vie2 ma, entail an insertion into one table and an update to anot/er) So ,ou 2rite an I<S0(.D O: trigger t/at Bires 2/en ,ou 2rite an insert against t/e vie2) Instead oB t/e original insertionA t/e trigger bod, eCecutesA 2/ic/ results in an insertion oB data into one table and an update to anot/er table) <ote: IB a vie2 is in/erentl, updatable and /as I<S0(.D O: triggersA t/en t/e triggers ta5e precedence) I<S0(.D O: triggers are ro2 triggers) 0/e %9(%? option Bor vie2s is not enBorced 2/en insertions or updates to t/e vie2 are perBormed b, using I<S0(.D O: triggers) 0/e I<S0(.D O: trigger bod, must enBorce t/e c/ec5)

c ra O l, - On

, em ad .c
0.6L( &

ra c O

le

l ae rn Uste

Oracle Database 11g: Develop PL/SQL Program Units # E &$

In

%reating an I<S0(.D O: 0rigger: (Cample


I<S(10 I<0O empLdetails V.LU(S H"''1AS.66O00SA*'''A 1'A S.dministrationSIR

&

I<S0(.D O: I<S(10 into (=PLD(0.ILS

I<S(10 into <(>L(=PS table

*
(=PLD(0.ILS vie2

UPD.0( <(>LD(P0S table

%op,rig/t @ &''"A Oracle) .ll rig/ts reserved)

%reating an I<S0(.D O: 0rigger 8ou can create an I<S0(.D O: trigger in order to maintain t/e base tables on 2/ic/ a vie2 is based) 0/e eCample in t/e slide illustrates an emplo,ee being inserted into t/e vie2 (=PLD(0.ILSA 2/ose Puer, is based on t/e (=PLO8((S and D(P.10=(<0S tables) 0/e <(>L(=PLD(P0 HI<S0(.D O:I trigger eCecutes in place oB t/e I<S(10 operation t/at causes t/e trigger to Bire) 0/e I<S0(.D O: trigger t/en issues t/e appropriate I<S(10 and UPD.0( to t/e base tables used b, t/e (=PLD(0.ILS vie2) 0/ereBoreA instead oB inserting t/e ne2 emplo,ee record into t/e (=PLO8((S tableA t/e Bollo2ing actions ta5e place: 1) 0/e <(>L(=PLD(P0 I<S0(.D O: trigger Bires) &) . ro2 is inserted into t/e <(>L(=PS table) *) 0/e D(P0LS.L column oB t/e <(>LD(P0S table is updated) 0/e salar, value supplied Bor t/e ne2 emplo,ee is added to t/e eCisting total salar, oB t/e department to 2/ic/ t/e ne2 emplo,ee /as been assigned) <ote: 6eBore ,ou run t/e eCample in t/e slideA ,ou must create t/e rePuired structures s/o2n on t/e neCt t2o pages)

c ra O l, - On

, em ad .c

ra c O

le

l ae rn Uste

Oracle Database 11g: Develop PL/SQL Program Units # E &G

In

%reating an I<S0(.D O: 0rigger to PerBorm D=L on %ompleC Vie2s


%1(.0( 0.6L( ne2Lemps .S S(L(%0 emplo,eeLidAlastLnameAsalar,AdepartmentLid :1O= emplo,eesR %1(.0( 0.6L( ne2Ldepts .S S(L(%0 d)departmentLidAd)departmentLnameA sumHe)salar,I deptLsal :1O= emplo,ees eA departments d >9(1( e)departmentLid Z d)departmentLidR

%1(.0( VI(> empLdetails .S S(L(%0 e)emplo,eeLidA e)lastLnameA e)salar,A e)departmentLidA d)departmentLname :1O= emplo,ees eA departments d >9(1( e)departmentLid Z d)departmentLid 1OUP 68 d)departmentLidAd)departmentLnameR

%op,rig/t @ &''"A Oracle) .ll rig/ts reserved)

%reating an I<S0(.D O: 0rigger HcontinuedI 0/e eCample in t/e slide creates t2o ne2 tablesA <(>L(=PS and <(>LD(P0SA t/at are based on t/e (=PLO8((S and D(P.10=(<0S tablesA respectivel,) It also creates an (=PLD(0.ILS vie2 Brom t/e (=PLO8((S and D(P.10=(<0S tables)

ra c O

IB a vie2 /as a compleC Puer, structureA t/en it is not al2a,s possible to perBorm D=L directl, on t/e vie2 to aBBect t/e underl,ing tables) 0/e eCample rePuires creation oB an I<S0(.D O: triggerA called <(>L(=PLD(P0A s/o2n on t/e neCt page) 0/e <(>LD(P0L(=P trigger /andles D=L in t/e Bollo2ing 2a,: >/en a ro2 is inserted into t/e (=PLD(0.ILS vie2A instead oB inserting t/e ro2 directl, into t/e vie2A ro2s are added into t/e <(>L(=PS and <(>LD(P0S tablesA using t/e data values supplied 2it/ t/e I<S(10 statement) >/en a ro2 is modiBied or deleted t/roug/ t/e (=PLD(0.ILS vie2A corresponding ro2s in t/e <(>L(=PS and <(>LD(P0S tables are aBBected) <ote: I<S0(.D O: triggers can be 2ritten onl, Bor vie2sA and t/e 6(:O1( and .:0(1 timing options are not valid)

c ra O l, - On

, em ad .c

le

l ae rn Uste

Oracle Database 11g: Develop PL/SQL Program Units # E &#

In

%reating an I<S0(.D O: 0rigger HcontinuedI


%1(.0( O1 1(PL.%( 01I (1 ne2LempLdept I<S0(.D O: I<S(10 O1 UPD.0( O1 D(L(0( O< empLdetails :O1 (.%9 1O> 6( I< I: I<S(10I< 09(< I<S(10 I<0O ne2Lemps V.LU(S H:<(>)emplo,eeLidA :<(>)lastLnameA :<(>)salar,A :<(>)departmentLidIR UPD.0( ne2Ldepts S(0 deptLsal Z deptLsal N :<(>)salar, >9(1( departmentLid Z :<(>)departmentLidR (LSI: D(L(0I< 09(< D(L(0( :1O= ne2Lemps >9(1( emplo,eeLid Z :OLD)emplo,eeLidR UPD.0( ne2Ldepts S(0 deptLsal Z deptLsal E :OLD)salar, >9(1( departmentLid Z :OLD)departmentLidR (LSI: UPD.0I< HSsalar,SI 09(< UPD.0( ne2Lemps S(0 salar, Z :<(>)salar, >9(1( emplo,eeLid Z :OLD)emplo,eeLidR UPD.0( ne2Ldepts S(0 deptLsal Z deptLsal N H:<(>)salar, E :OLD)salar,I >9(1( departmentLid Z :OLD)departmentLidR (LSI: UPD.0I< HSdepartmentLidSI 09(< UPD.0( ne2Lemps S(0 departmentLid Z :<(>)departmentLid >9(1( emplo,eeLid Z :OLD)emplo,eeLidR UPD.0( ne2Ldepts S(0 deptLsal Z deptLsal E :OLD)salar, >9(1( departmentLid Z :OLD)departmentLidR UPD.0( ne2Ldepts S(0 deptLsal Z deptLsal N :<(>)salar, >9(1( departmentLid Z :<(>)departmentLidR (<D I:R (<DR /

c ra O l, - On

, em ad .c

ra c O

le In

l ae rn Uste

Oracle Database 11g: Develop PL/SQL Program Units # E &"

0/e Status oB a 0rigger


. trigger is in eit/er oB t2o distinct modes: (nabled: 0/e trigger runs its trigger action iB a triggering statement is issued and t/e trigger restriction HiB an,I evaluates to true HdeBaultI) Disabled: 0/e trigger does not run its trigger actionA even iB a triggering statement is issued and t/e trigger restriction HiB an,I 2ould evaluate to true)

%op,rig/t @ &''"A Oracle) .ll rig/ts reserved)

l c ra O l, - On ra c O le In l ae rn Uste e

, em ad .c

Oracle Database 11g: Develop PL/SQL Program Units # E *'

%reating a Disabled 0rigger


6eBore Oracle Database 11gA iB ,ou created a trigger 2/ose bod, /ad a PL/SQL compilation errorA t/en D=L to t/e table Bailed) In Oracle Database 11gA ,ou can create a disabled trigger and t/en enable it onl, 2/en ,ou 5no2 it 2ill be compiled successBull,)

%1(.0( O1 1(PL.%( 01I (1 m,trg 6(:O1( I<S(10 O< m,table :O1 (.%9 1O> DIS.6L( 6( I< :<e2)ID :Z m,LseP)<eCtvalR ))) (<DR /

%op,rig/t @ &''"A Oracle) .ll rig/ts reserved)

%reating a Disabled 0rigger 6eBore Oracle Database 11gA iB ,ou created a trigger 2/ose bod, /ad a PL/SQL compilation errorA t/en D=L to t/e table Bailed) 0/e Bollo2ing error message 2as displa,ed: O1.E'!'"#: trigger S01 S is invalid and Bailed reEvalidation

In Oracle Database 11gA ,ou can create a disabled triggerA and t/en enable it onl, 2/en ,ou 5no2 it 2ill be compiled successBull,) 8ou can also temporaril, disable a trigger in t/e Bollo2ing situations: .n ob3ect it reBerences is not available) 8ou need to perBorm a large data loadA and ,ou 2ant it to proceed Puic5l, 2it/out Biring triggers) 8ou are reloading data) <ote: 0/e code eCample in t/e slide assumes t/at ,ou /ave an eCisting sePuence named m,LseP)

c ra O l, - On

, em ad .c

ra c O

le

l ae rn Uste

Oracle Database 11g: Develop PL/SQL Program Units # E *1

In

=anaging 0riggers Using t/e .L0(1 and D1OP SQL Statements


EE Disable or reenable a database trigger: .L0(1 01I (1 triggerLname DIS.6L( T (<.6L(R

EE Disable or reenable all triggers Bor a table: .L0(1 0.6L( tableLname DIS.6L( T (<.6L( .LL 01I EE 1ecompile a trigger Bor a table: .L0(1 01I (1 triggerLname %O=PIL(R (1SR

EE 1emove a trigger Brom t/e database: D1OP 01I (1 triggerLnameR

%op,rig/t @ &''"A Oracle) .ll rig/ts reserved)

=anaging 0riggers . trigger /as t2o modes or states: (<.6L(D and DIS.6L(D) >/en a trigger is Birst createdA it is enabled b, deBault) 0/e Oracle server c/ec5s integrit, constraints Bor enabled triggers and guarantees t/at triggers cannot compromise t/em) In additionA t/e Oracle server provides readE consistent vie2s Bor Pueries and constraintsA manages t/e dependenciesA and provides a t2oE p/ase commit process iB a trigger updates remote tables in a distributed database) Disabling a 0rigger Use t/e .L0(1 01I (1 command to disable a trigger) 8ou can also disable all triggers on a table b, using t/e .L0(1 0.6L( command) 8ou can disable triggers to improve perBormance or to avoid data integrit, c/ec5s 2/en loading massive amounts oB data 2it/ utilities suc/ as SQLKLoader) 8ou mig/t also disable a trigger 2/en it reBerences a database ob3ect t/at is currentl, unavailableA due to a Bailed net2or5 connectionA dis5 cras/A oBBline data BileA or oBBline tablespace) 1ecompiling a 0rigger Use t/e .L0(1 01I (1 command to eCplicitl, recompile a trigger t/at is invalid) 1emoving 0riggers >/en a trigger is no longer rePuiredA use a SQL statement in SQL Developer or SQLKPlus to remove it) >/en ,ou remove a tableA all triggers on t/at table are also removed)

c ra O l, - On

, em ad .c

ra c O

le

l ae rn Uste

Oracle Database 11g: Develop PL/SQL Program Units # E *&

In

=anaging 0riggers Using SQL Developer

%op,rig/t @ &''"A Oracle) .ll rig/ts reserved)

=anaging 0riggers Using SQL Developer 8ou can use t/e 0riggers node in t/e %onnections navigation tree to manage triggers) 1ig/tE clic5 a trigger nameA and t/en select one oB t/e Bollo2ing options: (dit %ompile %ompile Bor Debug 1ename Drop 0rigger (nable Disable

c ra O l, - On

, em ad .c

ra c O

le In

l ae rn Uste

Oracle Database 11g: Develop PL/SQL Program Units # E **

0esting 0riggers
0est eac/ triggering data operationA as 2ell as nonE triggering data operations) 0est eac/ case oB t/e >9(< clause) %ause t/e trigger to Bire directl, Brom a basic data operationA as 2ell as indirectl, Brom a procedure) 0est t/e eBBect oB t/e trigger on ot/er triggers) 0est t/e eBBect oB ot/er triggers on t/e trigger)

%op,rig/t @ &''"A Oracle) .ll rig/ts reserved)

0esting 0riggers 0esting code can be a timeEconsuming process) Do t/e Bollo2ing 2/en testing triggers: (nsure t/at t/e trigger 2or5s properl, b, testing a number oB cases separatel,: E 0est t/e most common success scenarios Birst) E 0est t/e most common Bailure conditions to see t/at t/e, are properl, managed) 0/e more compleC t/e triggerA t/e more detailed ,our testing is li5el, to be) :or eCampleA iB ,ou /ave a ro2 trigger 2it/ a >9(< clause speciBiedA t/en ,ou s/ould ensure t/at t/e trigger Bires 2/en t/e conditions are satisBied) OrA iB ,ou /ave cascading triggersA ,ou need to test t/e eBBect oB one trigger on t/e ot/er and ensure t/at ,ou end up 2it/ t/e desired results) Use t/e D6=SLOU0PU0 pac5age to debug triggers)

c ra O l, - On

, em ad .c

ra c O

le In

l ae rn Uste

Oracle Database 11g: Develop PL/SQL Program Units # E *!

Vie2ing 0rigger InBormation


8ou can vie2 t/e Bollo2ing trigger inBormation:

Data Dictionar, Vie2


US(1LO6;(%0S US(1/.LL/D6.L01I US(1L(11O1S (1S

Description
Displa,s ob3ect inBormation Displa,s trigger inBormation Displa,s PL/SQL s,ntaC errors Bor a trigger

%op,rig/t @ &''"A Oracle) .ll rig/ts reserved)

Vie2ing 0rigger InBormation 0/e slide s/o2s t/e data dictionar, vie2s t/at ,ou can access to get inBormation regarding t/e triggers) 0/e US(1LO6;(%0S vie2 contains t/e name and status oB t/e trigger and t/e date and time 2/en t/e trigger 2as created) 0/e US(1L(11O1S vie2 contains t/e details about t/e compilation errors t/at occurred 2/ile a trigger 2as compiling) 0/e contents oB t/ese vie2s are similar to t/ose Bor subprograms) 0/e US(1L01I (1S vie2 contains details suc/ as nameA t,peA triggering eventA t/e table on 2/ic/ t/e trigger is createdA and t/e bod, oB t/e trigger) 0/e S(L(%0 Username :1O= US(1LUS(1SR statement gives t/e name oB t/e o2ner oB t/e triggerA not t/e name oB t/e user 2/o is updating t/e table)

c ra O l, - On

, em ad .c

ra c O

le In

l ae rn Uste

Oracle Database 11g: Develop PL/SQL Program Units # E *+

Using US(1L01I
D(S%1I6( userLtriggers

(1S

S(L(%0 triggerLt,peA triggerLbod, :1O= userLtriggers >9(1( triggerLname Z SS(%U1(L(=PSR

%op,rig/t @ &''"A Oracle) .ll rig/ts reserved)

Using US(1L01I

(1S

l c ra O l, - On e

IB t/e source Bile is unavailableA t/en ,ou can use t/e SQL >or5s/eet in SQL Developer or SQLKPlus to regenerate it Brom US(1L01I (1S) 8ou can also eCamine t/e .LLL01I (1S and D6.L01I (1S vie2sA eac/ oB 2/ic/ contains t/e additional column O><(1A Bor t/e o2ner oB t/e ob3ect) 0/e result Bor t/e second eCample in t/e slide is as Bollo2s:

, em ad .c

ra c O

le In

l ae rn Uste

Oracle Database 11g: Develop PL/SQL Program Units # E *$

Qui4
. triggering event can be one or more oB t/e Bollo2ing: 1) .n I<S(10A UPD.0(A or D(L(0( statement on a speciBic table Hor vie2A in some casesI &) . %1(.0(A .L0(1A or D1OP statement on an, sc/ema ob3ect *) . database startup or instance s/utdo2n !) . speciBic error message or an, error message +) . user logon or logoBB

%op,rig/t @ &''"A Oracle) .ll rig/ts reserved)

.ns2ers: 1A &A *A !A +

l c ra O l, - On e

, em ad .c

ra c O

le In

l ae rn Uste

Oracle Database 11g: Develop PL/SQL Program Units # E *G

Summar,
In t/is lessonA ,ou s/ould /ave learned /o2 to: %reate database triggers t/at are invo5ed b, D=L operations %reate statement and ro2 trigger t,pes Use database triggerEBiring rules (nableA disableA and manage database triggers Develop a strateg, Bor testing triggers 1emove database triggers

%op,rig/t @ &''"A Oracle) .ll rig/ts reserved)

Summar, 0/is lesson covered creating database triggers t/at eCecute beBoreA aBterA or instead oB a speciBied D=L operation) 0riggers are associated 2it/ database tables or vie2s) 0/e 6(:O1( and .:0(1 timings appl, to D=L operations on tables) 0/e I<S0(.D O: trigger is used as a 2a, to replace D=L operations on a vie2 2it/ appropriate D=L statements against ot/er tables in t/e database) 0riggers are enabled b, deBault but can be disabled to suppress t/eir operation until enabled again) IB business rules c/angeA triggers can be removed or altered as rePuired)

c ra O l, - On

, em ad .c

ra c O

le In

l ae rn Uste

Oracle Database 11g: Develop PL/SQL Program Units # E *#

Practice # Overvie2: %reating Statement and 1o2 0riggers


0/is practice covers t/e Bollo2ing topics: %reating ro2 triggers %reating a statement trigger %alling procedures Brom a trigger

%op,rig/t @ &''"A Oracle) .ll rig/ts reserved)

Practice #: Overvie2 In t/is practiceA ,ou create statement and ro2 triggers) 8ou also create procedures t/at are invo5ed Brom 2it/in t/e triggers)

c ra O l, - On

, em ad .c

ra c O

le In

l ae rn Uste

Oracle Database 11g: Develop PL/SQL Program Units # E *"

l c ra O l, - On ra c O le In l ae rn Uste e

, em ad .c

%reating %ompoundA DDLA and (vent Database 0riggers

%op,rig/t @ &''"A Oracle) .ll rig/ts reserved)

l c ra O l, - On ra c O le In l ae rn Uste e

, em ad .c

Ob3ectives
.Bter completing t/is lessonA ,ou s/ould be able to do t/e Bollo2ing: Describe compound triggers Describe mutating tables %reate triggers on DDL statements %reate triggers on s,stem events Displa, inBormation about triggers

%op,rig/t @ &''"A Oracle) .ll rig/ts reserved)

Lesson .im In t/is lessonA ,ou learn /o2 to create and use database triggers)

c ra O l, - On

, em ad .c

ra c O

le In

l ae rn Uste

Oracle Database 11g: Develop PL/SQL Program Units " E &

>/at Is a %ompound 0riggerJ


. single trigger on a table t/at allo2s ,ou to speciB, actions Bor eac/ oB t/e Bollo2ing Bour timing points: 6eBore t/e Biring statement 6eBore eac/ ro2 t/at t/e Biring statement aBBects .Bter eac/ ro2 t/at t/e Biring statement aBBects .Bter t/e Biring statement

%op,rig/t @ &''"A Oracle) .ll rig/ts reserved)

>/at Is a %ompound 0riggerJ Starting 2it/ Oracle Database 11gA ,ou can use a compound trigger) . compound trigger is a single trigger on a table t/at allo2s ,ou to speciB, actions Bor eac/ oB t/e Bour triggering timing points: 6eBore t/e Biring statement 6eBore eac/ ro2 t/at t/e Biring statement aBBects .Bter eac/ ro2 t/at t/e Biring statement aBBects .Bter t/e Biring statement <ote: :or additional inBormation about triggersA reBer to t/e Oracle Database PL/SQL Language 1eBerence 11g 1elease & H11)&I)

c ra O l, - On

, em ad .c

ra c O

le In

l ae rn Uste

Oracle Database 11g: Develop PL/SQL Program Units " E *

>or5ing 2it/ %ompound 0riggers


0/e compound trigger bod, supports a common PL/SQL state t/at t/e code Bor eac/ timing point can access) 0/e compound trigger common state is:
M (stablis/ed 2/en t/e triggering statement starts M Destro,ed 2/en t/e triggering statement completes

. compound trigger /as a declaration section and a section Bor eac/ oB its timing points)

%op,rig/t @ &''"A Oracle) .ll rig/ts reserved)

>or5ing 2it/ %ompound 0riggers 0/e compound trigger bod, supports a common PL/SQL state t/at t/e code Bor eac/ timing point can access) 0/e common state is automaticall, destro,ed 2/en t/e Biring statement completesA even 2/en t/e Biring statement causes an error) 8our applications can avoid t/e mutating table error b, allo2ing ro2s destined Bor a second table Hsuc/ as a /istor, table or an audit tableI to accumulate and t/en bul5Einserting t/em) 6eBore Oracle Database 11g 1elease 1 H11)1IA ,ou needed to model t/e common state 2it/ an ancillar, pac5age) 0/is approac/ 2as bot/ cumbersome to program and sub3ect to memor, lea5 2/en t/e Biring statement caused an error and t/e aBterEstatement trigger did not Bire) %ompound triggers ma5e PL/SQL easier Bor ,ou to use and improve runEtime perBormance and scalabilit,)

c ra O l, - On

, em ad .c

ra c O

le In

l ae rn Uste

Oracle Database 11g: Develop PL/SQL Program Units " E !

0/e 6eneBits oB Using a %ompound 0rigger


8ou can use compound triggers to: Program an approac/ 2/ere ,ou 2ant t/e actions ,ou implement Bor t/e various timing points to s/are common data) .ccumulate ro2s destined Bor a second table so t/at ,ou can periodicall, bul5Einsert t/em .void t/e mutatingEtable error HO1.E'!'"1Ib, allo2ing ro2s destined Bor a second table to accumulate and t/en bul5Einserting t/em

%op,rig/t @ &''"A Oracle) .ll rig/ts reserved)

l c ra O l, - On ra c O le In l ae rn Uste e

, em ad .c

Oracle Database 11g: Develop PL/SQL Program Units " E +

0imingEPoint Sections oB a 0able %ompound 0rigger


. compound trigger deBined on a table /as one or more oB t/e Bollo2ing timingEpoint sections) 0imingEpoint sections must appear in t/e order s/o2n in t/e table)

0iming Point
6eBore t/e triggering statement eCecutes .Bter t/e triggering statement eCecutes 6eBore eac/ ro2 t/at t/e triggering statement aBBects .Bter eac/ ro2 t/at t/e triggering statement aBBects

%ompound 0rigger Section


6(:O1( statement .:0(1 statement 6(:O1( (.%9 1O> .:0(1 (.%9 1O>

%op,rig/t @ &''"A Oracle) .ll rig/ts reserved)

<ote 0imingEpoint sections must appear in t/e order s/o2n in t/e slide) IB a timingEpoint section is absentA not/ing /appens at its timing point)

c ra O l, - On

, em ad .c

ra c O

le In

l ae rn Uste

Oracle Database 11g: Develop PL/SQL Program Units " E $

%ompound 0rigger Structure Bor 0ables


%1(.0( O1 1(PL.%( 01I (1 sc/ema)trigger :O1 dmlLeventLclause O< sc/ema)table %O=POU<D 01I (1 EE Initial section EE Declarations EE Subprograms

EE Optional section 6(:O1( S0.0(=(<0 IS )))R

EE Optional section .:0(1 S0.0(=(<0 IS )))R EE Optional section 6(:O1( (.%9 1O> IS )))R EE Optional section .:0(1 (.%9 1O> IS )))R

&

%op,rig/t @ &''"A Oracle) .ll rig/ts reserved)

%ompound 0rigger Structure Bor 0ables . compound trigger /as t2o main sections: .n initial section 2/ere variables and subprograms are declared) 0/e code in t/is section eCecutes beBore an, oB t/e code in t/e optional section) .n optional section t/at deBines t/e code Bor eac/ possible trigger point) Depending on 2/et/er ,ou are deBining a compound trigger Bor a table or Bor a vie2A t/ese triggering points are diBBerent and are listed in t/e image s/o2n above and on t/e Bollo2ing page) 0/e code Bor t/e triggering points must Bollo2 t/e order s/o2n above) <ote: :or additional inBormation about %ompound 0riggersA reBer to t/e Oracle Database PL/SQL Language 1eBerence 11g 1elease & H11)&I guide)

c ra O l, - On

, em ad .c

ra c O

le In

l ae rn Uste

Oracle Database 11g: Develop PL/SQL Program Units " E G

%ompound 0rigger Structure Bor Vie2s

%1(.0( O1 1(PL.%( 01I sc/ema)trigger

(1

:O1 dmlLeventLclause O< sc/ema)vie2 %O=POU<D 01I EE Initial section EE Declarations EE Subprograms (1

EE Optional section HeCclusiveI I<S0(.D O: (.%9 1O> IS )))R

%op,rig/t @ &''"A Oracle) .ll rig/ts reserved)

%ompound 0rigger Structure Bor Vie2s >it/ vie2sA t/e onl, allo2ed section is an I<S0(.D O: (.%9 1O> clause)

c ra O l, - On

, em ad .c

ra c O

le In

l ae rn Uste

Oracle Database 11g: Develop PL/SQL Program Units " E #

%ompound 0rigger 1estrictions


0/e Biring order oB compound triggers is not guaranteed unless ,ou use t/e :OLLO>S clause) . compound trigger must be a D=L trigger and deBined on eit/er a table or a vie2) 0/e bod, oB a compound trigger must be compound trigger bloc5A 2ritten in PL/SQL) . compound trigger bod, cannot /ave an initiali4ation bloc5R t/ereBoreA it cannot /ave an eCception section) .n eCception t/at occurs in one section must be /andled in t/at section) It cannot transBer control to anot/er section) :OLD and :<(> cannot appear in t/e declarationA 6(:O1( S0.0(=(<0A or t/e .:0(1 S0.0(=(<0 sections) Onl, t/e 6(:O1( (.%9 1O> section can c/ange t/e value oB :<(>)

%op,rig/t @ &''"A Oracle) .ll rig/ts reserved)

%ompound 0rigger 1estrictions 0/e Bollo2ing are some oB t/e restrictions 2/en 2or5ing 2it/ compound triggers: 0/e bod, oB a compound trigger must compound trigger bloc5A 2ritten in PL/SQL) . compound trigger must be a D=L trigger) . compound trigger must be deBined on eit/er a table or a vie2) . compound trigger bod, cannot /ave an initiali4ation bloc5R t/ereBoreA it cannot /ave an eCception section) 0/is is not a problemA because t/e 6(:O1( S0.0(=(<0 section al2a,s eCecutes eCactl, once beBore an, ot/er timingEpoint section eCecutes) .n eCception t/at occurs in one section must be /andled in t/at section) It cannot transBer control to anot/er section) :OLDA :<(>A and :P.1(<0 cannot appear in t/e declaration sectionA t/e 6(:O1( S0.0(=(<0 sectionA or t/e .:0(1 S0.0(=(<0 section) 0/e Biring order oB compound triggers is not guaranteed unless ,ou use t/e :OLLO>S clause)

c ra O l, - On

, em ad .c

ra c O

le

l ae rn Uste

Oracle Database 11g: Develop PL/SQL Program Units " E "

In

0rigger 1estrictions on =utating 0ables


. mutating table is:
M . table t/at is being modiBied b, an UPD.0(A D(L(0(A or I<S(10 statementA or M . table t/at mig/t be updated b, t/e eBBects oB a D(L(0( %.S%.D( constraint

0/e session t/at issued t/e triggering statement cannot Puer, or modiB, a mutating table) 0/is restriction prevents a trigger Brom seeing an inconsistent set oB data) 0/is restriction applies to all triggers t/at use t/e :O1 (.%9 1O> clause) Vie2s being modiBied in t/e I<S0(.D O: triggers are not considered mutating)

%op,rig/t @ &''"A Oracle) .ll rig/ts reserved)

1ules overning 0riggers 1eading and 2riting data using triggers is sub3ect to certain rules) 0/e restrictions appl, onl, to ro2 triggersA unless a statement trigger is Bired as a result oB O< D(L(0( %.S%.D()

=utating 0able . mutating table is a table t/at is currentl, being modiBied b, an UPD.0(A D(L(0(A or I<S(10 statementA or a table t/at mig/t need to be updated b, t/e eBBects oB a declarative D(L(0( %.S%.D( reBerential integrit, action) :or S0.0(=(<0 triggersA a table is not considered a mutating table) . mutating table error HO1.E!'"1I occurs 2/en a ro2Elevel trigger attempts to c/ange or eCamine a table t/at is alread, undergoing c/ange via a D=L statement) 0/e triggered table itselB is a mutating tableA as 2ell as an, table reBerencing it 2it/ t/e :O1(I < ?(8 constraint) 0/is restriction prevents a ro2 trigger Brom seeing an inconsistent set oB data)

c ra O l, - On

, em ad .c

ra c O

le

l ae rn Uste

Oracle Database 11g: Develop PL/SQL Program Units " E 1'

In

=utating 0able: (Cample

%1(.0( O1 1(PL.%( 01I (1 c/ec5Lsalar, 6(:O1( I<S(10 O1 UPD.0( O: salar,A 3obLid O< emplo,ees :O1 (.%9 1O> >9(< H<(>)3obLid ^\ S.DLP1(SSI D(%L.1( vLminsalar, emplo,ees)salar,Q08P(R vLmaCsalar, emplo,ees)salar,Q08P(R 6( I< S(L(%0 =I<Hsalar,IA =.OHsalar,I I<0OvLminsalar,A vLmaCsalar, :1O=emplo,ees >9(1( 3obLid Z :<(>)3obLidR I: :<(>)salar, ^ vLminsalar, O1 :<(>)salar, \ vLmaCsalar, 09(< 1.IS(L.PPLI%.0IO<L(11O1HE&'+'+ASOut oB rangeSIR (<D I:R (<DR /

%op,rig/t @ &''"A Oracle) .ll rig/ts reserved)

=utating 0able: (Cample 0/e %9(%?LS.L.18 trigger in t/e slide eCample attempts to guarantee t/at 2/enever a ne2 emplo,ee is added to t/e (=PLO8((S table or 2/enever an eCisting emplo,eeFs salar, or 3ob ID is c/angedA t/e emplo,eeFs salar, Balls 2it/in t/e establis/ed salar, range Bor t/e emplo,eeFs 3ob) >/en an emplo,ee record is updatedA t/e %9(%?LS.L.18 trigger is Bired Bor eac/ ro2 t/at is updated) 0/e trigger code Pueries t/e same table t/at is being updated) 0/ereBoreA it is said t/at t/e (=PLO8((S table is a mutating table)

c ra O l, - On

, em ad .c

ra c O

le In

l ae rn Uste

Oracle Database 11g: Develop PL/SQL Program Units " E 11

=utating 0able: (Cample

UPD.0( emplo,ees S(0 salar, Z *!'' >9(1( lastLname Z SStilesSR

%op,rig/t @ &''"A Oracle) .ll rig/ts reserved)

=utating 0able: (Cample HcontinuedI In t/e eCample in t/e slideA t/e trigger code tries to read or select data Brom a mutating table) IB ,ou restrict t/e salar, 2it/in a range bet2een t/e minimum eCisting value and t/e maCimum eCisting valueA t/en ,ou get a runEtime error) 0/e (=PLO8((S table is mutatingA or in a state oB c/angeR t/ereBoreA t/e trigger cannot read Brom it) 1emember t/at Bunctions can also cause a mutating table error 2/en t/e, are invo5ed in a D=L statement) Possible Solutions Possible solutions to t/is mutating table problem include t/e Bollo2ing: Use a compound trigger as described earlier in t/is lesson) Store t/e summar, data Ht/e minimum salaries and t/e maCimum salariesI in anot/er summar, tableA 2/ic/ is 5ept upEtoEdate 2it/ ot/er D=L triggers) Store t/e summar, data in a PL/SQL pac5ageA and access t/e data Brom t/e pac5age) 0/is can be done in a 6(:O1( statement trigger)

c ra O l, - On

, em ad .c

ra c O

le

Depending on t/e nature oB t/e problemA a solution can become more convoluted and diBBicult to solve) In t/is caseA consider implementing t/e rules in t/e application or middle tier and avoid using database triggers to perBorm overl, compleC business rules) .n insert statement in t/e code eCample in t/e slide 2ill not generate a mutating table eCample)
Oracle Database 11g: Develop PL/SQL Program Units " E 1&

l ae rn Uste

In

Using a %ompound 0rigger to 1esolve t/e =utating 0able (rror


%1(.0( O1 1(PL.%( 01I (1 c/ec5Lsalar, :O1 I<S(10 O1 UPD.0( O: salar,A 3obLid O< emplo,ees >9(< H<(>)3obLid ^\ S.DLP1(SSI %O=POU<D 01I (1

08P( salariesLt minLsalaries maCLsalaries 08P( departmentLidsLt departmentLids 08P( departmentLsalariesLt departmentLminLsalaries departmentLmaCLsalaries EE eCample continues on neCt slide

IS 0.6L( O: emplo,ees)salar,Q08P(R salariesLtR salariesLtR IS 0.6L( O: emplo,ees)departmentLidQ08P(R departmentLidsLtR IS 0.6L( O: emplo,ees)salar,Q08P( I<D(O 68 V.1%9.1&H#'IR departmentLsalariesLtR departmentLsalariesLtR

%op,rig/t @ &''"A Oracle) .ll rig/ts reserved)

Using a %ompound 0rigger to 1esolve t/e =utating 0able (rror 0/e %9(%?LS.L.18 compound trigger resolves t/e mutating table error in t/e earlier eCample) 0/is is ac/ieved b, storing t/e values in PL/SQL collectionsA and t/en perBorming a bul5 insert/update in t/e XbeBore statementY section oB t/e compound trigger) In t/e eCample in t/e slideA PL/SQL collections are used) 0/e element t,pes used are based on t/e S.L.18 and D(P.10=(<0LID columns Brom t/e (=PLO8((S table) 0o create collectionsA ,ou deBine a collection t,peA and t/en declare variables oB t/at t,pe) %ollections are instantiated 2/en ,ou enter a bloc5 or subprogramA and cease to eCist 2/en ,ou eCit) minLsalaries is used to /old t/e minimum salar, Bor eac/ department and maCLsalaries is used to /old t/e maCimum salar, Bor eac/ department) departmentLids is used to /old t/e department IDs) IB t/e emplo,ee 2/o earns t/e minimum or maCimum salar, does not /ave an assigned departmentA ,ou use t/e <VL Bunction to store M1 Bor t/e department id instead oB <ULL) <eCtA ,ou collect t/e minimum salar,A maCimum salar,A and t/e department ID using a bul5 insert into t/e minLsalariesA maCLsalariesA and departmentLids respectivel, grouped b, department ID) 0/e select statement returns 1* ro2s) 0/e values oB t/e departmentLids are used as an indeC Bor t/e departmentLminLsalaries and departmentLminLsalaries tables) 0/ereBoreA t/e indeC Bor t/ose t2o tables HV.1%9.1&I represents t/e actual departmentLids)

c ra O l, - On

, em ad .c

ra c O

le

l ae rn Uste

Oracle Database 11g: Develop PL/SQL Program Units " E 1*

In

Using a %ompound 0rigger to 1esolve t/e =utating 0able (rror


))) 6(:O1( S0.0(=(<0 IS 6( I< S(L(%0 =I<Hsalar,IA =.OHsalar,IA <VLHdepartmentLidA E1I 6UL? %OLL(%0 I<0O minLSalariesA maCLsalariesA departmentLids :1O=emplo,ees 1OUP 68 departmentLidR :O1 3 I< 1))departmentLids)%OU<0HI LOOP departmentLminLsalariesHdepartmentLidsH3II :Z minLsalariesH3IR departmentLmaCLsalariesHdepartmentLidsH3II :Z maCLsalariesH3IR (<D LOOPR (<D 6(:O1( S0.0(=(<0R

.:0(1 (.%9 1O> IS 6( I< I: :<(>)salar, ^ departmentLminLsalariesH:<(>)departmentLidI O1 :<(>)salar, \ departmentLmaCLsalariesH:<(>)departmentLidI 09(< 1.IS(L.PPLI%.0IO<L(11O1HE&'+'+AS<e2 Salar, is out oB acceptable rangeSIR (<D I:R (<D .:0(1 (.%9 1O>R (<D c/ec5Lsalar,R

%op,rig/t @ &''"A Oracle) .ll rig/ts reserved)

Using a %ompound 0rigger to 1esolve t/e =utating 0able (rror HcontinuedI .Bter eac/ ro2 is addedA iB t/e ne2 salar, is less t/an t/e minimum salar, Bor t/at department or greater t/an t/e departmentFs maCimum salar,A t/en an error message is displa,ed) 0o test t/e ne2l, created compound triggerA issue t/e Bollo2ing statement:
UPD.0( emplo,ees S(0 salar, Z *!'' >9(1( lastLname Z SStilesSR

0o ensure t/at t/e salar, Bor emplo,ee Stiles 2as updatedA issue t/e Bollo2ing Puer, using t/e :" 5e, in SQL Developer:

c ra O l, - On

, em ad .c

ra c O

S(L(%0 emplo,eeLidA BirstLnameA lastLnameA 3obLidA departmentLidA salar, :1O= emplo,ees >9(1( lastLname Z SStilesSR

le

l ae rn Uste

Oracle Database 11g: Develop PL/SQL Program Units " E 1!

In

%reating 0riggers on DDL Statements

%1(.0( VO1 1(PL.%(W 01I (1 triggerLname 6(:O1( T .:0(1 EE 0iming VddlLevent1 VO1 ddlLevent& O1 )))WW O< bD.0.6.S( T S%9(=.c triggerLbod,

Sample DDL (vents %1(.0(

:ires >/en .n, database ob3ect is created using t/e %1(.0( command) .n, database ob3ect is altered using t/e .L0(1 command) .n, database ob3ect is dropped using t/e D1OP command)

.L0(1 D1OP

%op,rig/t @ &''"A Oracle) .ll rig/ts reserved)

%reating 0riggers on DDL Statements 8ou can speciB, one or more t,pes oB DDL statements t/at can cause t/e trigger to Bire) 8ou can create triggers Bor t/ese events on D.0.6.S( or S%9(=. unless ot/er2ise noted) 8ou can also speciB, 6(:O1( and .:0(1 Bor t/e timing oB t/e trigger) 0/e Oracle database Bires t/e trigger in t/e eCisting user transaction) 8ou cannot speciB, as a triggering event an, DDL operation perBormed t/roug/ a PL/SQL procedure) 0/e trigger bod, in t/e s,ntaC in t/e slide represents a complete PL/SQL bloc5) DDL triggers Bire onl, iB t/e ob3ect being created is a clusterA BunctionA indeCA pac5ageA procedureA roleA sePuenceA s,non,mA tableA tablespaceA triggerA t,peA vie2A or user)

c ra O l, - On

, em ad .c

ra c O

le In

l ae rn Uste

Oracle Database 11g: Develop PL/SQL Program Units " E 1+

%reating DatabaseE(vent 0riggers


0riggering user event:
M %1(.0(A .L0(1A or D1OP M Logging on or oBB

0riggering database or s,stem event:


M S/utting do2n or starting up t/e database M . speciBic error Hor an, errorI being raised

%op,rig/t @ &''"A Oracle) .ll rig/ts reserved)

%reating Database 0riggers 6eBore coding t/e trigger bod,A decide on t/e components oB t/e trigger) 0riggers on s,stem events can be deBined at t/e database or sc/ema level) :or eCampleA a database s/utdo2n trigger is deBined at t/e database level) 0riggers on data deBinition language HDDLI statementsA or a user logging on or oBBA can also be deBined at eit/er t/e database level or sc/ema level) 0riggers on data manipulation language HD=LI statements are deBined on a speciBic table or a vie2)

ra c O

. trigger deBined at t/e database level Bires Bor all users 2/ereas a trigger deBined at t/e sc/ema or table level Bires onl, 2/en t/e triggering event involves t/at sc/ema or table) 0riggering events t/at can cause a trigger to Bire: . data deBinition statement on an ob3ect in t/e database or sc/ema . speciBic user Hor an, userI logging on or oBB . database s/utdo2n or startup .n, error t/at occurs

c ra O l, - On

, em ad .c

le

l ae rn Uste

Oracle Database 11g: Develop PL/SQL Program Units " E 1$

In

%reating 0riggers on S,stem (vents

%1(.0( VO1 1(PL.%(W 01I (1 triggerLname 6(:O1( T .:0(1 EE timing VdatabaseLevent1 VO1 databaseLevent& O1 )))WW O< bD.0.6.S( T S%9(=.c triggerLbod,

Database (vent .:0(1 S(1V(1(11O1 .:0(1 LO O< 6(:O1( LO O:: .:0(1 S0.10UP 6(:O1( S9U0DO><

0riggers :ires >/en .n Oracle error is raised . user logs on to t/e database . user logs oBB t/e database 0/e database is opened 0/e database is s/ut do2n normall,

%op,rig/t @ &''"A Oracle) .ll rig/ts reserved)

%reating 0riggers on S,stem (vents 8ou can create triggers Bor t/e events listed in t/e table in t/e slide on D.0.6.S( or S%9(=.A eCcept S9U0DO>< and S0.10UPA 2/ic/ appl, onl, to D.0.6.S()

c ra O l, - On

, em ad .c

ra c O

le In

l ae rn Uste

Oracle Database 11g: Develop PL/SQL Program Units " E 1G

LO O< and LO O:: 0riggers: (Cample


EE %reate t/e logLtrigLtable s/o2n in t/e notes page EE Birst %1(.0( O1 1(PL.%( 01I (1 logonLtrig .:0(1 LO O< O< S%9(=. 6( I< I<S(10 I<0O logLtrigLtableHuserLidAlogLdateAactionI V.LU(S HUS(1A S8SD.0(A SLogging onSIR (<DR /

%1(.0( O1 1(PL.%( 01I (1 logoBBLtrig 6(:O1( LO O:: O< S%9(=. 6( I< I<S(10 I<0O logLtrigLtableHuserLidAlogLdateAactionI V.LU(S HUS(1A S8SD.0(A SLogging oBBSIR (<DR /

%op,rig/t @ &''"A Oracle) .ll rig/ts reserved)

LO O< and LO O:: 0riggers: (Cample

l c ra O l, - On e

8ou can create t/ese triggers to monitor /o2 oBten ,ou log on and oBBA or ,ou ma, 2ant to 2rite a report t/at monitors t/e lengt/ oB time Bor 2/ic/ ,ou are logged on) >/en ,ou speciB, O< S%9(=.A t/e trigger Bires Bor t/e speciBic user) IB ,ou speciB, O< D.0.6.S(A t/e trigger Bires Bor all users) 0/e deBinition oB t/e logLtrigLtable used in t/e slide eCamples is as Bollo2s:
%1(.0( 0.6L( logLtrigLtableH userLid V.1%9.1&H*'IA logLdate D.0(A action V.1%9.1&H!'II /

, em ad .c

ra c O

le In

l ae rn Uste

Oracle Database 11g: Develop PL/SQL Program Units " E 1#

%.LL Statements in 0riggers


%1(.0( VO1 1(PL.%(W 01I (1 triggerLname timing event1 VO1 event& O1 event*W O< tableLname V1(:(1(<%I< OLD .S old T <(> .S ne2W V:O1 (.%9 1O>W V>9(< conditionW %.LL procedureLname /

%1(.0( O1 1(PL.%( P1O%(DU1( logLeCecution IS 6( I< D6=SLOU0PU0)PU0LLI<(HSlogLeCection: (mplo,ee InsertedSIR (<DR / %1(.0( O1 1(PL.%( 01I (1 logLemplo,ee 6(:O1( I<S(10 O< (=PLO8((S %.LL logLeCecution ME no semicolon needed /

%op,rig/t @ &''"A Oracle) .ll rig/ts reserved)

%.LL Statements in 0riggers . %.LL statement enables ,ou to call a stored procedureA rat/er t/an code t/e PL/SQL bod, in t/e trigger itselB) 0/e procedure can be implemented in PL/SQLA %A or ;ava) 0/e call can reBerence t/e trigger attributes :<(> and :OLD as parametersA as in t/e Bollo2ing eCample:
%1(.0( O1 1(PL.%( 01I (1 salar,Lc/ec5 6(:O1( UPD.0( O: salar,A 3obLid O< emplo,ees :O1 (.%9 1O> >9(< H<(>)3obLid ^\ S.DLP1(SSI %.LL c/ec5Lsalar,H:<(>)3obLidA :<(>)salar,I

<ote: 0/ere is no semicolon at t/e end oB t/e %.LL statement) In t/e preceding eCampleA t/e trigger calls a c/ec5Lsalar, procedure) 0/e procedure compares t/e ne2 salar, 2it/ t/e salar, range Bor t/e ne2 3ob ID Brom t/e ;O6S table)

c ra O l, - On

, em ad .c

ra c O

le

l ae rn Uste

Oracle Database 11g: Develop PL/SQL Program Units " E 1"

In

6eneBits oB DatabaseE(vent 0riggers


Improved data securit,:
M Provides en/anced and compleC securit, c/ec5s M Provides en/anced and compleC auditing

Improved data integrit,:


M (nBorces d,namic data integrit, constraints M (nBorces compleC reBerential integrit, constraints M (nsures t/at related operations are perBormed toget/er implicitl,

%op,rig/t @ &''"A Oracle) .ll rig/ts reserved)

6eneBits oB DatabaseE(vent 0riggers 8ou can use database triggers: .s alternatives to Beatures provided b, t/e Oracle server IB ,our rePuirements are more compleC or more simple t/an t/ose provided b, t/e Oracle server IB ,our rePuirements are not provided b, t/e Oracle server at all

c ra O l, - On

, em ad .c

ra c O

le In

l ae rn Uste

Oracle Database 11g: Develop PL/SQL Program Units " E &'

S,stem Privileges 1ePuired to =anage 0riggers


0/e Bollo2ing s,stem privileges are rePuired to manage triggers: 0/e privileges t/at enable ,ou to createA alterA and drop triggers in an, sc/ema:
M 1.<0 %1(.0( 01I (1 0O ora$1 M 1.<0 .L0(1 .<8 01I (1 0O ora$1 M 1.<0 D1OP .<8 01I (1 0O ora$1

0/e privilege t/at enables ,ou to create a trigger on t/e database:


M 1.<0 .D=I<IS0(1 D.0.6.S( 01I (1 0O ora$1

0/e (O(%U0( privilege HiB ,our trigger reBers to an, ob3ects t/at are not in ,our sc/emaI

%op,rig/t @ &''"A Oracle) .ll rig/ts reserved)

S,stem Privileges 1ePuired to =anage 0riggers 0o create a trigger in ,our sc/emaA ,ou need t/e %1(.0( 01I (1 s,stem privilegeA and ,ou must o2n t/e table speciBied in t/e triggering statementA /ave t/e .L0(1 privilege Bor t/e table in t/e triggering statementA or /ave t/e .L0(1 .<8 0.6L( s,stem privilege) 8ou can alter or drop ,our triggers 2it/out an, Burt/er privileges being rePuired) IB t/e .<8 5e,2ord is usedA ,ou can createA alterA or drop ,our o2n triggers and t/ose in anot/er sc/ema and can be associated 2it/ an, userFs table)

ra c O

8ou do not need an, privileges to invo5e a trigger in ,our sc/ema) . trigger is invo5ed b, D=L statements t/at ,ou issue) 6ut iB ,our trigger reBers to an, ob3ects t/at are not in ,our sc/emaA t/e user creating t/e trigger must /ave t/e (O(%U0( privilege on t/e reBerenced proceduresA BunctionsA or pac5agesA and not t/roug/ roles) 0o create a trigger on D.0.6.S(A ,ou must /ave t/e .D=I<IS0(1 D.0.6.S( 01I (1 privilege) IB t/is privilege is later revo5edA ,ou can drop t/e trigger but ,ou cannot alter it) <ote: Similar to stored proceduresA statements in t/e trigger bod, use t/e privileges oB t/e trigger o2nerA not t/e privileges oB t/e user eCecuting t/e operation t/at Bires t/e trigger)

c ra O l, - On

, em ad .c

le

l ae rn Uste

Oracle Database 11g: Develop PL/SQL Program Units " E &1

In

uidelines Bor Designing 0riggers


8ou can design triggers to:
M PerBorm related actions M %entrali4e global operations

8ou must not design triggers:


M >/ere Bunctionalit, is alread, built into t/e Oracle server M 0/at duplicate ot/er triggers

8ou can create stored procedures and invo5e t/em in a triggerA iB t/e PL/SQL code is ver, lengt/,) (Ccessive use oB triggers can result in compleC interdependenciesA 2/ic/ ma, be diBBicult to maintain in large applications)

%op,rig/t @ &''"A Oracle) .ll rig/ts reserved)

uidelines Bor Designing 0riggers Use triggers to guarantee t/at related actions are perBormed Bor a speciBic operation and Bor centrali4edA global operations t/at s/ould be Bired Bor t/e triggering statementA independent oB t/e user or application issuing t/e statement) Do not deBine triggers to duplicate or replace t/e Bunctionalit, alread, built into t/e Oracle database) :or eCampleA implement integrit, rules using declarative constraints instead oB triggers) 0o remember t/e design order Bor a business rule: E Use builtEin constraints in t/e Oracle serverA suc/ as primar, 5e,A and so on) E Develop a database trigger or an applicationA suc/ as a servlet or (nterprise ;ava6eans H(;6I on ,our middle tier) E Use a presentation interBaceA suc/ as Oracle :ormsA 90=LA ;avaServer Pages H;SPI and so onA Bor data presentation rules) (Ccessive use oB triggers can result in compleC interdependenciesA 2/ic/ ma, be diBBicult to maintain) Use triggers 2/en necessar,A and be a2are oB recursive and cascading eBBects) .void lengt/, trigger logic b, creating stored procedures or pac5aged procedures t/at are invo5ed in t/e trigger bod,) Database triggers Bire Bor ever, user eac/ time t/e event occurs on t/e trigger t/at is created)

c ra O l, - On

, em ad .c

ra c O

le

l ae rn Uste

Oracle Database 11g: Develop PL/SQL Program Units " E &&

In

Qui4
1) . trigger is deBined 2it/ a %1(.0( 01I &) . triggerSs source code is contained in t/e US(1L01I (1S data dictionar,) *) . trigger is eCplicitl, invo5ed) !) . trigger is implicitl, invo5ed b, D=L) +) 0/e %O==I0A S.V(POI<0A and 1OLL6.%? are not allo2ed 2/en 2or5ing 2it/ a trigger) (1 statement

%op,rig/t @ &''"A Oracle) .ll rig/ts reserved)

.ns2ers: 1A &A !A +

l c ra O l, - On e

, em ad .c

ra c O

le In

l ae rn Uste

Oracle Database 11g: Develop PL/SQL Program Units " E &*

Summar,
In t/is lessonA ,ou s/ould /ave learned /o2 to: Describe compound triggers Describe mutating tables %reate triggers on DDL statements %reate triggers on s,stem events Displa, inBormation about triggers

%op,rig/t @ &''"A Oracle) .ll rig/ts reserved)

l c ra O l, - On ra c O le In l ae rn Uste e

, em ad .c

Oracle Database 11g: Develop PL/SQL Program Units " E &!

Practice ": Overvie2


0/is practice covers t/e Bollo2ing topics: %reating advanced triggers to manage data integrit, rules %reating triggers t/at cause a mutating table eCception %reating triggers t/at use pac5age state to solve t/e mutating table problem

%op,rig/t @ &''"A Oracle) .ll rig/ts reserved)

Practice ": Overvie2 In t/is practiceA ,ou implement a simple business rule Bor ensuring data integrit, oB emplo,eesF salaries 2it/ respect to t/e valid salar, range Bor t/eir 3ob) 8ou create a trigger Bor t/is rule) During t/is processA ,our ne2 triggers cause a cascading eBBect 2it/ triggers created in t/e practice section oB t/e previous lesson) 0/e cascading eBBect results in a mutating table eCception on t/e ;O6S table) 8ou t/en create a PL/SQL pac5age and additional triggers to solve t/e mutating table issue)

c ra O l, - On

, em ad .c

ra c O

le In

l ae rn Uste

Oracle Database 11g: Develop PL/SQL Program Units " E &+

l c ra O l, - On ra c O le In l ae rn Uste e

, em ad .c

Using t/e PL/SQL %ompiler

%op,rig/t @ &''"A Oracle) .ll rig/ts reserved)

l c ra O l, - On ra c O le In l ae rn Uste e

, em ad .c

Ob3ectives
.Bter completing t/is lessonA ,ou s/ould be able to do t/e Bollo2ing: Use t/e PL/SQL compiler initiali4ation parameters Use t/e PL/SQL compileEtime 2arnings

%op,rig/t @ &''"A Oracle) .ll rig/ts reserved)

l c ra O l, - On ra c O le In l ae rn Uste e

, em ad .c

Oracle Database 11g: Develop PL/SQL Program Units 1' E &

Lesson .genda
Using t/e PLSQLL%OD(L08P( and PLSQLLOP0I=I7(LL(V(L PL/SQL compilation initiali4ation parameters Using t/e PL/SQL compileEtime 2arnings:
M Using t/e PLSQLL>.1<I< initiali4ation parameter M Using t/e D6=SL>.1<I< pac5age subprograms

%op,rig/t @ &''"A Oracle) .ll rig/ts reserved)

l c ra O l, - On ra c O le In l ae rn Uste e

, em ad .c

Oracle Database 11g: Develop PL/SQL Program Units 1' E *

Initiali4ation Parameters Bor PL/SQL %ompilation


PLSQLL%OD(L08P( PLSQLLOP0I=I7(LL(V(L PLSQLL%%:L. S PLSQLL>.1<I< S

%op,rig/t @ &''"A Oracle) .ll rig/ts reserved)

Initiali4ation Parameters Bor PL/SQL %ompilation

l e

In releases beBore Oracle Database 1'gA t/e PL/SQL compiler translated ,our code to mac/ine code 2it/out appl,ing man, c/anges Bor perBormance) <o2A PL/SQL uses an optimi4ing compiler t/at can rearrange code Bor better perBormance) 8ou do not need to do an,t/ing to get t/e beneBits oB t/is ne2 optimi4erR it is enabled b, deBault) <ote 0/e PLSQLL%%:L. S initiali4ation parameter is covered in t/e lesson titled X=anaging PL/SQL %ode)Y 0/e PLSQLL>.1<I< S initiali4ation parameter is covered later in t/is lesson)

c ra O l, - On

, em ad .c

ra c O

le In

l ae rn Uste

Oracle Database 11g: Develop PL/SQL Program Units 1' E !

Using t/e Initiali4ation Parameters Bor PL/SQL %ompilation


PLSQLL%OD(L08P(: SpeciBies t/e compilation mode Bor PL/SQL librar, units

PLSQLL%OD(L08P( Z b I<0(1P1(0(D T <.0IV( c

PLSQLLOP0I=I7(LL(V(L: SpeciBies t/e optimi4ation level to be used to compile PL/SQL librar, units

PLSQLLOP0I=I7(LL(V(L Z b ' T 1 T & T *c

%op,rig/t @ &''"A Oracle) .ll rig/ts reserved)

Using t/e Initiali4ation Parameters Bor PL/SQL %ompilation 0/e PLSQLL%OD(L08P( Parameter

ra c O

0/is parameter speciBies t/e compilation mode Bor PL/SQL librar, units) IB ,ou c/oose I<0(1P1(0(DA PL/SQL librar, units 2ill be compiled to PL/SQL b,tecode Bormat) Suc/ modules are eCecuted b, t/e PL/SQL interpreter engine) IB ,ou c/oose <.0IV(A PL/SQL librar, units H2it/ t/e possible eCception oB topElevel anon,mous PL/SQL bloc5sI 2ill be compiled to native Hmac/ineI code) Suc/ modules 2ill be eCecuted nativel, 2it/out incurring an, interpreter over/ead) >/en t/e value oB t/is parameter is c/angedA it /as no eBBect on PL/SQL librar, units t/at /ave alread, been compiled) 0/e value oB t/is parameter is stored persistentl, 2it/ eac/ librar, unit) IB a PL/SQL librar, unit is compiled nativel,A all subsePuent automatic recompilations oB t/at librar, unit 2ill use native compilation) In Oracle Database 11gA native compilation is easier and more integratedA 2it/ Be2er initiali4ation parameters to set) In rare casesA iB t/e over/ead oB t/e optimi4er ma5es compilation oB ver, large applications ta5e too longA ,ou mig/t lo2er t/e optimi4ation level b, setting t/e initiali4ation parameter PLSQLLOP0I=I7(LL(V(L to 1 instead oB its deBault value &) In even rarer casesA ,ou mig/t see a c/ange in eCception be/aviorUeit/er an eCception t/at is not raised at all or one t/at is raised earlier t/an eCpected) Setting PLSQLLOP0I=I7(LL(V(L to ' prevents t/e code Brom being rearranged at all)

c ra O l, - On

, em ad .c

le

l ae rn Uste

Oracle Database 11g: Develop PL/SQL Program Units 1' E +

In

Using t/e Initiali4ation Parameters Bor PL/SQL %ompilation HcontinuedI 0/e PLSQLLOP0I=I7(LL(V(L Parameter 0/is parameter speciBies t/e optimi4ation level t/at 2ill be used to compile PL/SQL librar, units) 0/e /ig/er t/e setting oB t/is parameterA t/e more eBBort t/e compiler ma5es to optimi4e PL/SQL librar, units) 0/e available values are H'A 1A and & 2ere available starting 2it/ Oracle 1'g release &I: ': =aintains t/e evaluation order and /ence t/e pattern oB side eBBectsA eCceptionsA and pac5age initiali4ations oB Oracle"i and earlier releases) .lso removes t/e ne2 semantic identit, oB 6I<.18LI<0( (1 and PLSLI<0( (1 and restores t/e earlier rules Bor t/e evaluation oB integer eCpressions) .lt/oug/ code 2ill run some2/at Baster t/an it did in Oracle"iA use oB level ' 2ill BorBeit most oB t/e perBormance gains oB PL/SQL starting 2it/ Oracle Database 1'g) 1: .pplies a 2ide range oB optimi4ations to PL/SQL programs including t/e elimination oB unnecessar, computations and eCceptionsA but generall, does not move source code out oB its original source order &: .pplies a 2ide range oB modern optimi4ation tec/niPues be,ond t/ose oB level 1 including c/anges 2/ic/ ma, move source code relativel, Bar Brom its original location *: 0/is value is ne2 in Oracle Database 11g) It applies a 2ide range oB optimi4ation tec/niPues be,ond t/ose oB level &A automaticall, including tec/niPues not speciBicall, rePuested) 0/is enables procedure inliningA 2/ic/ is an optimi4ation process t/at replaces procedure calls 2it/ a cop, oB t/e bod, oB t/e procedure to be called) 0/e copied procedure almost al2a,s runs Baster t/an t/e original call) 0o allo2 subprogram inliningA eit/er accept t/e deBault value oB t/e PLSQLLOP0I=I7(LL(V(L initiali4ation parameter H2/ic/ is &I or set it to *) >it/ PLSQLLOP0I=I7(LL(V(L Z &A ,ou must speciB, eac/ subprogram to be inlined) >it/ PLSQLLOP0I=I7(LL(V(L Z *A t/e PL/SQL compiler see5s opportunities to inline subprograms be,ond t/ose t/at ,ou speciB,) <ote: :or additional inBormation about inliningA reBer to t/e Oracle Database PL/SQL Language 1eBerence 11g 1elease & H11)&I guide and t/e Oracle Database 11g .dvanced PL/SQL instructorEled course) enerall,A setting t/is parameter to & pa,s oBB in terms oB better eCecution perBormance) IBA /o2everA t/e compiler runs slo2l, on a particular source module or iB optimi4ation does not ma5e sense Bor some reason HBor eCampleA during rapid turnaround developmentIA t/en setting t/is parameter to 1 results in almost as good a compilation 2it/ less use oB compileEtime resources) 0/e value oB t/is parameter is stored persistentl, 2it/ t/e librar, unit) <ote 0/e PLSQLL%OD(L08P( parameter in Oracle Database 1'g replaced t/e Bollo2ing obsolete parameters: PLSQLL<.0IV(L%L%O=PIL(1 PLSQLL<.0IV(L=.?(L:IL(L<.=( PLSQLL<.0IV(L%L%O=PIL(1 PLSQLL<.0IV(L=.?(LU0ILI08 PLSQLL<.0IV(LLI<?(1 0/e PLSQLLD(6U parameter is deprecated in Oracle Database 11g) 0/e parameter PLSQLLD(6U no longer controls t/e generation oB debugging inBormation b, t/e PL/SQL compilerR debugging inBormation is al2a,s generated and no special parameter is needed)

c ra O l, - On

, em ad .c

ra c O

le

l ae rn Uste

Oracle Database 11g: Develop PL/SQL Program Units 1' E $

In

0/e %ompiler Settings


%ompiler Option PLSQLL%OD(L08P( Description SpeciBies t/e compilation mode Bor PL/SQL librar, units) SpeciBies t/e optimi4ation level to be used to compile PL/SQL librar, units) (nables or disables t/e reporting oB 2arning messages b, t/e PL/SQL compiler) %ontrols conditional compilation oB eac/ PL/SQL librar, unit independentl,)

PLSQLLOP0I=I7(LL(V(L

PLSQLL>.1<I< S

PLSQLL%%:L. S

In generalA Bor t/e Bastest perBormanceA use t/e Bollo2ing setting:


PLSQLL%OD(L08P( Z <.0IV( PLSQLLOP0I=I7(LL(V(L Z &

%op,rig/t @ &''"A Oracle) .ll rig/ts reserved)

0/e %ompiler Settings 0/e ne2 compiler increases t/e perBormance oB PL/SQL code and allo2s it to eCecute approCimatel, t2o times Baster t/an an Oracle#i database and 1)+ times to 1)G+ times as Bast as Oracle"i Database 1elease &) 0o get t/e Bastest perBormanceA t/e compiler setting must be: PLSQLL%OD(L08P( Z <.0IV( PLSQLLOP0I=I7(LL(V(L Z &

c ra O l, - On

, em ad .c

ra c O

le In

l ae rn Uste

Oracle Database 11g: Develop PL/SQL Program Units 1' E G

Displa,ing t/e PL/SQL Initiali4ation Parameters


Use t/e US(1T.LLTD6.LPLSQLLO6;(%0LS(00I< S data dictionar, vie2s to displa, t/e settings Bor a PL/SQL ob3ect:
D(S%1I6( US(1LPLSQLLO6;(%0LS(00I< S

%op,rig/t @ &''"A Oracle) .ll rig/ts reserved)

Displa,ing t/e PL/SQL Initiali4ation Parameters 0/e columns oB t/e US(1LPLSQLLO6;(%0SLS(00I< S data dictionar, vie2 are: O2ner: 0/e o2ner oB t/e ob3ect) 0/is column is not displa,ed in t/e US(1LPLSQLLO6;(%0SLS(00I< S vie2)

<ame: 0/e name oB t/e ob3ect 0,pe: 0/e available c/oices are: P1O%(DU1(A :U<%0IO<A P.%?. (A P.%?. ( 6OD8A 01I (1A 08P(A or 08P( 6OD8) PLSQLLOP0I=I7(LL(V(L: 0/e optimi4ation level t/at 2as used to compile t/e ob3ect PLSQLL%OD(L08P(: 0/e compilation mode Bor t/e ob3ect PLSQLLD(6U : SpeciBies 2/et/er or not t/e ob3ect 2as compiled Bor debugging PLSQLL>.1<I< S: 0/e compiler 2arning settings used to compile t/e ob3ect <LSLL(< 09LS(=.<0I%S: 0/e <LS lengt/ semantics used to compile t/e ob3ect PLSQLL%%:L. S: 0/e conditional compilation Blag used to compile t/e ob3ect PLS%OP(LS(00I< S: %ontrols t/e compileEtime collectionA cross reBerenceA and storage oB PL/SQL source code identiBier data Hne2 in Oracle Database 11gI

c ra O l, - On

, em ad .c

ra c O

le

l ae rn Uste

Oracle Database 11g: Develop PL/SQL Program Units 1' E #

In

Displa,ing and Setting t/e PL/SQL Initiali4ation Parameters


S(L(%0 nameA t,peA plsPlLcodeLt,pe .S %OD(L08P(A plsPlLoptimi4eLlevel .S OP0LLVL :1O=userLplsPlLob3ectLsettingsR

)))

Set t/e compiler initiali4ation parameterFs value using t/e .L0(1 S8S0(= or .L0(1 S(SSIO< statements) 0/e parametersF values are accessed 2/en t/e %1(.0( O1 1(PL.%( statement is eCecuted)

%op,rig/t @ &''"A Oracle) .ll rig/ts reserved)

<ote :or additional inBormation about t/e .L0(1 S8S0(= or .L0(1 S(SSIO< statementsA reBer to t/e Oracle Database SQL 1eBerence 11g 1elease & H11)&I uide) 0/e D6.LS0O1(DLS(00I< S data dictionar, vie2 Bamil, is deprecated in Oracle Database 1'g and is replaced 2it/ t/e D6.LPLSQLLO6;(%0LS(00I< S data dictionar, vie2 Bamil,)

c ra O l, - On

, em ad .c

ra c O

le In

l ae rn Uste

Oracle Database 11g: Develop PL/SQL Program Units 1' E "

%/anging PL/SQL Initiali4ation Parameters: (Cample


.L0(1 S(SSIO< S(0 PLSQLLOP0I=I7(LL(V(L Z 1R .L0(1 S(SSIO< S(0 PLSQLL%OD(L08P( Z S<.0IV(SR

EE code displa,ed in t/e notes page %1(.0( O1 1(PL.%( P1O%(DU1( addL3obL/istor,

)))

]codeL1'L1'Ls)sPl

)))
%op,rig/t @ &''"A Oracle) .ll rig/ts reserved)

%/anging PL/SQL Initiali4ation Parameters: (Cample 0o c/ange a compiled PL/SQL ob3ect Brom interpreted code t,pe to native code t,peA ,ou must Birst set t/e PLSQLL%OD(L08P( parameter to <.0IV( Hoptionall, set t/e ot/er parametersI and t/enA recompile t/e program) 0o enBorce native compilation to all PL/SQL codeA ,ou must recompile eac/ one) Scripts Hin t/e rdmbs/admin director,I are provided Bor ,ou to ac/ieve conversion to Bull native compilation Hdbmsupgnv)sPlI or Bull interpreted compilation Hdbmsupgin)sPlI) 0/e addL3obL/istor, procedure is created as Bollo2s:
%1(.0( O1 1(PL.%( P1O%(DU1( addL3obL/istor, H pLempLid3obL/istor,)emplo,eeLidQt,pe A pLstartLdate3obL/istor,)startLdateQt,pe A pLendLdate3obL/istor,)endLdateQt,pe A pL3obLid3obL/istor,)3obLidQt,pe A pLdepartmentLid3obL/istor,)departmentLidQt,pe I IS 6( I< I<S(10 I<0O 3obL/istor, Hemplo,eeLidA startLdateA endLdateA 3obLidA departmentLidI V.LU(SHpLempLidA pLstartLdateA pLendLdateA pL3obLidA pLdepartmentLidIR (<D addL3obL/istor,R /

c ra O l, - On

, em ad .c

ra c O

le

l ae rn Uste

Oracle Database 11g: Develop PL/SQL Program Units 1' E 1'

In

Lesson .genda
Using t/e PLSQLL%OD(L08P( and PLSQLLOP0I=I7(LL(V(L PL/SQL compilation initiali4ation parameters Using t/e PL/SQL compileEtime 2arnings:
M Using t/e PLSQLL>.1<I< initiali4ation parameter M Using t/e D6=SL>.1<I< pac5age subprograms

%op,rig/t @ &''"A Oracle) .ll rig/ts reserved)

l c ra O l, - On ra c O le In l ae rn Uste e

, em ad .c

Oracle Database 11g: Develop PL/SQL Program Units 1' E 11

Overvie2 oB PL/SQL %ompileE0ime >arnings Bor Subprograms


Starting 2it/ Oracle 1'gA t/e PL/SQL compiler /as been en/anced to produce 2arnings Bor subprograms)

(nable 2arnings

%ompile program

Vie2 2arnings

%op,rig/t @ &''"A Oracle) .ll rig/ts reserved)

Overvie2 oB PL/SQL %ompileE0ime >arnings Bor Subprograms 0o ma5e ,our programs more robust and avoid problems at run timeA ,ou can turn on c/ec5ing Bor certain 2arning conditions) 0/ese conditions are not serious enoug/ to produce an error and 5eep ,ou Brom compiling a subprogram) 0/e, ma, point out somet/ing in t/e subprogram t/at produces an undeBined result or mig/t create a perBormance problem) In releases prior to Oracle Database 1'gA compiling a PL/SQL program /ad t2o possible outcomes: SuccessA producing a valid compiled unit :ailureA 2it/ compilation errors indicating t/at t/e program /ad eit/er s,ntaC or semantic errors

ra c O

9o2everA even 2/en compilation oB a program 2as successBulA t/e program ma, /ave violated recommended best practices or could /ave been coded to be more eBBicient) Oracle Database 1'g introduced a ne2 easeEoBEuse Beature t/at allo2s t/e PL/SQL compiler to communicate 2arning messages in t/ese situations) %ompiler 2arnings allo2 developers to avoid common coding pitBallsA t/us improving productivit,)

c ra O l, - On

, em ad .c

le

l ae rn Uste

Oracle Database 11g: Develop PL/SQL Program Units 1' E 1&

In

Overvie2 oB PL/SQL %ompileE0ime >arnings Bor Subprograms HcontinuedI PL/SQL supports passing oB I< OU0 and OU0 parameters b, value or b, reBerence t/roug/ t/e <O%OP8 compiler /int) Passing parameters b, value is in/erentl, less eBBicient because it involves ma5ing multiple copies oB t/e data) >it/ Oracle Database 11gA t/e compiler automaticall, detects and recommends t/e use oB t/e <O%OP8 /intA 2/ere t/e parameter t,pes are large ob3ectA recordA or collection t,pes) >it/ t/e PL/SQL compilerE2arning BeatureA compiling a PL/SQL program could /ave additional possible outcomes: Success 2it/ compilation 2arnings :ailure 2it/ compilation errors and compilation 2arnings <ote t/at t/e compiler ma, issue 2arning messages even on a successBul compile) . compilation error must be corrected to be able to use t/e stored procedure 2/ereas a 2arning is Bor inBormational purposes) (Camples oB 2arning messages SP&E'#'!: Procedure created 2it/ compilation 2arnings PL>E'G&'*: Parameter SIOL06LS ma, beneBit Brom use oB t/e <O%OP8 compiler /int

l c ra O l, - On ra c O le In l ae rn Uste e

, em ad .c

Oracle Database 11g: Develop PL/SQL Program Units 1' E 1*

6eneBits oB %ompiler >arnings


=a5e programs more robust and avoid problems at run time IdentiB, potential perBormance problems IdentiB, Bactors t/at produce undeBined results

%op,rig/t @ &''"A Oracle) .ll rig/ts reserved)

6eneBits oB %ompiler >arnings Using compiler 2arnings can /elp ,ou to: =a5e ,our programs more robust and avoid problems at run time IdentiB, potential perBormance problems IdentiB, Bactors t/at produce undeBined results <ote 8ou can enable c/ec5ing Bor certain 2arning conditions 2/en t/ese conditions are not serious enoug/ to produce an error and 5eep ,ou Brom compiling a subprogram) >arning messages can be issued during compilation oB PL/SQL subprogramsR anon,mous bloc5s do not produce an, 2arnings) .ll PL/SQL 2arning messages use t/e preBiC PL>)

c ra O l, - On

, em ad .c

ra c O

le In

l ae rn Uste

Oracle Database 11g: Develop PL/SQL Program Units 1' E 1!

%ategories oB PL/SQL %ompileE0ime >arning =essages

S(V(1(

P(1:O1=.<%(

I<:O1=.0IO<.L

.LL

%op,rig/t @ &''"A Oracle) .ll rig/ts reserved)

%ategories oB PL/SQL %ompileE0ime >arning =essages PL/SQL 2arning messages are divided into categoriesA so t/at ,ou can suppress or displa, groups oB similar 2arnings during compilation) 0/e categories are: S(V(1(: =essages Bor conditions t/at ma, cause uneCpected be/avior or 2rong resultsA suc/ as aliasing problems 2it/ parameters P(1:O1=.<%(: =essages Bor conditions t/at ma, cause perBormance problemsA suc/ as passing a V.1%9.1& value to a <U=6(1 column in an I<S(10 statement I<:O1=.0IO<.L: =essages Bor conditions t/at do not /ave an eBBect on perBormance or correctnessA but t/at ,ou ma, 2ant to c/ange to ma5e t/e code more maintainableA suc/ as unreac/able code t/at can never be eCecuted

c ra O l, - On

, em ad .c

ra c O

le In

l ae rn Uste

Oracle Database 11g: Develop PL/SQL Program Units 1' E 1+

Setting t/e >arning =essages Levels


8ou can set 2arning levels using one oB t/e Bollo2ing met/ods: Declarativel,:
M Using t/e PLSQLL>.1<I< S initiali4ation parameter

Programmaticall,:
M Using t/e D6=SL>.1<I< pac5age

PLSQLL>.1<I< S initiali4ation parameter

D6=SL>.1<I< pac5age

%op,rig/t @ &''"A Oracle) .ll rig/ts reserved)

Setting t/e >arning =essages Levels 8ou can set t/e compiler 2arning messages levels using one oB t/e Bollo2ing met/ods: Using t/e PLSQLL>.1<I< S Initiali4ation Parameter 0/e PLSQLL>.1<I< S setting enables or disables t/e reporting oB 2arning messages b, t/e PL/SQL compilerA and speciBies 2/ic/ 2arning messages to s/o2 as errors) 0/e settings Bor t/e PLSQLL>.1<I< S parameter are stored along 2it/ eac/ compiled subprogram) 8ou can use t/e PLSQLL>.1<I< S initiali4ation parameter to do t/e Bollo2ing: (nable or disable t/e reporting oB all 2arningsA 2arnings oB a selected categor,A or speciBic 2arning messages) 0reat all 2arningsA a selected categor, oB 2arningA or speciBic 2arning messages as errors) .n, valid combination oB t/e preceding 0/e 5e,2ord .ll is a s/ort/and 2a, to reBer to all 2arning messages: S(V(1(A P(1:O1=.<%(A and I<:O1=.0IO<.L) Using t/e D6=SL>.1<I< Pac5age

c ra O l, - On

, em ad .c

ra c O

le

0/e D6=SL>.1<I< pac5age provides a 2a, to manipulate t/e be/avior oB PL/SQL 2arning messagesA in particular b, reading and c/anging t/e setting oB t/e PLSQLL>.1<I< S initiali4ation parameter to control 2/at 5inds oB 2arnings are suppressedA displa,edA or treated as errors) 0/is pac5age provides t/e interBace to Puer,A modiB,A and delete current s,stem or session settings) 0/is pac5age is covered later in t/is lesson)
Oracle Database 11g: Develop PL/SQL Program Units 1' E 1$

l ae rn Uste

In

Setting %ompiler >arning Levels: Using PLSQLL>.1<I< S

.L0(1 VS(SSIO<TS8S0(=W PLSQLL>.1<I< S Z SvalueLclause1SV ASvalueLclause&SW)))

valueLclause Z QualiBier Value : =odiBier Value

QualiBier Value Z b (<.6L( T DIS.6L( T (11O1 c =odiBier Value Z b .LL T S(V(1( T I<:O1=.0IO<.L T P(1:O1=.<%( T b integer T Hinteger VA integer W )))I c c

%op,rig/t @ &''"A Oracle) .ll rig/ts reserved)

=odiB,ing %ompiler >arning Settings 0/e parameter value comprises a commaEseparated list oB Puoted PualiBier and modiBier 5e,2ordsA 2/ere t/e 5e,2ords are separated b, colons) 0/e PualiBier values are: (<.6L(A DIS.6L(A and (11O1) 0/e modiBier value .LL applies to all 2arning messages) S(V(1(A I<:O1=.0IO<.LA and P(1:O1=.<%( appl, to messages in t/eir o2n categor,A and an integer list Bor speciBic 2arning messages) Possible values Bor (<.6L(A DIS.6L(A and (11O1: .LL S(V(1( I<:O1=.0IO<.L P(1:O1=.<%( numericLvalue

c ra O l, - On

, em ad .c

ra c O

Values Bor numericLvalue are in: 1ange +'''E+""" Bor severe 1ange $'''E$&!" Bor inBormational 1ange G'''EG&!" Bor perBormance

le

l ae rn Uste

Oracle Database 11g: Develop PL/SQL Program Units 1' E 1G

In

Setting %ompiler >arning Levels: Using PLSQLL>.1<I< SA (Camples


.L0(1 S(SSIO< S(0 plsPlL2arnings Z Senable:severeSA Senable:perBormanceSA Sdisable:inBormationalSR

.L0(1 S(SSIO< S(0 plsPlL2arnings Z Senable:severeSR

.L0(1 S(SSIO< S(0 PLSQLL>.1<I< SZS(<.6L(:S(V(1(SA SDIS.6L(:P(1:O1=.<%(S A S(11O1:'+''*SR

%op,rig/t @ &''"A Oracle) .ll rig/ts reserved)

Setting %ompiler >arning Levels: Using PLSQLL>.1<I< SA (Camples 8ou can use t/e .L0(1 S(SSIO< or .L0(1 S8S0(= command to c/ange t/e PLSQLL>.1<I< S initiali4ation parameter) 0/e grap/ic in t/e slide s/o2s t/e various eCamples oB enabling and disabling compiler 2arnings) (Cample 1 In t/is eCampleA ,ou are enabling S(V(1( and P(1:O1=.<%( 2arnings and disabling I<:O1=.0IO<.L 2arnings)

(Cample & In t/e second eCampleA ,ou are enabling onl, S(V(1( 2arnings) (Cample * 8ou can also treat particular messages as errors instead oB 2arnings) In t/is eCampleA iB ,ou 5no2 t/at t/e 2arning message PL>E'+''* represents a serious problem in ,our codeA including S(11O1:'+''*S in t/e PLSQLL>.1<I< S setting ma5es t/at condition trigger an error message HPLSL'+''*I instead oB a 2arning message) .n error message causes t/e compilation to Bail) In t/is eCampleA ,ou are also disabling P(1:O1=.<%( 2arnings)

c ra O l, - On

, em ad .c

ra c O

le

l ae rn Uste

Oracle Database 11g: Develop PL/SQL Program Units 1' E 1#

In

Setting %ompiler >arning Levels: Using PLSQLL>.1<I< S in SQL Developer

%op,rig/t @ &''"A Oracle) .ll rig/ts reserved)

Setting %ompiler >arning Levels: Using PLSQLL>.1<I< S in SQL Developer

ra c O

0/e PL/SQL %ompiler pane speciBies options Bor compilation oB PL/SQL subprograms) IB t/e enerate PL/SQL Debug InBormation c/ec5 boC is selectedA PL/SQL debug inBormation is included in t/e compiled codeR iB t/is option is not selectedA t/is debug inBormation is not included) 0/e abilit, to stop on individual code lines and debugger access to variables are allo2ed onl, in code compiled 2it/ debug inBormation generated) Setting and Vie2ing t/e PL/SQL %ompileE0ime >arning =essages %ategories in SQL Developer 8ou can control t/e displa, oB inBormationalA severeA and perBormanceErelated messages) 0/e .LL t,pe overrides an, individual speciBications Bor t/e ot/er t,pes oB messages) :or eac/ t,pe oB messageA ,ou can speciB, an, oB t/e Bollo2ing: <o entr, Hblan5I: Use an, value speciBied Bor .LLR and iB no value is speciBiedA use t/e Oracle deBault) (nable: (nable t/e displa, oB all messages oB t/is categor,) Disable: Disable t/e displa, oB all messages oB t/is categor,) (rror: (nable t/e displa, oB onl, error messages oB t/is categor,)

c ra O l, - On

, em ad .c

le

l ae rn Uste

Oracle Database 11g: Develop PL/SQL Program Units 1' E 1"

In

Vie2ing t/e %urrent Setting oB PLSQLL>.1<I< S

V[P.1.=(0(1 vie2

US(1TD6.T.LLLPLSQLL O6;(%0LS(00I< S vie2s

PLSQLL>.1<I< S initiali4ation parameter

SQL Developer

%op,rig/t @ &''"A Oracle) .ll rig/ts reserved)

Vie2ing t/e %urrent Value oB t/e PLSQLL>.1<I< S Parameter 8ou can eCamine t/e current setting Bor t/e PLSQLL>.1<I< S parameter b, issuing a S(L(%0 statement on t/e V[P.1.=(0(1 vie2) :or eCample:
.L0(1 S(SSIO< S(0 plsPlL2arnings Z Senable:severeSA Senable:perBormanceSASenable:inBormationalSR Session altered) S(L(%0 value :1O= v[parameter >9(1( nameZSplsPlL2arningsSR V.LU( EEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEE (<.6L(:.LL

.lternativel,A ,ou can use t/e D6=SL>.1<I< ) (0L>.1<I< LS(00I< LS01I< pac5age and procedure to retrieve t/e current settings Bor t/e PLSQLL>.1<I< S parameter:
D(%L.1( s V.1%9.1&H1'''IR 6( I< s :Z dbmsL2arning)getL2arningLsettingLstringHIR dbmsLoutput)putLline HsIR (<DR /

c ra O l, - On

, em ad .c
D6=SL>.1<I< pac5age Bunction

ra c O

le

l ae rn Uste

Oracle Database 11g: Develop PL/SQL Program Units 1' E &'

In

Vie2ing t/e %ompiler >arnings: Using SQL DeveloperA SQLKPlusA or Data Dictionar, Vie2s

Vie2 errors/2arnings in SQL Developer

Use S9O> (11O1S command in SQLKPlus (nable 2arnings and compile program %ompiler 2arnings/errorsJ Vie2 compiler 2arnings/errors

%op,rig/t @ &''"A Oracle) .ll rig/ts reserved)

Vie2ing t/e %ompiler >arnings 8ou can use SQLKPlus to see an, 2arnings raised as a result oB t/e compilation oB a PL/SQL bloc5) SQLKPlus indicates t/at a compilation 2arning /as occurred) 0/e XSP&E'#CC: ^ob3ect\ created 2it/ compilation 2arnings)Y message is displa,ed Bor ob3ects compiled 2it/ t/e P(1:O1=.<%(A I<:O1=.0IO<.LA or S(V(1( modiBiers) 0/ere is no diBBerentiation bet2een t/e t/ree) 8ou must enable t/e compiler 2arnings beBore compiling t/e program) 8ou can displa, t/e compiler 2arning messages using one oB t/e Bollo2ing met/ods: Using t/e SQLKPlus S9O> (11O1S %ommand 0/is command displa,s an, compiler errors including t/e ne2 compiler 2arnings and inBormational messages) 0/is command is invo5ed immediatel, aBter a %1(.0( VP1O (DU1(T:U<%0IO<TP.%?. (W command is used) 0/e S9O> (11O1S command displa,s 2arnings and compiler errors) <e2 compiler 2arnings and inBormational messages are XinterleavedY 2it/ compiler errors 2/en S9O> (11O1S is invo5ed)

c ra O l, - On

, em ad .c

Use US(1/.LL/D6.L (11O1S vie2s

ra c O

Using t/e Data Dictionar, Vie2s 8ou can select Brom t/e US(1LT.LLLTD6.L(11O1S data dictionar, vie2s to displa, PL/SQL compiler 2arnings) 0/e .001I6U0(S column oB t/ese vie2s /as a ne2 attribute called >.1<I< and t/e 2arning message displa,s in t/e 0(O0 column)

le

l ae rn Uste

Oracle Database 11g: Develop PL/SQL Program Units 1' E &1

In

SQLKPlus >arning =essages: (Cample

%1(.0( O1 1(PL.%( P1O%(DU1( badLprocHpLout _I IS 6( I< ) ) )R (<DR / SP&E'#'!: Procedure created 2it/ compilation 2arnings)

S9O> (11O1SR (rrors Bor P1O%(DU1( 6.DLP1O%: LI<(/%OL EEEEEEEE $/&! (11O1 EEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEE PL>E'G&'*: parameter SpLoutS ma, beneBit Brom use oB t/e <O%OP8 compiler /int

%op,rig/t @ &''"A Oracle) .ll rig/ts reserved)

SQLKPlus >arning =essages: (Cample Use t/e S9O> (11O1S command in SQLKPlus to displa, t/e compilation errors oB a stored procedure) >/en ,ou speciB, t/is option 2it/ no argumentsA SQLKPlus displa,s t/e compilation errors Bor t/e most recentl, created or altered stored procedure) IB SQLKPlus displa,s a compilation 2arnings message aBter ,ou create or alter a stored procedureA ,ou can use S9O> (11O1S commands to obtain more inBormation) >it/ t/e introduction oB t/e support Bor PL/SQL 2arningsA t/e range oB Beedbac5 messages is eCpanded to include a t/ird message as Bollo2s:
SP&E'#CC: ^ob3ect\ created 2it/ compilation 2arnings)

ra c O

0/is enables ,ou to diBBerentiate bet2een t/e occurrence oB a compilation 2arning and a compilation error) 8ou must correct an error iB ,ou 2ant to use t/e stored procedureA 2/ereas a 2arning is Bor inBormational purposes onl,) 0/e SP& preBiC is included 2it/ t/e 2arning messageA because t/is provides ,ou 2it/ t/e abilit, to loo5 up t/e corresponding message number in t/e SQLKPlus UserFs uide and 1eBerence to determine t/e cause and action Bor t/e particular message) <ote: 0/e S9O> SQLKPlus command is not supported in t/e SQL Developer 1)+)! version t/at is used in t/is class) 8ou can vie2 t/e compiler errors and 2arnings using t/e US(1LT.LLLTD6.L(11O1S data dictionar, vie2s)

c ra O l, - On

, em ad .c

le

l ae rn Uste

Oracle Database 11g: Develop PL/SQL Program Units 1' E &&

In

uidelines Bor Using PLSQLL>.1<I< S


0/e settings Bor t/e PLSQLL>.1<I< S parameter are stored along 2it/ eac/ compiled subprogram) IB ,ou recompile t/e subprogram using one oB t/e Bollo2ing statementsA t/e current settings Bor t/at session are used:
M %1(.0( O1 1(PL.%( M .L0(1 ))) %O=PIL(

IB ,ou recompile t/e subprogram using t/e .L0(1 ))) %O=PIL( statement 2it/ t/e 1(US( S(00I< S clauseA t/e original setting stored 2it/ t/e program is used)

%op,rig/t @ &''"A Oracle) .ll rig/ts reserved)

uidelines Bor Using PLSQLL>.1<I< S .s alread, statedA t/e PLSQLL>.1<I< S parameter can be set at t/e session level or t/e s,stem level) 0/e settings Bor t/e PLSQLL>.1<I< S parameter are stored along 2it/ eac/ compiled subprogram) IB ,ou recompile t/e subprogram 2it/ a %1(.0( O1 1(PL.%( statementA t/e current settings Bor t/at session are used) IB ,ou recompile t/e subprogram 2it/ an .L0(1)))%O=PIL( statementA t/en t/e current session setting is used unless ,ou speciB, t/e 1(US( S(00I< S clause in t/e statementA 2/ic/ uses t/e original setting t/at is stored 2it/ t/e subprogram)

c ra O l, - On

, em ad .c

ra c O

le In

l ae rn Uste

Oracle Database 11g: Develop PL/SQL Program Units 1' E &*

Lesson .genda
Using t/e PLSQLL%OD(L08P( and PLSQLLOP0I=I7(LL(V(L PL/SQL %ompilation Initiali4ation Parameters Using t/e PL/SQL %ompileE0ime >arnings:
M Using t/e PLSQLL>.1<I< Initiali4ation Parameter M Using t/e D6=SL>.1<I< Pac5age subprograms

%op,rig/t @ &''"A Oracle) .ll rig/ts reserved)

l c ra O l, - On ra c O le In l ae rn Uste e

, em ad .c

Oracle Database 11g: Develop PL/SQL Program Units 1' E &!

Setting %ompiler >arning Levels: Using t/e D6=SL>.1<I< Pac5age

Quer, settings

=odiB, settings

D6=SL>.1<I< S pac5age subprograms

1estore settings

%op,rig/t @ &''"A Oracle) .ll rig/ts reserved)

Setting %ompiler >arning Levels: Using t/e D6=SL>.1<I< Pac5age Use t/e D6=SL>.1<I< pac5age to programmaticall, manipulate t/e be/avior oB current s,stem or session PL/SQL 2arning settings) 0/e D6=SL>.1<I< pac5age provides a 2a, to manipulate t/e be/avior oB PL/SQL 2arning messagesA in particular b, reading and c/anging t/e setting oB t/e PLSQLL>.1<I< S initiali4ation parameter to control 2/at 5inds oB 2arnings are suppressedA displa,edA or treated as errors) 0/is pac5age provides t/e interBace to Puer,A modiB,A and delete current s,stem or session settings) 0/e D6=SL>.1<I< pac5age is valuable iB ,ou are 2riting a development environment t/at compiles PL/SQL subprograms) Using t/e pac5age interBace routinesA ,ou can control PL/SQL 2arning messages programmaticall, to suit ,our rePuirements)

c ra O l, - On

, em ad .c
Delete settings

ra c O

le In

l ae rn Uste

Oracle Database 11g: Develop PL/SQL Program Units 1' E &+

Setting %ompiler >arning Levels: Using t/e D6=SL>.1<I< Pac5age HcontinuedI Overvie2 oB PL/SQL %ompileE0ime >arnings Bor Subprograms: (Cample .ssume t/at ,ou 2rite some code to compile PL/SQL code) 8ou 5no2 t/at t/e compiler issues perBormance 2arnings 2/en passing collection variables as OU0 or I< OU0 parameters 2it/out speciB,ing t/e <O%OP8 /int) 0/e general environment t/at calls ,our compilation utilit, ma, or ma, not /ave appropriate 2arningElevel settings) In an, caseA ,our business rules indicate t/at t/e calling environment set must be preserved and t/at ,our compilation process s/ould suppress t/e 2arnings) 6, calling subprograms in t/e D6=SL>.1<I< pac5ageA ,ou can detect t/e current 2arning settingsA c/ange t/e settings to suit ,our business rePuirementsA and restore t/e original settings 2/en ,our processing /as completed) >/en ,ou use t/e .L0(1 S(SSIO< or .L0(1 S8S0(= command to set t/e PLSQLL>.1<I< S parameterA t/e ne2 value speciBied completel, replaces t/e previous value) . ne2 pac5ageA D6=SL>.1<I< is available in Oracle Database 1'g t/at /as interBaces to Puer, and incrementall, c/ange t/e setting Bor t/e PLSQLL>.1<I< S parameter and ma5e it more speciBic to ,our rePuirements) 0/e D6=S)>.1<I< pac5age can be used to c/ange t/e PLSQLL>.1<I< S parameter incrementall,A so t/at ,ou can set t/e 2arnings t/at ,ou 2ant to setA 2it/out /aving to 2or5 out /o2 to preserve t/e values oB an, 2arnings not oB direct interest to ,ou) :or eCampleA t/e D6. ma, onl, enable severe 2arnings Bor t/e entire database in t/e initiali4ation parameter BileA but a developer 2/o is testing ne2 code ma, 2ant to vie2 speciBic perBormance and inBormational messages) 0/e developer can t/en use t/e D6=SL>.1<I< pac5age to incrementall, add t/e speciBic 2arnings t/at /e or s/e 2is/es to see) 0/is allo2s t/e developer to vie2 t/e messages t/at /e or s/e 2ants to see 2it/out replacing t/e D6.Fs settings)

l c ra O l, - On ra c O le In l ae rn Uste e

, em ad .c

Oracle Database 11g: Develop PL/SQL Program Units 1' E &$

Using t/e D6=SL>.1<I< Pac5age Subprograms

Scenario Set 2arnings

Subprograms to Use .DDL>.1<I< LS(00I< L%.0 HprocedureI .DDL>.1<I< LS(00I< L<U= HprocedureI (0L>.1<I< LS(00I< L%.0 HBunctionI (0L>.1<I< LS(00I< L<U= HBunctionI (0L>.1<I< LS(00I< LS01I< HBunctionI S(0L>.1<I< LS(00I< LS01I< HprocedureI (0L%.0( O18 HBunctionI

Quer, 2arnings

1eplace 2arnings et t/e 2arningsF categories names

%op,rig/t @ &''"A Oracle) .ll rig/ts reserved)

Using t/e D6=SL>.1<I< Subprograms 0/e Bollo2ing is a list oB t/e D6=SL>.1<I< subprograms: .DDL>.1<I< LS(00I< L%.0: =odiBies t/e current session or s,stem 2arning settings oB t/e 2arningLcategor, previousl, supplied .DDL>.1<I< LS(00I< L<U=: =odiBies t/e current session or s,stem 2arning settings oB t/e 2arningLnumber previousl, supplied (0L%.0( O18: 1eturns t/e categor, nameA given t/e message number (0L>.1<I< LS(00I< L%.0: 1eturns t/e speciBic 2arning categor, in t/e session (0L>.1<I< LS(00I< L<U=: 1eturns t/e speciBic 2arning number in t/e session (0L>.1<I< LS(00I< LS01I< : 1eturns t/e entire 2arning string Bor t/e current session S(0L>.1<I< LS(00I< LS01I< : 1eplaces previous settings 2it/ t/e ne2 value

c ra O l, - On

, em ad .c

ra c O

<ote: :or additional inBormation about t/e above subprogramsA reBer to Oracle Database PL/SQL Pac5ages and 0,pes 1eBerence 11g 1elease & H11)&I)

le

l ae rn Uste

Oracle Database 11g: Develop PL/SQL Program Units 1' E &G

In

0/e D6=SL>.1<I< Procedures: S,ntaCA ParametersA and .llo2ed Values


(O(%U0( D6=SL>.1<I< ).DDL>.1<I< LS(00I< L%.0 HE 2arningLcategor,I<V.1%9.1&A 2arningLvalueI<V.1%9.1&A scopeI<V.1%.91&IR

(O(%U0( D6=SL>.1<I< ).DDL>.1<I< LS(00I< L<U= HE 2arningLnumberI<<U=6(1A 2arningLvalueI<V.1%9.1&A scopeI<V.1%.91&IR

(O(%U0( D6=SL>.1<I< )S(0L>.1<I< LS(00I< LS01I< HE 2arningLvalueI<V.1%9.1&A scopeI<V.1%9.1&IR

%op,rig/t @ &''"A Oracle) .ll rig/ts reserved)

0/e D6=SL>.1<I< Procedures: S,ntaCA ParametersA and .llo2ed Values 0/e 2arningLcategor, is t/e name oB t/e categor,) 0/e allo2ed values are: .LL I<:O1=.0IO<.L S(V(1( P(1:O1=.<%() 0/e 2arningLvalue is t/e value Bor t/e categor,) 0/e allo2ed values are: (<.6L( DIS.6L( (11O1

ra c O

0/e 2arningLnumber is t/e 2arning message number) 0/e allo2ed values are all valid 2arning numbers) 0/e scope speciBies 2/et/er t/e c/anges are being perBormed in t/e session conteCt or t/e s,stem conteCt) 0/e allo2ed values are S(SSIO< or S8S0(=) Using S8S0(= rePuires t/e .L0(1 S8S0(= privilege)

c ra O l, - On

, em ad .c

le

l ae rn Uste

Oracle Database 11g: Develop PL/SQL Program Units 1' E &#

In

0/e D6=SL>.1<I< Procedures: (Cample

EE EE EE EE EE

(stablis/ t/e Bollo2ing 2arning setting string in t/e current session: (<.6L(:I<:O1=.0IO<.LA DIS.6L(:P(1:O1=.<%(A (<.6L(:S(V(1(

(O(%U0( D6=SL>.1<I< )S(0L>.1<I< LS(00I< LS01I< HE S(<.6L(:.LLSA SS(SSIO<SIR (O(%U0( D6=SL>.1<I< ).DDL>.1<I< LS(00I< L%.0HE SP(1:O1=.<%(SASDIS.6L(SA SS(SSIO<SIR

%op,rig/t @ &''"A Oracle) .ll rig/ts reserved)

Using D6=SL>.1<I< Procedures: (Cample Using t/e S(0L>.1<I< LS(00I< LS01I< procedureA ,ou can set one 2arning setting) IB ,ou /ave multiple 2arning settingsA ,ou s/ould perBorm t/e Bollo2ing steps: 1) %all S(0L>.1<I< LS(00I< LS01I< to set t/e initial 2arning setting string) &) %all .DDL>.1<I< LS(00I< L%.0 Hor .DDL>.1<I< LS(00I< L<U=I repeatedl, to add more settings to t/e initial string) 0/e eCample in t/e slide establis/es t/e Bollo2ing 2arning setting string in t/e current session:
(<.6L(:I<:O1=.0IO<.LADIS.6L(:P(1:O1=.<%(A(<.6L(:S(V(1(

c ra O l, - On

, em ad .c

ra c O

le In

l ae rn Uste

Oracle Database 11g: Develop PL/SQL Program Units 1' E &"

0/e D6=SL>.1<I< :unctions: S,ntaCA ParametersA and .llo2ed Values


D6=SL>.1<I< ) (0L>.1<I< LS(00I< L%.0 HE 2arningLcategor, I< V.1%9.1&I 1(0U1< 2arningLvalueR

D6=SL>.1<I< ) (0L>.1<I< LS(00I< L<U= HE 2arningLnumber I< <U=6(1I 1(0U1< 2arningLvalueR

D6=SL>.1<I< ) (0L>.1<I< LS(00I< LS01I< 1(0U1< plsLintegerR

D6=SL>.1<I< ) (0L%.0( O18 HE 2arningLnumber I<plsLintegerI 1(0U1< V.1%9.1&R

%op,rig/t @ &''"A Oracle) .ll rig/ts reserved)

0/e D6=SL>.1<I< :unctions: S,ntaCA ParametersA and .llo2ed Values 0/e 2arningLcategor, is t/e name oB t/e categor,) 0/e allo2ed values are: .LL I<:O1=.0IO<.L S(V(1( P(1:O1=.<%( 0/e 2arningLnumber is t/e 2arning message number) 0/e allo2ed values are all valid 2arning numbers) 0/e scope speciBies 2/et/er t/e c/anges are being perBormed in t/e session conteCt or t/e s,stem conteCt) 0/e allo2ed values are S(SSIO< or S8S0(=) Using S8S0(= rePuires t/e .L0(1 S8S0(= privilege) <ote: Use t/e (0L>.1<I< LS(00I< LS01I< Bunction 2/en ,ou do not /ave t/e S(L(%0 privilege on t/e v[parameter or v[parameter& BiCed tablesA or iB ,ou 2ant to parse t/e 2arning string ,ourselB and t/en modiB, and set t/e ne2 value using S(0L>.1<I< LS(00I< LS01I< )

c ra O l, - On

, em ad .c

ra c O

le

l ae rn Uste

Oracle Database 11g: Develop PL/SQL Program Units 1' E *'

In

0/e D6=SL>.1<I< :unctions: (Cample

EE Determine t/e current session 2arning settings S(0 S(1V(1OU0PU0 O< (O(%U0( D6=SLOU0PU0)PU0LLI<(H E D6=SL>.1<I< ) (0L>.1<I< LS(00I< LS01I< IR

EE Determine t/e categor, Bor 2arning message number EE PL>E'G&'* S(0 S(1V(1OU0PU0 O< (O(%U0( D6=SLOU0PU0)PU0LLI<(H E D6=SL>.1<I< ) (0L%.0( O18HG&'*IIR

%op,rig/t @ &''"A Oracle) .ll rig/ts reserved)

<ote 0/e message numbers must be speciBied as positive integersA because t/e data t,pe Bor t/e (0L%.0( O18 parameter is PLSLI<0( (1 Hallo2ing positive integer valuesI)

c ra O l, - On

, em ad .c

ra c O

le In

l ae rn Uste

Oracle Database 11g: Develop PL/SQL Program Units 1' E *1

Using D6=SL>.1<I< : (Cample

%1(.0( O1 1(PL.%( P1O%(DU1( compileLcodeHpLp5gLname V.1%9.1&I IS vL2arnLvalueV.1%9.1&H&''IR vLcompileLstmt V.1%9.1&H&''I :Z S.L0(1 P.%?. ( STT pLp5gLname TTS %O=PIL(SR 6( I< vL2arnLvalue :Z D6=SL>.1<I< ) (0L>.1<I< LS(00I< LS01I< R D6=SLOU0PU0)PU0LLI<(HS%urrent 2arning settings: STT vL2arnLvalueIR D6=SL>.1<I< ).DDL>.1<I< LS(00I< L%.0H SP(1:O1=.<%(SA SDIS.6L(SA SS(SSIO<SIR D6=SLOU0PU0)PU0LLI<(HS=odiBied 2arning settings: STT D6=SL>.1<I< ) (0L>.1<I< LS(00I< LS01I< IR (O(%U0( I==(DI.0( vLcompileLstmtR D6=SL>.1<I< )S(0L>.1<I< LS(00I< LS01I< HvL2arnLvalueA SS(SSIO<SIR D6=SLOU0PU0)PU0LLI<(HS1estored 2arning settings: STT D6=SL>.1<I< ) (0L>.1<I< LS(00I< LS01I< IR (<DR /

%op,rig/t @ &''"A Oracle) .ll rig/ts reserved)

Using D6=SL>.1<I< : (Cample

l c ra O l, - On e

<ote: 6eBore ,ou run t/e code provided in t/e eCample in t/e slideA ,ou must create t/e =8LP? script Bound in demoL1'L**)sPl) 0/is demo script creates t/e =8LP? pac5age)

, em ad .c

In t/e eCample in t/e slideA t/e compileLcode procedure is designed to compile a named PL/SQL pac5age) 0/e code suppresses t/e P(1:O1=.<%( categor, 2arnings) 0/e calling environmentFs 2arning settings must be restored aBter t/e compilation is perBormed) 0/e code does not 5no2 2/at t/e calling environment 2arning settings areR it uses t/e (0L>.1<I< LS(00I< LS01I< Bunction to save t/e current setting) 0/is value is used to restore t/e calling environment setting using t/e D6=SL>.1<I< )S(0L>.1<I< LS(00I< LS01I< procedure in t/e last line oB t/e eCample code) 6eBore compiling t/e pac5age using <ative D,namic SQLA t/e compileLcode procedure alters t/e current sessionE2arning level b, disabling 2arnings Bor t/e P(1:O1=.<%( categor,) 0/e code also prints t/e originalA modiBiedA and t/e restored 2arning settings)

ra c O

le

l ae rn Uste

Oracle Database 11g: Develop PL/SQL Program Units 1' E *&

In

Using D6=SL>.1<I< : (Cample


(O(%U0( D6=SL>.1<I< )S(0L>.1<I< LS(00I< LS01I< HE S(<.6L(:.LLSA SS(SSIO<SIR

]codeL1'L*&Ls)sPl

]codeL1'L**Lcs)sPl ME compiles t/e D(P0LP? pac5age

%op,rig/t @ &''"A Oracle) .ll rig/ts reserved)

Using D6=SL>.1<I< : (Cample HcontinuedI

l e

In t/e eCample in t/e slideA t/e eCample provided in t/e previous slide is tested) :irstA enable all compiler 2arnings) <eCtA run t/e script on t/e previous page) :inall,A call t/e compileLcode procedure and pass it an eCisting pac5age nameA D(P0LP? A as a parameter)

c ra O l, - On

, em ad .c

ra c O

le In

l ae rn Uste

Oracle Database 11g: Develop PL/SQL Program Units 1' E **

Using t/e PL> '$''" >arning =essage


0/e PL> 2arning indicates t/at t/e O09(1S /andler oB ,our PL/SQL subroutine can eCit 2it/out eCecuting:
M Some Borm oB 1.IS(A or M . call to t/e standard procedure 1.IS(L.PPLI%.0IO<L(11O1

. good programming practice suggests t/at O09(1S /andlers must al2a,s pass an eCception up2ard)

%op,rig/t @ &''"A Oracle) .ll rig/ts reserved)

Using t/e <e2 PL> '$''" >arning .s a good programming practiceA ,ou s/ould /ave ,our O09(1S eCception /andler pass t/e eCception up2ard to t/e calling subroutine) IB ,ou Bail to add t/is Bunctionalit,A ,ou run t/e ris5 oB /aving eCceptions go unnoticed) 0o avoid t/is Bla2 in ,our codeA ,ou can turn on 2arnings Bor ,our session and recompile t/e code t/at ,ou 2ant to veriB,) IB t/e O09(1S /andler does not /andle t/e eCceptionA t/e PL> '$''" 2arning 2ill inBorm ,ou)

<ote: PL> '$''" is not t/e onl, ne2 2arning message in Oracle Database 11g) :or a complete list oB all PL> 2arningsA see t/e Oracle Database (rror =essages11g 1elease & H11)&I guide)

c ra O l, - On

, em ad .c

ra c O

le In

l ae rn Uste

Oracle Database 11g: Develop PL/SQL Program Units 1' E *!

0/e PL> '$''" >arning: (Cample


%1(.0( O1 1(PL.%( P1O%(DU1( pHi I< V.1%9.1&I IS 6( I< I<S(10 I<0O tHcolLaI V.LU(S HiIR (O%(P0IO< >9(< O09(1S 09(< nullR (<D pR / .L0(1 P1O%(DU1( P %O=PIL( PLSQLL2arnings Z Senable:allS 1(US( S(00I< SR

S(L(%0 K :1O= userLerrors >9(1( name Z SPS

%op,rig/t @ &''"A Oracle) .ll rig/ts reserved)

0/e PL> '$''" >arning: (Cample .Bter running t/e Birst code eCample in t/e slide and aBter compiling t/e procedure using t/e Ob3ect <avigation treeA t/e %ompiler M Log tab displa,s t/e PL>E'$''" 2arning) 8ou can also use t/e userLerror data dictionar, vie2 to displa, t/e error) 0/e deBinition oB table t t/at is used in t/e slide eCample is as Bollo2s:
%1(.0( 0.6L( t HcolLa <U=6(1IR

c ra O l, - On

, em ad .c

ra c O

le In

l ae rn Uste

Oracle Database 11g: Develop PL/SQL Program Units 1' E *+

Qui4
0/e categories oB PL/SQL compileEtime 2arning messages are: 1) S(V(1( &) P(1:O1=.<%( *) I<:O1=.0IO<.L !) .ll +) %1I0I%.L

%op,rig/t @ &''"A Oracle) .ll rig/ts reserved)

.ns2ers: 1A &A *A ! PL/SQL 2arning messages are divided into categoriesA so t/at ,ou can suppress or displa, groups oB similar 2arnings during compilation) 0/e categories are: S(V(1(: =essages Bor conditions t/at ma, cause uneCpected be/avior or 2rong resultsA suc/ as aliasing problems 2it/ parameters) P(1:O1=.<%(: =essages Bor conditions t/at ma, cause perBormance problemsA suc/ as passing a V.1%9.1& value to a <U=6(1 column in an I<S(10 statement) I<:O1=.0IO<.L: =essages Bor conditions t/at do not /ave an eBBect on perBormance or correctnessA but t/at ,ou ma, 2ant to c/ange to ma5e t/e code more maintainableA suc/ as unreac/able code t/at can never be eCecuted) .LL: Displa,s all categories)

c ra O l, - On

, em ad .c

ra c O

le In

l ae rn Uste

Oracle Database 11g: Develop PL/SQL Program Units 1' E *$

Summar,
In t/is lessonA ,ou s/ould /ave learned /o2 to: Use t/e PL/SQL compiler initiali4ation parameters Use t/e PL/SQL compileEtime 2arnings

%op,rig/t @ &''"A Oracle) .ll rig/ts reserved)

l c ra O l, - On ra c O le In l ae rn Uste e

, em ad .c

Oracle Database 11g: Develop PL/SQL Program Units 1' E *G

Practice 1': Overvie2


0/is practice covers t/e Bollo2ing topics: Displa,ing t/e compiler initiali4ation parameters (nabling native compilation Bor ,our session and compiling a procedure Disabling t/e compiler 2arningsA and t/en restoring t/e original sessionE2arning settings IdentiB,ing t/e categories Bor some compilerE2arning message numbers

%op,rig/t @ &''"A Oracle) .ll rig/ts reserved)

Practice 1': Overvie2 In t/is practiceA ,ou displa, t/e compiler initiali4ation parameters) 8ou t/en enable native compilation Bor ,our session and compile a procedure) 8ou t/en suppress all compiler 2arnings categories and t/en restore t/e original sessionE2arning settings) :inall,A ,ou identiB, t/e categories Bor some compilerE2arning message numbers)

c ra O l, - On

, em ad .c

ra c O

le In

l ae rn Uste

Oracle Database 11g: Develop PL/SQL Program Units 1' E *#

=anaging PL/SQL %ode

%op,rig/t @ &''"A Oracle) .ll rig/ts reserved)

l c ra O l, - On ra c O le In l ae rn Uste e

, em ad .c

Ob3ectives
.Bter completing t/is lessonA ,ou s/ould be able to do t/e Bollo2ing: Describe and use conditional compilation 9ide PL/SQL source code using d,namic obBuscation and t/e >rap utilit,

%op,rig/t @ &''"A Oracle) .ll rig/ts reserved)

Lesson .im 0/is lesson introduces t/e conditional compilation and obBuscating or 2rapping PL/SQL code)

c ra O l, - On

, em ad .c

ra c O

le In

l ae rn Uste

Oracle Database 11g: Develop PL/SQL Program Units 11 E &

Lesson .genda
Using conditional compilation ObBuscating PL/SQL code

%op,rig/t @ &''"A Oracle) .ll rig/ts reserved)

l c ra O l, - On ra c O le In l ae rn Uste e

, em ad .c

Oracle Database 11g: Develop PL/SQL Program Units 11 E *

>/at Is %onditional %ompilationJ


(nables ,ou to customi4e t/e Bunctionalit, in a PL/SQL application 2it/out removing an, source code: Utili4e t/e latest Bunctionalit, 2it/ t/e latest database release or disable t/e ne2 Beatures to run t/e application against an older release oB t/e database) .ctivate debugging or tracing Bunctionalit, in t/e development environment and /ide t/at Bunctionalit, in t/e application 2/ile it runs at a production site)

[I:A [09(<A [(LS(A [(LSI:A [(<DA [[A [(11O1


1eserved preprocessor control to5ens

%op,rig/t @ &''"A Oracle) .ll rig/ts reserved)

>/at Is %onditional %ompilationJ %onditional compilation enables ,ou to selectivel, include codeA depending on t/e values oB t/e conditions evaluated during compilation) :or eCampleA conditional compilation enables ,ou to determine 2/ic/ PL/SQL Beatures in a PL/SQL application are used Bor speciBic database releases) 0/e latest PL/SQL Beatures in an application can be run on a ne2 database release and at t/e same time t/ose Beatures can be conditional so t/at t/e same application is compatible 2it/ a previous database release) %onditional compilation is also useBul 2/en ,ou 2ant to eCecute debugging procedures in a development environmentA but 2ant to turn oBB t/e debugging routines in a production environment) 6eneBits oB %onditional %ompilation Support Bor multiple versions oB t/e same program in one source code (as, maintenance and debugging oB code (as, migration oB code to a diBBerent release oB t/e database

c ra O l, - On

, em ad .c

ra c O

le In

l ae rn Uste

Oracle Database 11g: Develop PL/SQL Program Units 11 E !

9o2 Does %onditional %ompilation >or5J

Selection directives: Use t/e [I: to5en)

InPuir, directives: Use t/e [[ to5en)

(rror directives: Use t/e [(11O1 to5en)

D6=SLP1(P1O%(SSO1 pac5age

D6=SLD6LV(1SIO< pac5age

%op,rig/t @ &''"A Oracle) .ll rig/ts reserved)

9o2 Does %onditional %ompilation >or5J 8ou can use conditional compilation b, embedding directives in ,our PL/SQL source programs) >/en t/e PL/SQL program is submitted Bor compilationA a preprocessor evaluates t/ese directives and selects parts oB t/e program to be compiled) 0/e selected program source is t/en /anded oBB to t/e compiler Bor compilation) InPuir, directives use t/e [[ to5en to ma5e inPuiries about t/e compilation environment suc/ as t/e value oB a PL/SQL compiler initiali4ation parameters PLSQLL%%:L. S or PLSQLLOP0I=I7(LL(V(L Bor t/e unit being compiled) 0/is directive can be used in con3unction 2it/ t/e conditional selection directive to select t/e parts oB t/e program to compile) Selection directives can test inPuir, directives or static pac5age constants b, using t/e [I: construct to branc/ sections oB code Bor possible compilation iB a condition is satisBied) (rror directives issue a compilation error iB an uneCpected condition is encountered during conditional compilation using t/e [(11O1 to5en) 0/e D6=SLD6LV(1SIO< pac5age provides database version and release constants t/at can be used Bor conditional compilation) 0/e D6=SLP1(P1O%(SSO1 pac5age provides subprograms Bor accessing t/e postEprocessed source teCt t/at is selected b, conditional compilation directives in a PL/SQL unit)

c ra O l, - On

, em ad .c

ra c O

le

l ae rn Uste

Oracle Database 11g: Develop PL/SQL Program Units 11 E +

In

Using Selection Directives


[I: ^6ooleanEeCpression\ [09(< 0eCt [(LS(I: ^6ooleanEeCpression\ [09(< 0eCt ))) [(LS( 0eCt [(<D

D(%L.1( %U1SO1 cur IS S(L(%0 emplo,eeLid :1O= emplo,ees >9(1( [I: m,appLtaCLpac5age)ne2LtaCLcode [09(< salar, \ &''''R [(LS( salar, \ +''''R [(<D 6( I< OP(< curR ))) (<DR

%op,rig/t @ &''"A Oracle) .ll rig/ts reserved)

Using Selection Directives 0/e conditional selection directive loo5s li5e and operates li5e t/e I:E09(<E(LS( mec/anism in PL/SQL proper) >/en t/e preprocessor encounters [09(<A it veriBies t/at t/e teCt bet2een [I: and [09(< is a static eCpression) IB t/e c/ec5 succeeds and t/e result oB t/e evaluation is 01U(A t/en t/e PL/SQL program teCt bet2een [09(< and [(LS( Hor [(LSI:I is selected Bor compilation) 0/e selection condition Ht/e eCpression bet2een [I: and [09(<I can be constructed b, reBerring to constants deBined in anot/er pac5age or an inPuir, directive or some combination oB t/e t2o) In t/e eCample in t/e slideA conditional selection directive c/ooses bet2een t2o versions oB t/e cursorA curA on t/e basis oB t/e value oB =8.PPL0.OLP.%?. ()<(>L0.OL%OD() IB t/e value is 01U(A t/en emplo,ees 2it/ salar, \ &'''' are selectedA else emplo,ees 2it/ salar, \ +'''' are selected)

c ra O l, - On

, em ad .c

ra c O

le In

l ae rn Uste

Oracle Database 11g: Develop PL/SQL Program Units 11 E $

Using PredeBined and UserEDeBined InPuir, Directives


PLSQLL%%:L. S PLSQLL%OD(L08P( PLSQLLOP0I=I7(LL(V(L PLSQLL>.1<I< S <LSLL(< 09LS(=.<0I%S PLSQLLLI<( PLSQLLU<I0

PredeBined inPuir, directives

PLSQLL%%:L. S Z SplsPlLccBlags:trueAdebug:trueAdebug:'SR UserEdeBined inPuir, directives

%op,rig/t @ &''"A Oracle) .ll rig/ts reserved)

Using PredeBined and UserEDeBined InPuir, Directives .n inPuir, directive can be predeBined or userEdeBined) 0/e Bollo2ing describes t/e order oB t/e processing Blo2 2/en conditional compilation attempts to resolve an inPuir, directive: 1) 0/e ID is used as an inPuir, directive in t/e Borm [[id Bor t/e searc/ 5e,) &) 0/e t2oEpass algorit/m proceeds as Bollo2s: a) 0/e string in t/e PLSQLL%%:L. S initiali4ation parameter is scanned Brom rig/t to leBtA searc/ing 2it/ ID Bor a matc/ing name Hnot case sensitiveIR done iB Bound) b) 0/e predeBined inPuir, directives are searc/edR done iB Bound) *) IB t/e [[ID cannot be resolved to a valueA t/en t/e PL>E$''* 2arning message is reported iB t/e source teCt is not 2rapped) 0/e literal <ULL is substituted as t/e value Bor undeBined inPuir, directives) <ote t/at iB t/e PL/SQL code is 2rappedA t/en t/e 2arning message is disabled so t/at t/e undeBined inPuir, directive is not revealed) In t/e eCample in t/e slideA t/e value oB [[debug is ' and t/e value oB [[plsPlLccBlags is 01U() <ote t/at t/e value oB [[plsPlLccBlags resolves to t/e userEdeBined plsPlLccBlags inside t/e value oB t/e PLSQLL%%:L. S compiler parameter) 0/is occurs because a userEdeBined directive overrides t/e predeBined one)

c ra O l, - On

, em ad .c

ra c O

le

l ae rn Uste

Oracle Database 11g: Develop PL/SQL Program Units 11 E G

In

0/e PLSQLL%%:L. S Parameter and t/e InPuir, Directive


Use t/e PLSQLL%%:L. S parameter to control conditional compilation oB eac/ PL/SQL librar, unit independentl,)

PLSQLL%%:L. S Z S^v1\:^c1\A^v&\:^c&\A)))A^vn\:^cn\S

.L0(1 S(SSIO< S(0 PLSQLL%%:L. S Z SplsPlLccBlags:trueA debug:trueA debug:'SR

PLSQLL%%:L. S initiali4ation parameter

InPuir, directive

%op,rig/t @ &''"A Oracle) .ll rig/ts reserved)

0/e PLSQLL%%:L. S Parameter and t/e InPuir, Directive

ra c O

Oracle Database 1'g 1elease & introduced a ne2 Oracle initiali4ation parameter PLSQLL%%:L. S Bor use 2it/ conditional compilation) 0/is d,namic parameter enables ,ou to set up nameEvalue pairs) 0/e names Hcalled Blag namesI can t/en be reBerenced in inPuir, directives) PLSQLL%%:L. S provides a mec/anism t/at allo2s PL/SQL programmers to control conditional compilation oB eac/ PL/SQL librar, unit independentl,) Values vi: 9as t/e Borm oB an unPuoted PL/SQL identiBier) It is unrestricted and can be a reserved 2ord or a 5e,2ord) 0/e teCt is not case sensitive) (ac/ one is 5no2n as a Blag or Blag name) (ac/ vi can occur more t/an once in t/e stringA eac/ occurrence can /ave a diBBerent Blag valueA and t/e Blag values can be oB diBBerent 5inds) ci: %an be an, oB t/e Bollo2ing: E . PL/SQL 6oolean literal E . PLSLI<0( (1 literal E 0/e literal <ULL HdeBaultI) 0/e teCt is not case sensitive) (ac/ one is 5no2n as a Blag value and corresponds to a Blag name)

c ra O l, - On

, em ad .c

le

l ae rn Uste

Oracle Database 11g: Develop PL/SQL Program Units 11 E #

In

Displa,ing t/e PLSQLL%%:L. S Initiali4ation Parameter Setting

S(L(%0 nameA t,peA plsPlLccBlags :1O=userLplsPlLob3ectLsettings

)))

%op,rig/t @ &''"A Oracle) .ll rig/ts reserved)

Displa,ing t/e PLSQLL%%:L. S Initiali4ation Parameter Setting Use t/e US(1T.LLTD6.LPLSQLLO6;(%0LS(00I< S data dictionar, vie2s to displa, t/e settings oB a PL/SQL ob3ect) 8ou can deBine an, allo2able value Bor PLSQLL%%:L. S) 9o2everA Oracle recommends t/at t/is parameter be used Bor controlling t/e conditional compilation oB debugging or tracing code) 0/e Blag names can be set to an, identiBierA including reserved 2ords and 5e,2ords) 0/e values must be t/e literals 01U(A :.LS(A or <ULLA or a PLSLI<0( (1 literal) 0/e Blag names and values are not case sensitive) 0/e PLSQLL%%:L. S parameter is a PL/SQL compiler parameter Hli5e ot/er compiler parametersI and is stored 2it/ t/e PL/SQL program unit) %onsePuentl,A iB t/e PL/SQL program gets recompiled later 2it/ t/e 1(US( S(00I< S clause HeCampleA .L0(1 P.%?. ( _1(US( S(00I< SIA t/en t/e same value oB PLSQLL%%:L. S is used Bor t/e recompilation) 6ecause t/e PLSQLL%%:L. S parameter can be set to a diBBerent value Bor eac/ PL/SQL unitA it provides a convenient met/od Bor controlling conditional compilation on a per unit basis)

c ra O l, - On

, em ad .c

ra c O

le

l ae rn Uste

Oracle Database 11g: Develop PL/SQL Program Units 11 E "

In

0/e PLSQLL%%:L. S Parameter and t/e InPuir, Directive: (Cample


.L0(1 S(SSIO< S(0 PLSQLL%%:L. S Z S0racing:trueSR %1(.0( O1 1(PL.%( P1O%(DU1( P IS 6( I< [I: [[tracing [09(< D6=SLOU0PU0)PU0LLI<( HS01.%I< SIR [(<D (<D PR

S(L(%0 nameA plsPlLccBlags :1O= US(1LPLSQLLO6;(%0LS(00I< S >9(1( name Z SPSR

%op,rig/t @ &''"A Oracle) .ll rig/ts reserved)

0/e PLSQLL%%:L. S Parameter and t/e InPuir, Directive: (Cample

In t/e eCample in t/e slideA t/e parameter is set and t/en t/e procedure is created) 0/e setting is stored 2it/ eac/ PL/SQL unit)

c ra O l, - On

, em ad .c

ra c O

le In

l ae rn Uste

Oracle Database 11g: Develop PL/SQL Program Units 11 E 1'

Using %onditional %ompilation (rror Directives to 1aise UserEDeBined (rrors


[(11O1 varc/ar&LstaticLeCpression [(<D .L0(1 S(SSIO< S(0 PlsPlL%%:lags Z S 0raceLLevel:* S / %1(.0( P1O%(DU1( P IS 6( I< [I:[[0raceLLevel Z ' [09(< )))R [(LSI: [[0raceLLevel Z 1 [09(< )))R [(LSI: [[0raceLLevel Z & [09(< )))R [else [error S6ad: STT[[0raceLLevel [(<D ME error EE directive [(<D EE selection directive ends (<D PR

S9O> (11O1S (rrors Bor P1O%(DU1( P: LI<(/%OL (11O1 EEEEEEEE EEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEE $/"PLSE''1G": [(11O1: 6ad: *

%op,rig/t @ &''"A Oracle) .ll rig/ts reserved)

Using %onditional %ompilation (rror Directives to 1aise UserEDeBined (rrors 0/e [(11O1 error directive raises a userEdeBined error and is oB t/e Borm:
[(11O1 varc/ar&LstaticLeCpression [(<D

<ote: varc/ar&LstaticLeCpression must be a V.1%9.1& static eCpression)ee

c ra O l, - On

, em ad .c

ra c O

le In

l ae rn Uste

Oracle Database 11g: Develop PL/SQL Program Units 11 E 11

Using Static (Cpressions 2it/ %onditional %ompilation


6oolean static eCpressions:
M 01U(A :.LS(A <ULLA IS <ULLA IS <O0 <ULL M \ A ^ A \Z A ^Z A Z A ^\A <O0A .<DA O1

PLSLI<0( (1 static eCpressions:


M E&1!G!#*$!# to &1!G!#*$!GA <ULL

V.1%9.1& static eCpressions include:


M TTA <ULLA 0OL%9.1

Static constants:

staticLconstant %O<S0.<0 datat,pe :Z staticLeCpressionR

%op,rig/t @ &''"A Oracle) .ll rig/ts reserved)

Using Static (Cpressions 2it/ %onditional %ompilation .s described earlierA a preprocessor processes conditional directives beBore proper compilation begins) %onsePuentl,A onl, eCpressions t/at can be Bull, evaluated at compile time are permitted in conditional compilation directives) .n, eCpression t/at contains reBerences to variables or Bunctions t/at rePuire t/e eCecution oB t/e PL/SQL are not available during compilation and cannot be evaluated) 0/is subset oB PL/SQL eCpressions allo2ed in conditional compilation directives is reBerred to as static eCpressions) Static eCpressions are careBull, deBined to guarantee t/at iB a unit is automaticall, recompiled 2it/out an, c/anges to t/e values it depends onA t/e eCpressions evaluate in t/e same 2a, and t/e same source is compiled)

ra c O

enerall,A static eCpressions are composed oB t/ree sources: InPuir, directives mar5ed 2it/ [[ %onstants deBined in PL/SQL pac5ages suc/ as D6=SLD6LV(1SIO<) 0/ese values can be combined and compared using t/e ordinar, operations oB PL/SQL) Literals suc/ as 01U(A :.LS(A S%.SA 1&*A <ULL

c ra O l, - On

, em ad .c

le

Static eCpressions can also contain operations t/at include comparisonsA logical 6oolean operations Hsuc/ as O1 and .<DIA or concatenations oB static c/aracter eCpression)

l ae rn Uste

Oracle Database 11g: Develop PL/SQL Program Units 11 E 1&

In

0/e D6=SLD6LV(1SIO< Pac5age: 6oolean %onstants


V(1LL(L" V(1LL(L"L1 V(1LL(L"L& V(1LL(L1' V(1LL(L1'L1 V(1LL(L1'L& V(1LL(L11 V(1LL(L11L1
D6=SLD6LV(1SIO< Pac5age D6=SLD6LV(1SIO< 6oolean constants 01U(J

Oracle 11g 1elease 1

%op,rig/t @ &''"A Oracle) .ll rig/ts reserved)

0/e D6=SLD6LV(1SIO< Pac5age Oracle Database 1'g 1elease & introduced t/e D6=SLD6LV(1SIO< pac5age) 0/is pac5age speciBies t/e Oracle database version and release numbers t/at are useBul 2/en ma5ing simple selections Bor conditional compilation) 0/e constants represent a 6oolean condition t/at evaluates to less t/an or ePual to t/e version and t/e releaseA iB present) (Cample V(1LL(L11 indicates t/at t/e database version ^Z 11) 0/e values oB t/e constants are eit/er 01U( or :.LS() :or eCampleA in an Oracle Database 11g 1elease 1 databaseA V(1LL(L11 and V(1LL(L11L1 are 01U( and all ot/er constants are :.LS()

c ra O l, - On

, em ad .c

ra c O

le In

l ae rn Uste

Oracle Database 11g: Develop PL/SQL Program Units 11 E 1*

0/e D6=SLD6LV(1SIO< Pac5age %onstants

<ame V(1LL(L" V(1LL(L"L1 V(1LL(L"L& V(1LL(L1' V(1LL(L1'L1 V(1LL(L1'L& V(1LL(L11 V(1LL(L11L1

Value :.LS( :.LS( :.LS( 01U( :.LS( 01U( :.LS( 01U(

Description Version ^Z ") Version ^Z " and release ^Z 1) Version ^Z " and release ^Z &) Version ^Z 1') Version ^Z 1' and release ^Z 1) Version ^Z1' and release ^Z &) Version ^Z 11) Version ^Z11 and release ^Z 1)

%op,rig/t @ &''"A Oracle) .ll rig/ts reserved)

0/e D6=SLD6LV(1SIO< Pac5age 0/e pac5age Bor t/e Oracle Database 11g 1elease 1 version is s/o2n belo2:

P.%?. ( D6=SLD6LV(1SIO< IS V(1SIO< %O<S0.<0 PLSLI<0( (1 :Z 11R EE 1D6=S version EE number 1(L(.S( %O<S0.<0 PLSLI<0( (1 :Z 1R EE 1D6=S release EE number verLleL"L1%O<S0.<0 6OOL(.< :Z :.LS(R verLleL"L&%O<S0.<0 6OOL(.< :Z :.LS(R verLleL"%O<S0.<0 6OOL(.< :Z :.LS(R verLleL1'L1%O<S0.<0 6OOL(.< :Z :.LS(R verLleL1'L&%O<S0.<0 6OOL(.< :Z :.LS(R verLleL1'%O<S0.<0 6OOL(.< :Z :.LS(R verLleL11L1%O<S0.<0 6OOL(.< :Z 01U(R verLleL11%O<S0.<0 6OOL(.< :Z 01U(R (<D D6=SLD6LV(1SIO<R

c ra O l, - On

, em ad .c

ra c O

le

0/e D6=SLD6LV(1SIO< pac5age contains diBBerent constants Bor diBBerent Oracle Database releases) 0/e Oracle Database 11g 1elease 1 version oB t/e D6=SLD6LV(1SIO< pac5age uses t/e constants s/o2n in t/e slide)

l ae rn Uste

Oracle Database 11g: Develop PL/SQL Program Units 11 E 1!

In

Using %onditional %ompilation 2it/ Database Versions: (Cample


.L0(1 S(SSIO< S(0 PLSQLL%%:L. S Z Sm,Ldebug::.LS(A m,Ltracing::.LS(SR %1(.0( P.%?. ( m,Lp5g .S SU608P( m,Lreal IS EE %/ec5 t/e database versionA iB \Z 1'gA use 6I<.18LDOU6L( data t,peA EE else use <U=6(1 data t,pe [I: D6=SLD6LV(1SIO<)V(1SIO< ^ 1' [09(<<U=6(1R [(LS( 6I<.18LDOU6L(R [(<D m,Lpi m,LrealR m,Le m,LrealR (<D m,Lp5gR / %1(.0( P.%?. ( 6OD8 m,Lp5g .S 6( I< [I: D6=SLD6LV(1SIO<)V(1SIO< ^ 1' [09(< m,Lpi :Z *)1!'1$!'#&#"''#&"&!*1"!''&G*!*$$$#$*&&GR m,Le :Z &)G1#&#1#&#!+"'!+&*+*$'&#G!G1*+&$$&!"GG+R [(LS( m,Lpi :Z *)1!'1$!'#&#"''#&"&!*1"!''&G*!*$$$#$*&&GdR m,Le :Z &)G1#&#1#&#!+"'!+&*+*$'&#G!G1*+&$$&!"GG+dR [(<D (<D m,Lp5gR /

%op,rig/t @ &''"A Oracle) .ll rig/ts reserved)

Using %onditional %ompilation 2it/ Database Versions: (Cample 0/is eCample also s/o2s t/e use oB t/e PLSQLL%%:L. S parameter) :irstA ,ou set t/e PLSQLL%%:L. S parameter Blag Bor displa,ing debugging code and tracing inBormation)

In t/e eCample in t/e slide on t/is page and t/e neCt pageA conditional compilation is used to speciB, code Bor database versions) %onditional compilation is used to determine 2/et/er t/e 6I<.18LDOU6L( data t,pe can be utili4ed in t/e calculations Bor PL/SQL units in t/e database) 0/e 6I<.18LDOU6L( data t,pe can onl, be used in Oracle Database 1'g or later) IB ,ou are using Oracle Database 1'gA t/en t/e data t,pe Bor m,Lreal is 6I<.18LDOU6L(R ot/er2iseA t/e data t,pe Bor m,Lreal is <U=6(1) In t/e speciBication oB t/e ne2 pac5ageA m,Lp5gA conditional compilation is used to c/ec5 Bor t/e database version) In t/e bod, deBinition oB t/e pac5ageA conditional compilation is used again to set t/e values oB m,Lpi and m,Le Bor Buture calculations based on t/e database version) 0/e result oB t/e slide eCample code is as Bollo2s:

c ra O l, - On

, em ad .c

ra c O

le

l ae rn Uste

Oracle Database 11g: Develop PL/SQL Program Units 11 E 1+

In

Using %onditional %ompilation 2it/ Database Versions: (Cample


%1(.0( O1 1(PL.%( P1O%(DU1( circleLareaHpLradius m,Lp5g)m,LrealI IS vLm,Larea m,Lp5g)m,LrealR vLm,Ldatat,pe V.1%9.1&H*'IR 6( I< vLm,Larea :Z m,Lp5g)m,Lpi K pLradius K pLradiusR D6=SLOU0PU0)PU0LLI<(HS1adius: S TT 0OL%9.1HpLradiusI TT S .rea: S TT 0OL%9.1HvLm,LareaI IR [I: [[m,Ldebug [09(< EE iB m,Ldebug is 01U(A run some debugging code S(L(%0 D.0.L08P( I<0O vLm,Ldatat,pe :1O= US(1L.1 U=(<0S >9(1( O6;(%0L<.=( Z S%I1%L(L.1(.S .<D .1 U=(<0L<.=( Z SPL1.DIUSSR D6=SLOU0PU0)PU0LLI<(HSDatat,pe oB t/e 1.DIUS argument is: S TT vLm,Ldatat,peIR [(<D (<DR /

%.LL circleLareaH+'IR EE Using Oracle Database 11g 1elease &

%op,rig/t @ &''"A Oracle) .ll rig/ts reserved)

Using %onditional %ompilation 2it/ Database Versions: (Cample HcontinuedI In t/e eCample in t/e slideA a ne2 procedure called circleLarea is deBined) 0/is procedure calculates t/e area oB a circle based on t/e values oB t/e variables in t/e m,Lp5g pac5age deBined on t/e previous page) 0/e procedure /as one I< Bormal parameterA radius) 0/e procedure declares a couple oB variables: m,LareaA 2/ic/ is t/e same data t,pe as m,Lreal in m,Lp5gA and m,Ldatat,peA 2/ic/ is a V.1%9.1&H*'I) In t/e procedureFs bod,A m,Larea becomes ePual to t/e value oB m,Lpi set in m,Lp5g multiplied b, t/e value t/at is passed to t/e procedure as a radius) . message is printed displa,ing t/e radius and t/e area oB t/e circle as s/o2n in t/e second code eCample in t/e slide) <ote: IB ,ou 2ant to set m,Ldebug to 01U(A ,ou can ma5e t/is c/ange onl, Bor t/e circleLarea procedure 2it/ t/e 1(US( S(00I< S clause as Bollo2s:

c ra O l, - On

, em ad .c

ra c O

.L0(1 P1O%(DU1( circleLarea %O=PIL( PLSQLL%%:L. S Z Sm,Ldebug:01U(S 1(US( S(00I< SR

le

l ae rn Uste

Oracle Database 11g: Develop PL/SQL Program Units 11 E 1$

In

Using D6=SLP1(P1O%(SSO1 Procedures to Print or 1etrieve Source 0eCt


%.LL D6=SLP1(P1O%(SSO1)P1I<0LPOS0LP1O%(SS(DLSOU1%(HSP.%?. (S A SO1.$1SA S=8LP? SIR

%op,rig/t @ &''"A Oracle) .ll rig/ts reserved)

Using D6=SLP1(P1O%(SSO1 Procedures to Print or 1etrieve Source 0eCt D6=SLP1(P1O%(SSO1 subprograms print or retrieve t/e postprocessed source teCt oB a PL/SQL unit aBter processing t/e conditional compilation directives) 0/is postprocessed teCt is t/e actual source used to compile a valid PL/SQL unit) 0/e eCample in t/e slide s/o2s /o2 to print t/e postprocessed Borm oB m,Lp5g using t/e P1I<0LPOS0LP1O%(SS(DLSOU1%( procedure) >/en m,Lp5g is compiled on an Oracle Database 1'g release or later database using t/e 91 accountA t/e resulting output is s/o2n in t/e slide above) 0/e P1I<0LPOS0LP1O%(SS(DLSOU1%( removes unselected teCt) 0/e lines oB code t/at are not included in t/e postprocessed teCt are removed) 0/e arguments Bor t/e P1I<0LPOS0LP1O%(SS(DLSOU1%( procedure are: ob3ect t,peA sc/ema name Husing student account O1.$1IA and ob3ect name) <ote: :or additional inBormation about t/e D6=SLP1(P1O%(SSO1 pac5ageA reBer to t/e Oracle Database PL/SQL Pac5ages and 0,pes 1eBerence 11g 1elease & H11)&I guide)

c ra O l, - On

, em ad .c

ra c O

le

l ae rn Uste

Oracle Database 11g: Develop PL/SQL Program Units 11 E 1G

In

Lesson .genda
Using conditional compilation ObBuscating PL/SQL code

%op,rig/t @ &''"A Oracle) .ll rig/ts reserved)

l c ra O l, - On ra c O le In l ae rn Uste e

, em ad .c

Oracle Database 11g: Develop PL/SQL Program Units 11 E 1#

>/at Is ObBuscationJ
ObBuscation Hor 2rappingI oB a PL/SQL unit is t/e process oB /iding t/e PL/SQL source code) >rapping can be done 2it/ t/e 2rap utilit, and D6=SLDDL subprograms) 0/e >rap utilit, is run Brom t/e command line and it processes an input SQL BileA suc/ as a SQLKPlus installation script) 0/e D6=SLDDL subprograms 2rap a single PL/SQL unitA suc/ as a single %1(.0( P1O%(DU1( commandA t/at /as been generated d,namicall,)

%op,rig/t @ &''"A Oracle) .ll rig/ts reserved)

<ote :or additional inBormation about obBuscationA reBer to t/e Oracle Database PL/SQL Language 1eBerence 11g 1elease & H11)&I guide)

c ra O l, - On

, em ad .c

ra c O

le In

l ae rn Uste

Oracle Database 11g: Develop PL/SQL Program Units 11 E 1"

6eneBits oB ObBuscating
It prevents ot/ers Brom seeing ,our source code) 8our source code is not visible t/roug/ t/e US(1LSOU1%(A .LLLSOU1%(A or D6.LSOU1%( data dictionar, vie2s) SQLKPlus can process t/e obBuscated source Biles) 0/e Import and (Cport utilities accept 2rapped Biles)

%op,rig/t @ &''"A Oracle) .ll rig/ts reserved)

l c ra O l, - On ra c O le In l ae rn Uste e

, em ad .c

Oracle Database 11g: Develop PL/SQL Program Units 11 E &'

>/atFs <e2 in D,namic ObBuscating Since Oracle 1'gJ


Provides t/e same Bunctionalit, as t/e %1(.0(L>1.PP(D procedure but allo2s Bor larger inputs

D6=SLDDL)>1.P Bunction

D6=SLDDL pac5age

>raps t/e teCt and creates t/e PL/SQL unit


%1(.0(L>1.PP(D procedure

%op,rig/t @ &''"A Oracle) .ll rig/ts reserved)

>/atFs <e2 in D,namic ObBuscating Since Oracle 1'gJ 0/e %1(.0(L>1.PP(D Procedure It ta5es as input a single %1(.0( O1 1(PL.%( statement t/at speciBies creation oB a PL/SQL pac5age speciBicationA pac5age bod,A BunctionA procedureA t,pe speciBicationA or t,pe bod,A generates a %1(.0( O1 1(PL.%( statement 2it/ t/e PL/SQL source teCt obBuscatedA and eCecutes t/e generated statement) 0/e >1.P :unction It ta5es as input a %1(.0( O1 1(PL.%( statement t/at speciBies t/e creation oB a PL/SQL pac5age speciBicationA pac5age bod,A BunctionA procedureA t,pe speciBicationA or t,pe bod, and returns a %1(.0( O1 1(PL.%( statementA 2/ere t/e teCt oB t/e PL/SQL unit /as been obBuscated)

c ra O l, - On

, em ad .c

ra c O

le In

l ae rn Uste

Oracle Database 11g: Develop PL/SQL Program Units 11 E &1

<onobBuscated PL/SQL %ode: (Cample


S(0 S(1V(1OU0PU0 O< 6( I< EE 0/e .LLLSOU1%( vie2 Bamil, s/o2s source code (O(%U0( I==(DI.0( S %1(.0( O1 1(PL.%( P1O%(DU1( P1 IS 6( I< D6=SLOU0PU0)PU0LLI<( HSSI am not 2rappedSSIR (<D P1R SR (<DR / %.LL p1HIR

S(L(%0 teCt :1O= userLsource >9(1( name Z SP1S O1D(1 68 lineR

%op,rig/t @ &''"A Oracle) .ll rig/ts reserved)

<onobBuscated PL/SQL %ode: (Cample In t/e Birst eCample in t/e slideA t/e (O(%U0( I==(DI.0( statement is used to create t/e procedure P1) 0/e code in t/e created procedure is not 2rapped) 0/e code is not /idden 2/en ,ou use an, oB t/e vie2s Brom t/e .LLLSOU1%( vie2 Bamil, to displa, t/e procedureFs code as s/o2n in t/e slide)

c ra O l, - On

, em ad .c

ra c O

le In

l ae rn Uste

Oracle Database 11g: Develop PL/SQL Program Units 11 E &&

ObBuscated PL/SQL %ode: (Cample


6( I< EE .LLLSOU1%( vie2 Bamil, obBuscates source code D6=SLDDL)%1(.0(L>1.PP(D H S %1(.0( O1 1(PL.%( P1O%(DU1( P1 IS 6( I< D6=SLOU0PU0)PU0LLI<( HSSI am 2rapped no2SSIR (<D P1R S IR (<DR / %.LL p1HIR

S(L(%0 teCt :1O= userLsource >9(1( name Z SP1S O1D(1 68 lineR

)))
%op,rig/t @ &''"A Oracle) .ll rig/ts reserved)

ObBuscated PL/SQL %ode: (Cample In t/e eCample in t/e slideA t/e D6=SLDDL)%1(.0(L>1.PP(D pac5age procedure is used to create t/e procedure P1)

0/e code is obBuscated 2/en ,ou use an, oB t/e vie2s Brom t/e .LLLSOU1%( vie2 Bamil, to displa, t/e procedureFs code as s/o2n on t/e neCt page) >/en ,ou c/ec5 t/e KLSOU1%( vie2sA t/e source is 2rappedA or /iddenA so t/at ot/ers cannot vie2 t/e code details as s/o2n in t/e output oB t/e command in t/e slide)

c ra O l, - On

, em ad .c

ra c O

le In

l ae rn Uste

Oracle Database 11g: Develop PL/SQL Program Units 11 E &*

D,namic ObBuscation: (Cample

S(0 S(1V(1OU0PU0 O< D(%L.1( cLcode %O<S0.<0 V.1%9.1&H*&G$GI :Z S %1(.0( O1 1(PL.%( P1O%(DU1( ne2Lproc .S vLVD.0( D.0(R 6( I< vLVD.0( :Z S8SD.0(R D6=SLOU0PU0)PU0LLI<(HvLVD.0(I R (<DR S R 6( I< D6=SLDDL)%1(.0(L>1.PP(D HcL%OD(IR (<DR /

%op,rig/t @ &''"A Oracle) .ll rig/ts reserved)

D,namic ObBuscation: (Cample 0/e eCample in t/e slide displa,s t/e creation oB a d,namicall, obBuscated procedure called <(>LP1O%) 0o veriB, t/at t/e code Bor <(>LP1O% is obBuscatedA ,ou can Puer, Brom t/e D6.T.LLTUS(1LSOU1%( dictionar, vie2s as s/o2n belo2:
S(L(%0 teCt :1O= userLsource >9(1( name Z S<(>LP1O%SR

)))

c ra O l, - On

, em ad .c

ra c O

le In

l ae rn Uste

Oracle Database 11g: Develop PL/SQL Program Units 11 E &!

0/e PL/SQL >rapper Utilit,


0/e PL/SQL 2rapper is a standEalone utilit, t/at /ides application internals b, converting PL/SQL source code into portable ob3ect code) >rapping /as t/e Bollo2ing Beatures:
M M M M M PlatBorm independence D,namic loading D,namic binding Dependenc, c/ec5ing <ormal importing and eCporting 2/en invo5ed

%op,rig/t @ &''"A Oracle) .ll rig/ts reserved)

PL/SQL >rapper 0/e PL/SQL 2rapper is a standEalone utilit, t/at converts PL/SQL source code into portable ob3ect code) Using itA ,ou can deliver PL/SQL applications 2it/out eCposing ,our source codeA 2/ic/ ma, contain proprietar, algorit/ms and data structures) 0/e 2rapper converts t/e readable source code into unreadable code) 6, /iding application internalsA it prevents misuse oB ,our application) >rapped codeA suc/ as PL/SQL stored programsA /as several Beatures: It is platBorm independentA so ,ou do not need to deliver multiple versions oB t/e same compilation unit) It permits d,namic loadingA so users need not s/ut do2n and restart to add a ne2 Beature) It permits d,namic bindingA so eCternal reBerences are resolved at load time) It oBBers strict dependenc, c/ec5ingA so t/at invalidated program units are recompiled automaticall, 2/en t/e, are invo5ed) It supports normal importing and eCportingA so t/e import/eCport utilit, can process 2rapped Biles)

c ra O l, - On

, em ad .c

ra c O

le

l ae rn Uste

Oracle Database 11g: Develop PL/SQL Program Units 11 E &+

In

1unning t/e >rapper Utilit,

>1.P I<.=(ZinputLBileLname VO<.=(ZoutputLBileLnameW

Do not use spaces around t/e ePual signs) 0/e I<.=( argument is rePuired) 0/e deBault eCtension Bor t/e input Bile is )sPlA unless it is speciBied 2it/ t/e name) 0/e O<.=( argument is optional) 0/e deBault eCtension Bor output Bile is )plbA unless speciBied 2it/ t/e O<.=( argument)

(Camples >1.P I<.=(ZdemoL'!L/ello)sPl >1.P I<.=(ZdemoL'!L/ello >1.P I<.=(ZdemoL'!L/ello)sPl O<.=(ZdemoL'!L/ello)plb

%op,rig/t @ &''"A Oracle) .ll rig/ts reserved)

1unning t/e >rapper 0/e 2rapper is an operating s,stem eCecutable called >1.P) 0o run t/e 2rapperA enter t/e Bollo2ing command at ,our operating s,stem prompt:
>1.P I<.=(ZinputLBileLname VO<.=(ZoutputLBileLnameW

ra c O

(ac/ oB t/e eCamples s/o2n in t/e slide ta5es a Bile called demoL'!L/ello)sPl as input and creates an output Bile called demoL'!L/ello)plb) .Bter t/e 2rapped Bile is createdA eCecute t/e )plb Bile Brom SQLKPlus to compile and store t/e 2rapped version oB t/e source codeA as ,ou 2ould eCecute SQL script Biles) <ote Onl, t/e I<.=( argument is rePuired) IB t/e O<.=( argument is not speciBiedA t/en t/e output Bile acPuires t/e same name as t/e input Bile 2it/ an eCtension oB )plb) 0/e input Bile can /ave an, eCtensionA but t/e deBault is )sPl) %ase sensitivit, oB t/e I<.=( and O<.=( values depends on t/e operating s,stem) enerall,A t/e output Bile is muc/ larger t/an t/e input Bile) Do not put spaces around t/e ePual signs in t/e I<.=( and O<.=( arguments and values)

c ra O l, - On

, em ad .c

le

l ae rn Uste

Oracle Database 11g: Develop PL/SQL Program Units 11 E &$

In

1esults oB >rapping
EE Original PL/SQL source code in input Bile: %1(.0( P.%?. ( ban5ing IS minLbal :Z 1''R noLBunds (O%(P0IO<R ))) (<D ban5ingR /

EE >rapped code in output Bile: %1(.0( P.%?. ( ban5ing 2rapped '1&abc!$*e ))) /

%op,rig/t @ &''"A Oracle) .ll rig/ts reserved)

1esults oB >rapping >/en it is 2rappedA an ob3ect t,peA pac5ageA or subprogram /as t/e Bollo2ing Borm: /eaderA Bollo2ed b, t/e 2ord 2rappedA Bollo2ed b, t/e encr,pted bod,)

0/e input Bile can contain an, combination oB SQL statements) 9o2everA t/e PL/SQL 2rapper 2raps onl, t/e Bollo2ing %1(.0( statements: %1(.0( VO1 1(PL.%(W 08P( %1(.0( VO1 1(PL.%(W 08P( 6OD8 %1(.0( VO1 1(PL.%(W P.%?. ( %1(.0( VO1 1(PL.%(W P.%?. ( 6OD8 %1(.0( VO1 1(PL.%(W :U<%0IO< %1(.0( VO1 1(PL.%(W P1O%(DU1( .ll ot/er SQL %1(.0( statements are passed intact to t/e output Bile)

c ra O l, - On

, em ad .c

ra c O

le In

l ae rn Uste

Oracle Database 11g: Develop PL/SQL Program Units 11 E &G

uidelines Bor >rapping


8ou must 2rap onl, t/e pac5age bod,A not t/e pac5age speciBication) 0/e 2rapper can detect s,ntactic errors but cannot detect semantic errors) 0/e output Bile s/ould not be edited) 8ou maintain t/e original source code and 2rap again as rePuired) 0o ensure t/at all t/e important parts oB ,our source code are obBuscatedA vie2 t/e 2rapped Bile in a teCt editor beBore distributing it)

%op,rig/t @ &''"A Oracle) .ll rig/ts reserved)

uidelines Bor >rapping uidelines include t/e Bollo2ing: >/en 2rapping a pac5age or ob3ect t,peA 2rap onl, t/e bod,A not t/e speciBication) 0/usA ,ou give ot/er developers t/e inBormation t/at t/e, need to use t/e pac5age 2it/out eCposing its implementation) IB ,our input Bile contains s,ntactic errorsA t/e PL/SQL 2rapper detects and reports t/em) 9o2everA t/e 2rapper cannot detect semantic errors because it does not resolve eCternal reBerences) :or eCampleA t/e 2rapper does not report an error iB t/e table or vie2 amp does not eCist:
%1(.0( P1O%(DU1( raiseLsalar, HempLid I<0( (1A amount <U=6(1I .S 6( I< UPD.0( amp EE s/ould be emp S(0 sal Z sal N amount >9(1( empno Z empLidR (<DR

c ra O l, - On

, em ad .c

ra c O

le

9o2everA t/e PL/SQL compiler resolves eCternal reBerences) 0/ereBoreA semantic errors are reported 2/en t/e 2rapper output Bile H)plb BileI is compiled) 6ecause its contents are not readableA t/e output Bile s/ould not be edited) 0o c/ange a 2rapped ob3ectA ,ou need to modiB, t/e original source code and 2rap t/e code again)

l ae rn Uste

Oracle Database 11g: Develop PL/SQL Program Units 11 E &#

In

D6=SLDDL Pac5age Versus t/e >rap Utilit,

:unctionalit, %ode obBuscation D,namic ObBuscation ObBuscate multiple programs at a time

D6=SLDDL
8es 8es <o

>rap Utilit,
8es <o 8es

%op,rig/t @ &''"A Oracle) .ll rig/ts reserved)

D6=SLDDL Versus t/e >rap Utilit, 6ot/ t/e >rap utilit, and t/e D6=SLDDL pac5age /ave distinct uses:

ra c O

0/e >rap utilit, is useBul Bor obBuscating multiple programs 2it/ one eCecution oB t/e utilit,) In essenceA a complete application ma, be 2rapped) 9o2everA t/e >rap utilit, cannot be used to obBuscate d,namicall, generated code at run time) 0/e >rap utilit, processes an input SQL Bile and obBuscates onl, t/e PL/SQL units in t/e BileA suc/ as: Pac5age speciBication and bod, :unction and procedure 0,pe speciBication and bod, 0/e >rap utilit, does not obBuscate PL/SQL content in: .non,mous bloc5s 0riggers <onEPL/SQL code 0/e D6=SLDDL pac5age is intended to obBuscate a d,namicall, generated program unit Brom 2it/in anot/er program unit) 0/e D6=SLDDL pac5age met/ods cannot obBuscate multiple program units at one eCecution) (ac/ eCecution oB t/ese met/ods accepts onl, one %1(.0( O1 1(PL.%( statement at a time as argument)

c ra O l, - On

, em ad .c

le

l ae rn Uste

Oracle Database 11g: Develop PL/SQL Program Units 11 E &"

In

Qui4
%onditional compilation enables ,ou to customi4e t/e Bunctionalit, in a PL/SQL application 2it/out removing an, source code) 1) 0rue &) :alse

%op,rig/t @ &''"A Oracle) .ll rig/ts reserved)

.ns2er: 1

l c ra O l, - On e

%onditional %ompilation %onditional compilation enables ,ou to customi4e t/e Bunctionalit, in a PL/SQL application 2it/out removing an, source code) Utili4e t/e latest Bunctionalit, 2it/ t/e latest database release or disable t/e ne2 Beatures to run t/e application against an older release oB t/e database) .ctivate debugging or tracing Bunctionalit, in t/e development environment and /ide t/at Bunctionalit, in t/e application 2/ile it runs at a production site)

, em ad .c

ra c O

le In

l ae rn Uste

Oracle Database 11g: Develop PL/SQL Program Units 11 E *'

Summar,
In t/is lessonA ,ou s/ould /ave learned /o2 to: Describe and use conditional compilation 9ide PL/SQL source code using d,namic obBuscation and t/e >rap utilit,

%op,rig/t @ &''"A Oracle) .ll rig/ts reserved)

Summar, 0/is lesson introduced t/e conditional compilation and obBuscating Hor 2rappingI oB PL/SQL code)

c ra O l, - On

, em ad .c

ra c O

le In

l ae rn Uste

Oracle Database 11g: Develop PL/SQL Program Units 11 E *1

Practice 11: Overvie2


0/is practice covers t/e Bollo2ing topics: %reating a pac5age and a procedure t/at uses conditional compilation Using t/e appropriate pac5age to retrieve t/e postprocessed source teCt oB t/e PL/SQL unit ObBuscating some PL/SQL code

%op,rig/t @ &''"A Oracle) .ll rig/ts reserved)

Practice 11: Overvie2 In t/is practiceA ,ou create a pac5age and a procedure t/at use conditional compilation) In additionA ,ou use t/e appropriate pac5age to retrieve t/e postprocessed source teCt oB t/e PL/SQL unit) 8ou also obBuscate some PL/SQL code)

c ra O l, - On

, em ad .c

ra c O

le In

l ae rn Uste

Oracle Database 11g: Develop PL/SQL Program Units 11 E *&

=anaging Dependencies

%op,rig/t @ &''"A Oracle) .ll rig/ts reserved)

l c ra O l, - On ra c O le In l ae rn Uste e

, em ad .c

Ob3ectives
.Bter completing t/is lessonA ,ou s/ould be able to do t/e Bollo2ing: 0rac5 procedural dependencies Predict t/e eBBect oB c/anging a database ob3ect on procedures and Bunctions =anage procedural dependencies

%op,rig/t @ &''"A Oracle) .ll rig/ts reserved)

Lesson .im 0/is lesson introduces ,ou to ob3ect dependencies and implicit and eCplicit recompilation oB invalid ob3ects)

c ra O l, - On

, em ad .c

ra c O

le In

l ae rn Uste

Oracle Database 11g: Develop PL/SQL Program Units 1& E &

Overvie2 oB Sc/ema Ob3ect Dependencies

Ob3ect 0,pe Pac5age bod, Pac5age speciBication SePuence Subprogram S,non,m 0able 0rigger UserEdeBined ob3ect UserEdeBined collection Vie2

%an 6e Dependent or 1eBerenced Dependent onl, 6ot/ 1eBerenced onl, 6ot/ 6ot/ 6ot/ 6ot/ 6ot/ 6ot/ 6ot/

%op,rig/t @ &''"A Oracle) .ll rig/ts reserved)

Dependent and 1eBerenced Ob3ects Some t,pes oB sc/ema ob3ects can reBerence ot/er ob3ects in t/eir deBinitions) :or eCampleA a vie2 is deBined b, a Puer, t/at reBerences tables or ot/er vie2sA and t/e bod, oB a subprogram can include SQL statements t/at reBerence ot/er ob3ects) IB t/e deBinition oB ob3ect . reBerences ob3ect 6A t/en . is a dependent ob3ect H2it/ respect to 6I and 6 is a reBerenced ob3ect H2it/ respect to .I) Dependenc, Issues IB ,ou alter t/e deBinition oB a reBerenced ob3ectA dependent ob3ects ma, or ma, not continue to 2or5 properl,) :or eCampleA iB t/e table deBinition is c/angedA t/e procedure ma, or ma, not continue to 2or5 2it/out error) 0/e Oracle server automaticall, records dependencies among ob3ects) 0o manage dependenciesA all sc/ema ob3ects /ave a status Hvalid or invalidI t/at is recorded in t/e data dictionar,A and ,ou can vie2 t/e status in t/e US(1LO6;(%0S data dictionar, vie2) IB t/e status oB a sc/ema ob3ect is V.LIDA t/en t/e ob3ect /as been compiled and can be immediatel, used 2/en reBerenced) IB t/e status oB a sc/ema ob3ect is I<V.LIDA t/en t/e sc/ema ob3ect must be compiled beBore it can be used)

c ra O l, - On

, em ad .c

ra c O

le

l ae rn Uste

Oracle Database 11g: Develop PL/SQL Program Units 1& E *

In

Dependencies

Direct dependenc,

Direct dependenc,

Dependent procedure

Vie2 or procedure: 1eBerenced/dependent

1eBerenced table

Indirect dependenc,

%op,rig/t @ &''"A Oracle) .ll rig/ts reserved)

Dependent and 1eBerenced Ob3ects HcontinuedI . procedure or Bunction can directl, or indirectl, Ht/roug/ an intermediate vie2A procedureA BunctionA or pac5aged procedure or BunctionI reBerence t/e Bollo2ing ob3ects: 0ables Vie2s SePuences Procedures :unctions Pac5aged procedures or Bunctions

c ra O l, - On

, em ad .c

ra c O

le In

l ae rn Uste

Oracle Database 11g: Develop PL/SQL Program Units 1& E !

Direct Local Dependencies

Procedure .

Procedure 6

Vie2 .

0able .

XdependsEonY table

%op,rig/t @ &''"A Oracle) .ll rig/ts reserved)

=anaging Local Dependencies In t/e case oB local dependenciesA t/e ob3ects are on t/e same node in t/e same database) 0/e Oracle server automaticall, manages all local dependenciesA using t/e databaseFs internal XdependsEonY table) >/en a reBerenced ob3ect is modiBiedA t/e dependent ob3ects are sometimes invalidated) 0/e neCt time an invalidated ob3ect is calledA t/e Oracle server automaticall, recompiles it) IB ,ou alter t/e deBinition oB a reBerenced ob3ectA dependent ob3ects mig/t or mig/t not continue to Bunction 2it/out errorA depending on t/e t,pe oB alteration) :or eCampleA iB ,ou drop a tableA no vie2 based on t/e dropped table is usable) Starting 2it/ Oracle Database 1'gA t/e %1(.0( O1 1(PL.%( S8<O<8= command /as been en/anced to minimi4e t/e invalidations to dependent PL/SQL program units and vie2s t/at reBerence it) 0/is is covered later in t/is lesson) Starting 2it/ Oracle Database 11gA dependencies are trac5ed at t/e level oB element 2it/in unit) 0/is is reBerred to as BineEgrained dependenc,) :ineEgrained dependencies are covered later in t/is lesson)

c ra O l, - On

, em ad .c

ra c O

le

l ae rn Uste

Oracle Database 11g: Develop PL/SQL Program Units 1& E +

In

Quer,ing Direct Ob3ect Dependencies: Using t/e US(1LD(P(<D(<%I(S Vie2

S(L(%0 nameA t,peA reBerencedLnameA reBerencedLt,pe :1O=userLdependencies >9(1( reBerencedLname I< HS(=PLO8((SSAS(=PLV>S IR

)))
%op,rig/t @ &''"A Oracle) .ll rig/ts reserved)

Quer,ing Direct Ob3ect Dependencies: Using t/e US(1LD(P(<D(<%I(S Vie2

8ou can determine 2/ic/ database ob3ects to recompile manuall, b, displa,ing direct dependencies Brom t/e US(1LD(P(<D(<%I(S data dictionar, vie2)

0/e .LLLD(P(<D(<%I(S and D6.LD(P(<D(<%I(S vie2s contain t/e additional O><(1 columnA 2/ic/ reBerences t/e o2ner oB t/e ob3ect) 0/e US(1LD(P(<D(<%I(S Data Dictionar, Vie2 %olumns 0/e columns oB t/e US(1LD(P(<D(<%I(S data dictionar, vie2 are as Bollo2s: <.=(: 0/e name oB t/e dependent ob3ect 08P(: 0/e t,pe oB t/e dependent ob3ect HP1O%(DU1(A :U<%0IO<A P.%?. (A P.%?. ( 6OD8A 01I (1A or VI(>I 1(:(1(<%(DLO><(1: 0/e sc/ema oB t/e reBerenced ob3ect 1(:(1(<%(DL<.=(: 0/e name oB t/e reBerenced ob3ect 1(:(1(<%(DL08P(: 0/e t,pe oB t/e reBerenced ob3ect 1(:(1(<%(DLLI<?L<.=(: 0/e database lin5 used to access t/e reBerenced ob3ect

c ra O l, - On

, em ad .c

ra c O

le

l ae rn Uste

Oracle Database 11g: Develop PL/SQL Program Units 1& E $

In

Quer,ing an Ob3ectFs Status


(ver, database ob3ect /as one oB t/e Bollo2ing status values:

Status
V.LID

Description
0/e ob3ect 2as successBull, compiledA using t/e current deBinition in t/e data dictionar,) 0/e most recent attempt to compile t/e ob3ect produced errors) 0/e ob3ect is mar5ed invalid because an ob3ect t/at it reBerences /as c/anged) HOnl, a dependent ob3ect can be invalid)I .n access privilege on a reBerenced ob3ect 2as revo5ed) HOnl, a dependent ob3ect can be unaut/ori4ed)I

%O=PIL(D >I09 (11O1S I<V.LID

U<.U09O1I7(D

%op,rig/t @ &''"A Oracle) .ll rig/ts reserved)

Quer,ing an Ob3ectFs Status (ver, database ob3ect /as one oB t/e status values s/o2n in t/e table in t/e slide) <ote: 0/e US(1LO6;(%0SA .LLLO6;(%0SA and D6.LO6;(%0S static data dictionar, vie2s do not distinguis/ bet2een %ompiled 2it/ errorsA InvalidA and Unaut/ori4edR insteadA t/e, describe all t/ese as I<V.LID)

c ra O l, - On

, em ad .c

ra c O

le In

l ae rn Uste

Oracle Database 11g: Develop PL/SQL Program Units 1& E G

Invalidation oB Dependent Ob3ects

Procedure .

Vie2 6

0able %

Procedure . is a direct dependent oB Vie2 6) Vie2 6 is a direct dependent oB 0able %) Procedure . is an indirect dependent oB 0able %) Direct dependents are invalidated onl, b, c/anges to t/e reBerenced ob3ect t/at aBBect t/em) Indirect dependents can be invalidated b, c/anges to t/e reBerence ob3ect t/at do not aBBect t/em)

%op,rig/t @ &''"A Oracle) .ll rig/ts reserved)

Invalidation oB Dependent Ob3ects IB ob3ect . depends on ob3ect 6A 2/ic/ depends on ob3ect %A t/en . is a direct dependent oB 6A 6 is a direct dependent oB %A and . is an indirect dependent oB %)

In Oracle Database 11gA direct dependents are invalidated onl, b, c/anges to t/e reBerenced ob3ect t/at aBBect t/em Hc/anges to t/e signature oB t/e reBerenced ob3ectI) Indirect dependents can be invalidated b, c/anges to t/e reBerence ob3ect t/at do not aBBect t/em: IB a c/ange to 0able % invalidates Vie2 6A it invalidates Procedure . Hand all ot/er direct and indirect dependents oB Vie2 6I) 0/is is called cascading invalidation) .ssume t/at t/e structure oB t/e table on 2/ic/ a vie2 is based is modiBied) >/en ,ou describe t/e vie2 b, using t/e SQLKPlus D(S%1I6( commandA ,ou get an error message t/at states t/at t/e ob3ect is invalid to describe) 0/is is because t/e command is not a SQL commandR at t/is stageA t/e vie2 is invalid because t/e structure oB its base table is c/anged) IB ,ou Puer, t/e vie2 no2A t/en t/e vie2 is recompiled automaticall, and ,ou can see t/e result iB it is successBull, recompiled)

c ra O l, - On

, em ad .c

ra c O

le

l ae rn Uste

Oracle Database 11g: Develop PL/SQL Program Units 1& E #

In

Sc/ema Ob3ect %/ange 0/at Invalidates Some Dependents: (Cample


%1(.0( VI(> commissioned .S S(L(%0 BirstLnameA lastLnameA commissionLpct :1O= emplo,ees >9(1( commissionLpct \ ')''R

%1(.0( VI(> siCLBigureLsalar, .S S(L(%0 K :1O= emplo,ees >9(1( salar, \Z 1'''''R

S(L(%0 ob3ectLnameA status :1O= userLob3ects >9(1( ob3ectLt,pe Z SVI(>SR

%op,rig/t @ &''"A Oracle) .ll rig/ts reserved)

Sc/ema Ob3ect %/ange 0/at Invalidates Some Dependents: (Cample 0/e eCample in t/e slide demonstrates an eCample oB a sc/ema ob3ect c/ange t/at invalidates some dependents but not ot/ers) 0/e t2o ne2l, created vie2s are based on t/e (=PLO8((S table in t/e 91 sc/ema) 0/e status oB t/e ne2l, created vie2s is V.LID)

c ra O l, - On

, em ad .c

ra c O

le In

l ae rn Uste

Oracle Database 11g: Develop PL/SQL Program Units 1& E "

Sc/ema Ob3ect %/ange 0/at Invalidates Some Dependents: (Cample

.L0(1 0.6L( emplo,ees =ODI:8 email V.1%9.1&H+'IR S(L(%0 ob3ectLnameA status :1O= userLob3ects >9(1( ob3ectLt,pe Z SVI(>SR

%op,rig/t @ &''"A Oracle) .ll rig/ts reserved)

Sc/ema Ob3ect %/ange 0/at Invalidates Some Dependents: (Cample HcontinuedI Suppose ,ou determine t/at t/e (=.IL column in t/e (=PLO8((S table needs to be lengt/ened Brom &+ to +'A ,ou alter t/e table as s/o2n in t/e slide above) 6ecause t/e %O==ISSIO<(D vie2 does not include t/e (=.IL column in its select listA it is not invalidated) 9o2everA t/e SIO:I U1(S vie2 is invalidated because all columns in t/e table are selected)

c ra O l, - On

, em ad .c

ra c O

le In

l ae rn Uste

Oracle Database 11g: Develop PL/SQL Program Units 1& E 1'

Displa,ing Direct and Indirect Dependencies


1) 1un t/e utldtree)sPl script t/at creates t/e ob3ects t/at enable ,ou to displa, t/e direct and indirect dependencies)
]//ome/oracle/labs/plpu/labs/utldtree)sPl

&) (Cecute t/e D(P01((L:ILL procedure)


(O(%U0( deptreeLBillHS0.6L(SA SO1.$1SA S(=PLO8((SSI

%op,rig/t @ &''"A Oracle) .ll rig/ts reserved)

Displa,ing Direct and Indirect Dependencies b, Using Vie2s Provided b, Oracle Displa, direct and indirect dependencies Brom additional user vie2s called D(P01(( and ID(P01((R t/ese vie2s are provided b, Oracle) (Cample 1) =a5e sure t/at t/e utldtree)sPl script /as been eCecuted) 0/is script is located in t/e [O1.%L(L9O=(/labs/plpu/labs Bolder) 8ou can run t/e script as Bollo2s:

<ote: In t/is classA t/is script is supplied in t/e labs Bolder oB ,our class Biles) 0/e code eCample above uses t/e student account O1.$1) &) Populate t/e D(P01((L0(=P0.6 table 2it/ inBormation Bor a particular reBerenced ob3ect b, invo5ing t/e D(P01((L:ILL procedure) 0/ere are t/ree parameters Bor t/is procedure:

]J/labs/plpu/labs/utldtree)sPl

c ra O l, - On

, em ad .c

ra c O

ob3ectLt,pe

le

0,pe oB t/e reBerenced ob3ect Sc/ema oB t/e reBerenced ob3ect <ame oB t/e reBerenced ob3ect

ob3ectLo2ner ob3ectLname

l ae rn Uste

Oracle Database 11g: Develop PL/SQL Program Units 1& E 11

In

Displa,ing Dependencies Using t/e D(P01(( Vie2

S(L(%0nestedLlevelA t,peA name :1O=deptree O1D(1 68 sePdR

)))

%op,rig/t @ &''"A Oracle) .ll rig/ts reserved)

Displa,ing Dependencies Using t/e D(P01(( Vie2 8ou can displa, a tabular representation oB all dependent ob3ects b, Puer,ing t/e D(P01(( vie2) 8ou can displa, an indented representation oB t/e same inBormation b, Puer,ing t/e ID(P01(( vie2A 2/ic/ consists oB a single column named D(P(<D(<%I(S as Bollo2s:
S(L(%0 K :1O=ideptreeR

c ra O l, - On

, em ad .c

ra c O

le In

)))

l ae rn Uste

Oracle Database 11g: Develop PL/SQL Program Units 1& E 1&

=ore Precise Dependenc, =etadata in Oracle Database 11g


6eBore 11gA adding column D to table 0 invalidated t/e dependent ob3ects) Oracle Database 11g records additionalA BinerEgrained dependenc, management:
M .dding column D to table 0 does not impact vie2 V and does not invalidate t/e dependent ob3ects
.dd column D

0able 0 %olumns: .A6

Vie2 V %olumns: .A6

Procedure P

%op,rig/t @ &''"A Oracle) .ll rig/ts reserved)

:ineE rained Dependencies Starting 2it/ Oracle Database 11gA ,ou /ave access to records t/at describe more precise dependenc, metadata) 0/is is called BineEgrained dependenc, and it enables ,ou to see 2/en t/e dependent ob3ects are not invalidated 2it/out logical rePuirement) (arlier Oracle Database releases record dependenc, metadataUBor eCampleA PL/SQL unit P depends on PL/SQL unit :A or t/at vie2 V depends on table 0U2it/ t/e precision oB t/e 2/ole ob3ect) 0/is means t/at dependent ob3ects are sometimes invalidated 2it/out logical rePuirement) :or eCampleA iB vie2 V depends onl, on columns . and 6 in table 0A and column D is added to table 0A t/e validit, oB vie2 V is not logicall, aBBected) <evert/elessA beBore Oracle Database 1elease 11)1A vie2 V is invalidated b, t/e addition oB column D to table 0) >it/ Oracle Database 1elease 11)1A adding column D to table 0 does not invalidate vie2 V) Similarl,A iB procedure P depends onl, on elements (1 and (& 2it/in a pac5ageA adding element ("" to t/e pac5age does not invalidate procedure P)

c ra O l, - On

, em ad .c
:unction :

ra c O

1educing t/e invalidation oB dependent ob3ects in response to c/anges to t/e ob3ects on 2/ic/ t/e, depend increases application availabilit,A bot/ in t/e development environment and during online application upgrade) :or more inBormation about t/is topicA reBer to t/e 11g: InBrastructure rid M 9ig/ .vailabilit, P1 eStud,)

le

l ae rn Uste

Oracle Database 11g: Develop PL/SQL Program Units 1& E 1*

In

:ineE rained Dependenc, =anagement


In Oracle Database 11gA dependencies are no2 trac5ed at t/e level oB element 2it/in unit) (lementEbased dependenc, trac5ing covers t/e Bollo2ing:
M Dependenc, oB a singleEtable vie2 on its base table M Dependenc, oB a PL/SQL program unit Hpac5age speciBicationA pac5age bod,A or subprogramI on t/e Bollo2ing:
U

Ot/er PL/SQL program units 0ables Vie2s

%op,rig/t @ &''"A Oracle) .ll rig/ts reserved)

l c ra O l, - On ra c O le In l ae rn Uste e

, em ad .c

Oracle Database 11g: Develop PL/SQL Program Units 1& E 1!

:ineE rained Dependenc, =anagement: (Cample 1


%1(.0( 0.6L( t& HcolLa <U=6(1A colLb <U=6(1A colLc <U=6(1IR %1(.0( VI(> v .S S(L(%0 colLaA colLb :1O= t&R S(L(%0 ud)nameA ud)t,peA ud)reBerencedLnameA ud)reBerencedLt,peA uo)status :1O= userLdependencies udA userLob3ects uo >9(1( ud)name Z uo)ob3ectLname .<D ud)name Z SVSR

.L0(1 0.6L( t& .DD HcolLd V.1%9.1&H&'IIR S(L(%0 ud)nameA ud)t,peA ud)reBerencedLnameA ud)reBerencedLt,peA uo)status :1O= userLdependencies udA userLob3ects uo >9(1( ud)name Z uo)ob3ectLname .<D ud)name Z SVSR

%op,rig/t @ &''"A Oracle) .ll rig/ts reserved)

:ineE rained Dependenc, =anagement: (Cample 1 (Cample oB Dependenc, oB a SingleE0able Vie2 on Its 6ase 0able In t/e Birst eCample in t/e slideA table 0& is created 2it/ t/ree columns: %OLL.A %OLL6A and %OLL%) . vie2 named V is created based on columns %OLL. and %OLL6 oB table 0&) 0/e dictionar, vie2s are Pueried and t/e vie2 V is dependent on table 0 and its status is valid) In t/e t/ird eCampleA table 0& is altered) . ne2 column named %OLLD is added) 0/e dictionar, vie2s still report t/at t/e vie2 V is dependent because elementEbased dependenc, trac5ing reali4es t/at t/e columns %OLL. and %OLL6 are not modiBied andA t/ereBoreA t/e vie2 does not need to be invalidated)

c ra O l, - On

, em ad .c

ra c O

le In

l ae rn Uste

Oracle Database 11g: Develop PL/SQL Program Units 1& E 1+

:ineE rained Dependenc, =anagement: (Cample 1

.L0(1 0.6L( t& =ODI:8 HcolLa V.1%9.1&H&'IIR S(L(%0 ud)nameA ud)reBerencedLnameA ud)reBerencedLt,peA uo)status :1O= userLdependencies udA userLob3ects uo >9(1( ud)name Z uo)ob3ectLname .<D ud)name Z SVSR

%op,rig/t @ &''"A Oracle) .ll rig/ts reserved)

:ineE rained Dependenc, =anagement: (Cample 1 HcontinuedI In t/e eCample in t/e slideA t/e vie2 is invalidated because its element H%OLL.I is modiBied in t/e table on 2/ic/ t/e vie2 is dependent)

c ra O l, - On

, em ad .c

ra c O

le In

l ae rn Uste

Oracle Database 11g: Develop PL/SQL Program Units 1& E 1$

:ineE rained Dependenc, =anagement: (Cample &


%1(.0( P.%?. ( p5g IS P1O%(DU1( procL1R (<D p5gR / %1(.0( O1 1(PL.%( P1O%(DU1( p IS 6( I< p5g)procL1HIR (<D pR / %1(.0( O1 1(PL.%( P.%?. ( p5g IS P1O%(DU1( procL1R P1O%(DU1( un/eardLoBR (<D p5gR /

%op,rig/t @ &''"A Oracle) .ll rig/ts reserved)

:ineE rained Dependenc, =anagement: (Cample & In t/e eCample in t/e slideA ,ou create a pac5age named P? t/at /as procedure P1O%L1 declared) . procedure named P invo5es P? )P1O%L1) 0/e deBinition oB t/e P? pac5age is modiBied and anot/er subroutine is added to t/e pac5age declaration) >/en ,ou Puer, t/e US(1LO6;(%0S dictionar, vie2 Bor t/e status oB t/e P procedureA it is still valid as s/o2n because t/e element ,ou added to t/e deBinition oB P? is not reBerenced t/roug/ procedure P)

S(L(%0 status :1O= userLob3ects >9(1( ob3ectLname Z SPSR

c ra O l, - On

, em ad .c

ra c O

le

l ae rn Uste

Oracle Database 11g: Develop PL/SQL Program Units 1& E 1G

In

%/anges to S,non,m Dependencies

V.LID status %1(.0( O1 1(PL.%( S8<O<8=

%op,rig/t @ &''"A Oracle) .ll rig/ts reserved)

%/anges to S,non,m Dependencies 0/e Oracle Database minimi4es do2n time during code upgrades or sc/ema merges) >/en certain conditions on columnsA privilegesA partitionsA and so on are metA a table or ob3ect t,pe is considered ePuivalent and dependent ob3ects are no longer invalidated) In Oracle Database 1'gA t/e %1(.0( O1 1(PL.%( S8<O<8= command /as been en/anced to minimi4e t/e invalidations to dependent PL/SQL program units and vie2s t/at reBerence it) 0/is eliminates t/e need Bor timeEconsuming recompilation oB t/e program units aBter redeBinition oB t/e s,non,ms or during eCecution) 8ou do not /ave to set an, parameters or issue an, special commands to enable t/is Bunctionalit,R invalidations are minimi4ed automaticall,) <ote: 0/is en/ancement applies onl, to s,non,ms pointing to tables)

c ra O l, - On

, em ad .c

V.LID status

ra c O

le In

l ae rn Uste

Oracle Database 11g: Develop PL/SQL Program Units 1& E 1#

=aintaining Valid PL/SQL Program Units and Vie2s

(=PLO8((S

%1(.0( O1 1(PL.%( S8<O<8= empL/ist

V.LID status

(=PLO8((SL9IS0

%op,rig/t @ &''"A Oracle) .ll rig/ts reserved)

=aintaining Valid PL/SQL Program Units Starting 2it/ Oracle Database 1'g 1elease &A ,ou can c/ange t/e deBinition oB a s,non,mA and t/e dependent PL/SQL program units are not invalidated under t/e Bollo2ing conditions: 0/e column orderA column namesA and column data t,pes oB t/e tables are identical) 0/e privileges on t/e ne2l, reBerenced table and its columns are a superset oB t/e set oB privileges on t/e original table) 0/ese privileges must not be derived t/roug/ roles alone) 0/e names and t,pes oB partitions and subpartitions are identical) 0/e tables are oB t/e same organi4ation t,pe) Ob3ect t,pe columns are oB t/e same t,pe) =aintaining Valid Vie2s

ra c O

.s 2it/ dependent PL/SQL program unitsA ,ou can c/ange t/e deBinition oB a s,non,mA and t/e dependent vie2s are not invalidated under t/e conditions listed in t/e preceding paragrap/) In additionA t/e Bollo2ing must be true to preserve t/e V.LID status oB dependent vie2sA but not oB dependent PL/SQL program unitsA 2/en ,ou redeBine a s,non,m: %olumns and order oB columns deBined Bor primar, 5e, and uniPue indeCesA <O0 <ULL constraintsA and primar, 5e, and uniPue constraints must be identical) 0/e dependent vie2 cannot /ave an, reBerential constraints)

c ra O l, - On

, em ad .c

le

l ae rn Uste

Oracle Database 11g: Develop PL/SQL Program Units 1& E 1"

In

.not/er Scenario oB Local Dependencies

1(DU%(LS.L procedure

1.IS(LS.L procedure (=PLO8((S table

%op,rig/t @ &''"A Oracle) .ll rig/ts reserved)

.not/er Scenario oB Local Dependencies 0/e eCample in t/e slide illustrates t/e eBBect t/at a c/ange in t/e deBinition oB a procedure /as on t/e recompilation oB a dependent procedure) .ssume t/at t/e 1.IS(LS.L procedure updates t/e (=PLO8((S table directl,A and t/at t/e 1(DU%(LS.L procedure updates t/e (=PLO8((S table indirectl, b, 2a, oB 1.IS(LS.L) IB t/e internal logic oB t/e 1.IS(LS.L procedure is modiBiedA 1(DU%(LS.L 2ill successBull, recompile iB 1.IS(LS.L /as successBull, compiled) IB t/e Bormal parameters Bor t/e 1.IS(LS.L procedure are eliminatedA 1(DU%(LS.L 2ill not successBull, recompile)

c ra O l, - On

, em ad .c

ra c O

le In

l ae rn Uste

Oracle Database 11g: Develop PL/SQL Program Units 1& E &'

uidelines Bor 1educing Invalidation


0o reduce invalidation oB dependent ob3ects:

.dd ne2 items to t/e end oB t/e pac5age

1eBerence eac/ table t/roug/ a vie2

%op,rig/t @ &''"A Oracle) .ll rig/ts reserved)

uidelines Bor 1educing Invalidation .dd <e2 Items to (nd oB Pac5age >/en adding ne2 items to a pac5ageA add t/em to t/e end oB t/e pac5age) 0/is preserves t/e slot numbers and entr,Epoint numbers oB eCisting topElevel pac5age itemsA preventing t/eir invalidation) :or eCampleA consider t/e Bollo2ing pac5age: %1(.0( O1 1(PL.%( P.%?. ( p5g1 IS :U<%0IO< getLvar 1(0U1< V.1%9.1&R P1O%(DU1( setLvar Hv V.1%9.1&IR (<DR .dding an item to t/e end oB p5g1 does not invalidate dependents t/at reBerence getLvar) Inserting an item bet2een t/e getLvar Bunction and t/e setLvar procedure invalidates dependents t/at reBerence t/e setLvar Bunction)

c ra O l, - On

, em ad .c

ra c O

1eBerence (ac/ 0able 0/roug/ a Vie2 1eBerence tables indirectl,A using vie2s) 0/is allo2s ,ou to do t/e Bollo2ing: .dd columns to t/e table 2it/out invalidating dependent vie2s or dependent PL/SQL ob3ects =odiB, or delete columns not reBerenced b, t/e vie2 2it/out invalidating dependent ob3ects

le

l ae rn Uste

Oracle Database 11g: Develop PL/SQL Program Units 1& E &1

In

Ob3ect 1evalidation
.n ob3ect t/at is not valid 2/en it is reBerenced must be validated beBore it can be used) Validation occurs automaticall, 2/en an ob3ect is reBerencedR it does not rePuire eCplicit user action) IB an ob3ect is not validA its status is eit/er %O=PIL(D >I09 (11O1SA U<.U09O1I7(DA or I<V.LID)

%op,rig/t @ &''"A Oracle) .ll rig/ts reserved)

Ob3ect 1evalidation 0/e compiler cannot automaticall, revalidate an ob3ect t/at compiled 2it/ errors) 0/e compiler recompiles t/e ob3ectA and iB it recompiles 2it/out errorsA it is revalidatedR ot/er2iseA it remains invalid) 0/e compiler c/ec5s 2/et/er t/e unaut/ori4ed ob3ect /as access privileges to all oB its reBerenced ob3ects) IB soA t/e compiler revalidates t/e unaut/ori4ed ob3ect 2it/out recompiling it) IB notA t/e compiler issues appropriate error messages) 0/e SQL compiler recompiles t/e invalid ob3ect) IB t/e ob3ect recompiles 2it/out errorsA it is revalidatedR ot/er2iseA it remains invalid) :or an invalid PL/SQL program unit HprocedureA BunctionA or pac5ageIA t/e PL/SQL compiler c/ec5s 2/et/er an, reBerenced ob3ect c/anged in a 2a, t/at aBBects t/e invalid ob3ect) IB soA t/e compiler recompiles t/e invalid ob3ect) IB t/e ob3ect recompiles 2it/out errorsA it is revalidatedR ot/er2iseA it remains invalid) IB notA t/e compiler revalidates t/e invalid ob3ect 2it/out recompiling it) IB notA t/e compiler revalidates t/e invalid ob3ect 2it/out recompiling it) :ast revalidation is usuall, perBormed on ob3ects t/at 2ere invalidated due to cascading invalidation)

c ra O l, - On

, em ad .c

ra c O

le

l ae rn Uste

Oracle Database 11g: Develop PL/SQL Program Units 1& E &&

In

1emote Dependencies

1emote dependenc, Procedure

Procedure

Vie2 Local and remote reBerences

0able

1emote dependenc, Procedure V.LID Procedure I<V.LID Vie2 I<V.LID

%op,rig/t @ &''"A Oracle) .ll rig/ts reserved)

1emote Dependencies In t/e case oB remote dependenciesA t/e ob3ects are on separate nodes) 0/e Oracle server does not manage dependencies among remote sc/ema ob3ects ot/er t/an localEprocedureEtoEremoteE procedure dependencies Hincluding BunctionsA pac5agesA and triggersI) 0/e local stored procedure and all its dependent ob3ects are invalidated but do not automaticall, recompile 2/en called Bor t/e Birst time) 1ecompilation oB Dependent Ob3ects: Local and 1emote

ra c O

VeriB, successBul eCplicit recompilation oB t/e dependent remote procedures and implicit recompilation oB t/e dependent local procedures b, c/ec5ing t/e status oB t/ese procedures 2it/in t/e US(1LO6;(%0S vie2) IB an automatic implicit recompilation oB t/e dependent local procedures BailsA t/e status remains invalid and t/e Oracle server issues a runEtime error) 0/ereBoreA to avoid disrupting productionA it is strongl, recommended t/at ,ou recompile local dependent ob3ects manuall,A rat/er t/an rel,ing on an automatic mec/anism)

c ra O l, - On

, em ad .c

0able

le

l ae rn Uste

Oracle Database 11g: Develop PL/SQL Program Units 1& E &*

In

%oncepts oB 1emote Dependencies


1emote dependencies are governed b, t/e mode t/at is c/osen b, t/e user:

0I=(S0.=P c/ec5ing

SI <.0U1( c/ec5ing

%op,rig/t @ &''"A Oracle) .ll rig/ts reserved)

%oncepts oB 1emote Dependencies 0I=(S0.=P %/ec5ing

l c ra O l, - On e

ra c O

(ac/ PL/SQL program unit carries a time stamp t/at is set 2/en it is created or recompiled) >/enever ,ou alter a PL/SQL program unit or a relevant sc/ema ob3ectA all its dependent program units are mar5ed as invalid and must be recompiled beBore t/e, can eCecute) 0/e actual time stamp comparison occurs 2/en a statement in t/e bod, oB a local procedure calls a remote procedure) SI <.0U1( %/ec5ing :or eac/ PL/SQL program unitA bot/ t/e time stamp and t/e signature are recorded) 0/e signature oB a PL/SQL construct contains inBormation about t/e Bollo2ing: 0/e name oB t/e construct HprocedureA BunctionA or pac5ageI 0/e base t,pes oB t/e parameters oB t/e construct 0/e modes oB t/e parameters HI<A OU0A or I< OU0I 0/e number oB t/e parameters 0/e recorded time stamp in t/e calling program unit is compared 2it/ t/e current time stamp in t/e called remote program unit) IB t/e time stamps matc/A t/e call proceeds) IB t/e, do not matc/A t/e remote procedure call H1P%I la,er perBorms a simple comparison oB t/e signature to determine 2/et/er t/e call is saBe or not) IB t/e signature /as not been c/anged in an incompatible mannerA eCecution continuesR ot/er2iseA an error is returned)

, em ad .c

le

l ae rn Uste

Oracle Database 11g: Develop PL/SQL Program Units 1& E &!

In

Setting t/e 1(=O0(LD(P(<D(<%I(SL=OD( Parameter


.s an init)ora parameter: 1(=O0(LD(P(<D(<%I(SL=OD( Z 0I=(S0.=P T SI <.0U1( .t t/e s,stem level: .L0(1 S8S0(= S(0 1(=O0(LD(P(<D(<%I(SL=OD( Z 0I=(S0.=P T SI <.0U1( .t t/e session level: .L0(1 S(SSIO< S(0 1(=O0(LD(P(<D(<%I(SL=OD( Z 0I=(S0.=P T SI <.0U1(

%op,rig/t @ &''"A Oracle) .ll rig/ts reserved)

1(=O0(LD(P(<D(<%I(SL=OD( Parameter Setting t/e 1(=O0(LD(P(<D(<%I(SL=OD( value0I=(S0.=P SI <.0U1( SpeciB, t/e value oB t/e 1(=O0(LD(P(<D(<%I(SL=OD( parameter using one oB t/e t/ree met/ods described in t/e slide) <ote: 0/e calling site determines t/e dependenc, model)

c ra O l, - On

, em ad .c

ra c O

le In

l ae rn Uste

Oracle Database 11g: Develop PL/SQL Program Units 1& E &+

1emote Procedure 6 %ompiles at #:'' .=

1emote procedure 6: %ompiles and is V.LID at #:'' .=

%op,rig/t @ &''"A Oracle) .ll rig/ts reserved)

Local Procedures 1eBerencing 1emote Procedures . local procedure t/at reBerences a remote procedure is invalidated b, t/e Oracle server iB t/e remote procedure is recompiled aBter t/e local procedure is compiled)

.utomatic 1emote Dependenc, =ec/anism >/en a procedure compilesA t/e Oracle server records t/e time stamp oB t/at compilation 2it/in t/e P code oB t/e procedure) In t/e slideA 2/en t/e remote procedure 6 is successBull, compiled at #:'' .=A t/is time is recorded as its time stamp)

c ra O l, - On

, em ad .c

ra c O

le In

l ae rn Uste

Oracle Database 11g: Develop PL/SQL Program Units 1& E &$

Local Procedure . %ompiles at ":'' .=

0I=(S0.=P oB .

1ecord 0I=(S0.=P oB 6

0I=(S0.=P oB 6

Local procedure .: V.LID

%op,rig/t @ &''"A Oracle) .ll rig/ts reserved)

Local Procedures 1eBerencing 1emote Procedures HcontinuedI .utomatic 1emote Dependenc, =ec/anism HcontinuedI >/en a local procedure reBerencing a remote procedure compilesA t/e Oracle server also records t/e time stamp oB t/e remote procedure in t/e P code oB t/e local procedure) In t/e slideA local procedure . H2/ic/ is dependent on remote procedure 6I is compiled at ":'' .=) 0/e time stamps oB bot/ procedure . and remote procedure 6 are recorded in t/e P code oB procedure .)

c ra O l, - On

, em ad .c
1emote procedure 6: V.LID

ra c O

le In

l ae rn Uste

Oracle Database 11g: Develop PL/SQL Program Units 1& E &G

(Cecute Procedure .

0I=(S0.=P comparison

0I=(S0.=P oB .

0I=(S0.=P oB 6

0I=(S0.=P oB 6

Local procedure .: V.LID

%op,rig/t @ &''"A Oracle) .ll rig/ts reserved)

.utomatic 1emote Dependenc, >/en t/e local procedure is invo5ed at run timeA t/e Oracle server compares t/e t2o time stamps oB t/e reBerenced remote procedure)

IB t/e time stamps are ePual Hindicating t/at t/e remote procedure /as not recompiledIA t/en t/e Oracle server eCecutes t/e local procedure) In t/e eCample in t/e slideA t/e time stamp recorded 2it/ t/e P code oB remote procedure 6 is t/e same as t/at recorded 2it/ local procedure .) 0/ereBoreA local procedure . is valid)

c ra O l, - On

, em ad .c
1emote procedure 6: V.LID

ra c O

le In

l ae rn Uste

Oracle Database 11g: Develop PL/SQL Program Units 1& E &#

1emote Procedure 6 1ecompiled at 11:'' .=

1emote procedure 6: 1ecompiles and is V.LID at 11:'' .=

%op,rig/t @ &''"A Oracle) .ll rig/ts reserved)

Local Procedures 1eBerencing 1emote Procedures .ssume t/at remote procedure 6 is successBull, recompiled at 11:'' .=) 0/e ne2 time stamp is recorded along 2it/ its P code)

c ra O l, - On

, em ad .c

ra c O

le In

l ae rn Uste

Oracle Database 11g: Develop PL/SQL Program Units 1& E &"

(Cecute Procedure .
Saved 0I=(S0.=P oB 6 `Z %O=PIL( 0I=( oB 6

0I=(S0.=P comparison

0I=(S0.=P oB .

0I=(S0.=P oB 6

0I=(S0.=P oB 6

Local procedure .: I<V.LID

%op,rig/t @ &''"A Oracle) .ll rig/ts reserved)

.utomatic 1emote Dependenc, IB t/e time stamps are not ePual Hindicating t/at t/e remote procedure /as recompiledIA t/en t/e Oracle server invalidates t/e local procedure and returns a runEtime error) IB t/e local procedure H2/ic/ is no2 tagged as invalidI is invo5ed a second timeA t/en t/e Oracle server recompiles it beBore eCecutingA in accordance 2it/ t/e automatic local dependenc, mec/anism) <ote: IB a local procedure returns a runEtime error t/e Birst time it is invo5ed Hindicating t/at t/e remote procedureFs time stamp /as c/angedIA t/en ,ou s/ould develop a strateg, to reinvo5e t/e local procedure) In t/e eCample in t/e slideA t/e remote procedure is recompiled at 11:'' .= and t/is time is recorded as its time stamp in t/e P code) 0/e P code oB local procedure . still /as #:'' .= as t/e time stamp Bor remote procedure 6) 6ecause t/e time stamp recorded 2it/ t/e P code oB local procedure . is diBBerent Brom t/at recorded 2it/ t/e remote procedure 6A t/e local procedure is mar5ed invalid) >/en t/e local procedure is invo5ed Bor t/e second timeA it can be successBull, compiled and mar5ed valid)

c ra O l, - On

, em ad .c
1emote procedure 6: V.LID

ra c O

le

. disadvantage oB time stamp mode is t/at it is unnecessaril, restrictive) 1ecompilation oB dependent ob3ects across t/e net2or5 is oBten perBormed 2/en not strictl, necessar,A leading to perBormance degradation)

l ae rn Uste

Oracle Database 11g: Develop PL/SQL Program Units 1& E *'

In

Signature =ode
0/e signature oB a procedure is:
M 0/e name oB t/e procedure M 0/e data t,pes oB t/e parameters M 0/e modes oB t/e parameters

0/e signature oB t/e remote procedure is saved in t/e local procedure) >/en eCecuting a dependent procedureA t/e signature oB t/e reBerenced remote procedure is compared)

%op,rig/t @ &''"A Oracle) .ll rig/ts reserved)

Signatures 0o alleviate some oB t/e problems 2it/ t/e time stampMonl, dependenc, modelA ,ou can use t/e signature model) 0/is allo2s t/e remote procedure to be recompiled 2it/out aBBecting t/e local procedures) 0/is is important iB t/e database is distributed) 0/e signature oB a subprogram contains t/e Bollo2ing inBormation: 0/e name oB t/e subprogram 0/e data t,pes oB t/e parameters 0/e modes oB t/e parameters 0/e number oB parameters 0/e data t,pe oB t/e return value Bor a Bunction

IB a remote program is c/anged and recompiled but t/e signature does not c/angeA t/en t/e local procedure can eCecute t/e remote procedure) >it/ t/e time stamp met/odA an error 2ould /ave been raised because t/e time stamps 2ould not /ave matc/ed)

c ra O l, - On

, em ad .c

ra c O

le

l ae rn Uste

Oracle Database 11g: Develop PL/SQL Program Units 1& E *1

In

1ecompiling a PL/SQL Program Unit


1ecompilation: Is /andled automaticall, t/roug/ implicit runEtime recompilation Is /andled t/roug/ eCplicit recompilation 2it/ t/e .L0(1 statement

.L0(1 P1O%(DU1( VS%9(=.)WprocedureLname %O=PIL(R .L0(1 :U<%0IO< VS%9(=.)WBunctionLname %O=PIL(R

.L0(1 P.%?. ( VS%9(=.)Wpac5ageLname %O=PIL( VP.%?. ( T SP(%I:I%.0IO< T 6OD8WR .L0(1 01I (1 triggerLname V%O=PIL(VD(6U WWR

%op,rig/t @ &''"A Oracle) .ll rig/ts reserved)

1ecompiling PL/SQL Ob3ects IB t/e recompilation is successBulA t/e ob3ect becomes valid) IB notA t/e Oracle server returns an error and t/e ob3ect remains invalid) >/en ,ou recompile a PL/SQL ob3ectA t/e Oracle server Birst recompiles an, invalid ob3ect on 2/ic/ it depends) Procedure: .n, local ob3ects t/at depend on a procedure Hsuc/ as procedures t/at call t/e recompiled procedure or pac5age bodies t/at deBine t/e procedures t/at call t/e recompiled procedureI are also invalidated) Pac5ages: 0/e %O=PIL( P.%?. ( option recompiles bot/ t/e pac5age speciBication and t/e bod,A regardless oB 2/et/er it is invalid) 0/e %O=PIL( SP(%I:I%.0IO< option recompiles t/e pac5age speciBication) 1ecompiling a pac5age speciBication invalidates an, local ob3ects t/at depend on t/e speciBicationA suc/ as subprograms t/at use t/e pac5age) <ote t/at t/e bod, oB a pac5age also depends on its speciBication) 0/e %O=PIL( 6OD8 option recompiles onl, t/e pac5age bod,) 0riggers: (Cplicit recompilation eliminates t/e need Bor implicit runEtime recompilation and prevents associated runEtime compilation errors and perBormance over/ead) 0/e D(6U option instructs t/e PL/SQL compiler to generate and store t/e code Bor use b, t/e PL/SQL debugger)

c ra O l, - On

, em ad .c

ra c O

le

l ae rn Uste

Oracle Database 11g: Develop PL/SQL Program Units 1& E *&

In

UnsuccessBul 1ecompilation
1ecompiling dependent procedures and Bunctions is unsuccessBul 2/en: 0/e reBerenced ob3ect is dropped or renamed 0/e data t,pe oB t/e reBerenced column is c/anged 0/e reBerenced column is dropped . reBerenced vie2 is replaced b, a vie2 2it/ diBBerent columns 0/e parameter list oB a reBerenced procedure is modiBied

%op,rig/t @ &''"A Oracle) .ll rig/ts reserved)

UnsuccessBul 1ecompilation Sometimes a recompilation oB dependent procedures is unsuccessBul HBor eCampleA 2/en a reBerenced table is dropped or renamedI)

0/e success oB an, recompilation is based on t/e eCact dependenc,) IB a reBerenced vie2 is reE createdA an, ob3ect t/at is dependent on t/e vie2 needs to be recompiled) 0/e success oB t/e recompilation depends on t/e columns t/at t/e vie2 no2 containsA as 2ell as t/e columns t/at t/e dependent ob3ects rePuire Bor t/eir eCecution) IB t/e rePuired columns are not part oB t/e ne2 vie2A t/en t/e ob3ect remains invalid)

c ra O l, - On

, em ad .c

ra c O

le In

l ae rn Uste

Oracle Database 11g: Develop PL/SQL Program Units 1& E **

SuccessBul 1ecompilation
1ecompiling dependent procedures and Bunctions is successBul iB: 0/e reBerenced table /as ne2 columns 0/e data t,pe oB reBerenced columns /as not c/anged . private table is droppedA but a public table t/at /as t/e same name and structure eCists 0/e PL/SQL bod, oB a reBerenced procedure /as been modiBied and recompiled successBull,

%op,rig/t @ &''"A Oracle) .ll rig/ts reserved)

SuccessBul 1ecompilation 0/e recompilation oB dependent ob3ects is successBul iB: <e2 columns are added to a reBerenced table .ll I<S(10 statements include a column list <o ne2 column is deBined as <O0 <ULL

l e

>/en a private table is reBerenced b, a dependent procedure and t/e private table is droppedA t/e status oB t/e dependent procedure becomes invalid) >/en t/e procedure is recompiled Heit/er eCplicitl, or implicitl,I and a public table eCistsA t/e procedure can recompile successBull, but is no2 dependent on t/e public table) 0/e recompilation is successBul onl, iB t/e public table contains t/e columns t/at t/e procedure rePuiresR ot/er2iseA t/e status oB t/e procedure remains invalid)

c ra O l, - On

, em ad .c

ra c O

le In

l ae rn Uste

Oracle Database 11g: Develop PL/SQL Program Units 1& E *!

1ecompiling Procedures
=inimi4e dependenc, Bailures b,: Declaring records 2it/ t/e Q1O>08P( attribute Declaring variables 2it/ t/e Q08P( attribute Quer,ing 2it/ t/e S(L(%0 K notation Including a column list 2it/ I<S(10 statements

%op,rig/t @ &''"A Oracle) .ll rig/ts reserved)

1ecompilation oB Procedures 8ou can minimi4e recompilation Bailure b, Bollo2ing t/e guidelines t/at are s/o2n in t/e slide)

c ra O l, - On

, em ad .c

ra c O

le In

l ae rn Uste

Oracle Database 11g: Develop PL/SQL Program Units 1& E *+

Pac5ages and Dependencies: Subprogram 1eBerences t/e Pac5age

Procedure . declaration Pac5age speciBication

StandEalone procedure

Pac5age bod,

Procedure . declaration ) ) ) )

%op,rig/t @ &''"A Oracle) .ll rig/ts reserved)

Pac5ages and Dependencies: Subprogram 1eBerences t/e Pac5age 8ou can simpliB, dependenc, management 2it/ pac5ages 2/en reBerencing a pac5age procedure or Bunction Brom a standEalone procedure or Bunction) IB t/e pac5age bod, c/anges and t/e pac5age speciBication does not c/angeA t/en t/e standE alone procedure t/at reBerences a pac5age construct remains valid) IB t/e pac5age speciBication c/angesA t/en t/e outside procedure reBerencing a pac5age construct is invalidatedA as is t/e pac5age bod,)

c ra O l, - On

, em ad .c

Pac5age deBinition c/anged

ra c O

le In

l ae rn Uste

Oracle Database 11g: Develop PL/SQL Program Units 1& E *$

Pac5ages and Dependencies: Pac5age Subprogram 1eBerences Procedure

Procedure . declaration Pac5age speciBication

StandEalone procedure deBinition c/anged

Pac5age bod,

Procedure . declaration ) ) ) )

%op,rig/t @ &''"A Oracle) .ll rig/ts reserved)

Pac5ages and Dependencies: Pac5age Subprogram 1eBerences Procedure IB a standEalone procedure t/at is reBerenced 2it/in t/e pac5age c/angesA t/en t/e entire pac5age bod, is invalidatedA but t/e pac5age speciBication remains valid) 0/ereBoreA it is recommended t/at ,ou bring t/e procedure into t/e pac5age)

c ra O l, - On

, em ad .c

ra c O

le In

l ae rn Uste

Oracle Database 11g: Develop PL/SQL Program Units 1& E *G

Qui4
8ou can displa, direct and indirect dependencies b, running t/e utldtree)sPl scriptA populating t/e D(P01((L0(=P0.6 table 2it/ inBormation Bor a particular reBerenced ob3ectA and Puer,ing t/e D(P01(( or ID(P01(( vie2s) 1) 0rue &) :alse

%op,rig/t @ &''"A Oracle) .ll rig/ts reserved)

.ns2er: 1 Displa,ing Direct and Indirect Dependencies 8ou can displa, direct and indirect dependencies as Bollo2s: 1) 1un t/e utldtree)sPl scriptA 2/ic/ creates t/e ob3ects t/at enable ,ou to displa, t/e direct and indirect dependencies) &) Populate t/e D(P01((L0(=P0.6 table 2it/ inBormation Bor a particular reBerenced ob3ect b, eCecuting t/e D(P01((L:ILL procedure) *) Quer, t/e D(P01(( or ID(P01(( vie2s)

c ra O l, - On

, em ad .c

ra c O

le In

l ae rn Uste

Oracle Database 11g: Develop PL/SQL Program Units 1& E *#

Summar,
In t/is lessonA ,ou s/ould /ave learned /o2 to: 0rac5 procedural dependencies Predict t/e eBBect oB c/anging a database ob3ect on procedures and Bunctions =anage procedural dependencies

%op,rig/t @ &''"A Oracle) .ll rig/ts reserved)

Summar, .void disrupting production b, 5eeping trac5 oB dependent procedures and recompiling t/em manuall, as soon as possible aBter t/e deBinition oB a database ob3ect c/anges)

c ra O l, - On

, em ad .c

ra c O

le In

l ae rn Uste

Oracle Database 11g: Develop PL/SQL Program Units 1& E *"

Practice 1& Overvie2: =anaging Dependencies in 8our Sc/ema


0/is practice covers t/e Bollo2ing topics: Using D(P01((L:ILL and ID(P01(( to vie2 dependencies 1ecompiling proceduresA BunctionsA and pac5ages

%op,rig/t @ &''"A Oracle) .ll rig/ts reserved)

Practice 1&: Overvie2 In t/is practiceA ,ou use t/e D(P01((L:ILL procedure and t/e ID(P01(( vie2 to investigate dependencies in ,our sc/ema) In additionA ,ou recompile invalid proceduresA BunctionsA pac5agesA and vie2s)

c ra O l, - On

, em ad .c

ra c O

le In

l ae rn Uste

Oracle Database 11g: Develop PL/SQL Program Units 1& E !'

You might also like