unit 5 plsql fundamentals - part ii

Upload: shruthig29111988

Post on 03-Jun-2018

239 views

Category:

Documents


1 download

TRANSCRIPT

  • 8/13/2019 Unit 5 PLSQL Fundamentals - Part II

    1/63

    DBMS Unit 4 Procedural SQL Fundamentals: Part II

    Procedural SQL Fundamentals

    Part II Procedure, Function, Package, Trigger

    Table of ContentsProcedures and Functions...........................................................................................................1

    Overvie.............................................................................................................................1

    !reatin" Procedure..............................................................................................................#

    Develo$in" Procedures.......................................................................................................%

    I& Parameters..............................................................................................................'

    OU( Parameters..........................................................................................................'

    I& OU( Parameters.....................................................................................................)

    D*F+UL( O$tion ,or Parameters.............................................................................1-

    Invoin" Procedure...........................................................................................................1/

    Declarin" Su0$ro"rams.............................................................................................1/

    Invoin" a Procedure ,rom an +nonmous PL2SQL Bloc......................................1#

    Invoin" a Procedure ,rom +not3er Procedure........................................................1#

    emovin" Procedures...............................................................................................1#

    !reatin" Functions............................................................................................................14

    Develo$ Stored Functions.................................................................................................1%

    *5ecutin" Functions..........................................................................................................1%

    Invoin" Functions in SQL *5$ressions...................................................................16

    estrictions on !allin" Functions ,rom SQL *5$ressions.......................................17

    emovin" Functions.................................................................................................1'

    !om$arin" Procedures and Functions..............................................................................1'

    Mana"in" Stored PL2SQL O08ects............................................................................................1'

    US*9OB*!(S Data Dictionar ;ie..........................................................................1'

    US*9SOU!* Data Dictionar ;ie...........................................................................1)

    US*9*OS Data Dictionar ;ie...........................................................................1)

    Summar.........................................................................................................................../-Paca"e...................................................................................................................................../-

    Overvie o, Paca"es......................................................................................................./-

    !reatin" Paca"es.............................................................................................................//

    !reatin" t3e Paca"e S$eci,ication...........................................................................//

    !reatin" t3e Paca"e Bod......................................................................................./#

    Invoin" Paca"e !onstructs............................................................................................/%

    Declarin" a Bodiless Paca"e.................................................................................../%

    emovin" Paca"es........................................................................................................../6

  • 8/13/2019 Unit 5 PLSQL Fundamentals - Part II

    2/63

    DBMS Unit 4 Procedural SQL Fundamentals: Part II

    Oracle Su$$lied Paca"es................................................................................................./7

    Usin" t3e DBMS9SQL Paca"e.............................................................................../'

    Usin" t3e DBMS9DDL Paca"e..............................................................................#-

    Usin" DBMS9OB ,or Sc3edulin"...........................................................................#-

    Usin" t3e DBMS9OU(PU( Paca"e.......................................................................##

    U(L9FIL* Paca"e..................................................................................................##

    (3e U(L9=((P Paca"e..........................................................................................#7

    Usin" t3e U(L9(!P Paca"e...................................................................................#'

    Ot3er Oracle>su$$lied $aca"es...............................................................................#'

    (ri""er.......................................................................................................................................4/

    !reatin" DML (ri""ers.....................................................................................................4#

    Basic (ri""er Snta5:................................................................................................4%

    !reatin" a DML o (ri""er...................................................................................47

    I&S(*+D OF (ri""ers.....................................................................................................%1

    !reatin" an I&S(*+D OF (ri""er...........................................................................%1

    Di,,erentiatin" Beteen Data0ase (ri""ers and Stored Procedures.........................%7

    Mana"in" (ri""er..............................................................................................................%7

    Dis$lain" (ri""er De,inition *rrors........................................................................%7

    ;iein" De,ined (ri""ers.........................................................................................%7

    Dro$$in" (ri""ers.....................................................................................................%7

    Disa0lin" (ri""ers.....................................................................................................%7

    ecom$ile a tri""er ,or a ta0le:.................................................................................%'

    +0ortin" (ri""ers it3 *rror....................................................................................%'

    ii

  • 8/13/2019 Unit 5 PLSQL Fundamentals - Part II

    3/63

    DBMS Unit 4 Procedural SQL Fundamentals: Part II

    Procedures and Functions

    Overview

    PL2SQL Pro"ram !onstructs

    *ver

    PL2SQL construct is com$osed o, one or more 0locs. (3ese 0locs can 0e entirel

    se$arate or nested it3in one anot3er. (3ere,ore? one 0loc can re$resent a small

    $art o, anot3er 0loc? 3ic3 in turn can 0e $art o, t3e 3ole unit o, code.

    PL2SQL $rocedures 0e3ave ver muc3 lie $rocedures? or su0>$ro"rams? in ot3er

    $ro"rammin" lan"ua"e. + su0$ro"ram:

    Is a named PL2SQL 0loc t3at can acce$t $arameters and 0e invoed ,rom a callin"

    environment

    Is o, to t$es:

    + $rocedure t3at $er,orms an action

    + ,unction t3at com$utes a value

    Is 0ased on standard PL2SQL 0loc structure

    Provides modularit? reusa0ilit? e5tensi0ilit? and maintaina0ilit Provides eas maintenance? im$roved data securit and inte"rit? im$roved

    $er,ormance? and im$roved code clarit

    Bloc Structure ,or +nonmous PL2SQL Blocs

    DECLARE (optional)

    Declare PL2SQL o08ects to 0e used it3in t3is 0loc

    BEGIN (mandatory)

    De,ine t3e e5ecuta0le statements

    EXCEPTION (optional)

    1

  • 8/13/2019 Unit 5 PLSQL Fundamentals - Part II

    4/63

    DBMS Unit 4 Procedural SQL Fundamentals: Part II

    De,ine t3e actions t3at tae $lace i, an error or e5ce$tion arises

    END; (mandatory)

    (3e section 0eteen t3e eords DECLAREand BEGINis re,erred to as t3e

    declaration section. In t3e declaration section? ou de,ine t3e PL2SQL o08ects suc3as varia0les? constants? cursors? and user>de,ined e5ce$tions t3at ou ant to

    re,erence it3in t3e 0loc. (3e DECLAREeord is o$tional i, ou do not declare

    an PL2SQL o08ects.

    (3e BEGINand ENDeords are mandator and enclose t3e 0od o, actions to 0e

    $er,ormed. (3is section is re,erred to as t3e e5ecuta0le section o, t3e 0loc.

    (3e section 0eteen EXCEPTIONand ENDis re,erred to as t3e e5ce$tion section.

    (3e e5ce$tion section tra$s error conditions. In it? ou de,ine actions to tae i, t3e

    s$eci,ied condition arises. (3e e5ce$tion section is o$tional.

    (3e eords DECLARE? BEGIN? and EXCEPTIONare not ,olloed 0

    semicolons? 0ut ENDand all ot3er PL2SQL statements do re@uire semicolons.

    Bloc Structure ,or PL2SQL Su0$ro"rams

  • 8/13/2019 Unit 5 PLSQL Fundamentals - Part II

    5/63

    DBMS Unit 4 Procedural SQL Fundamentals: Part II

    enclosin" t3e 0od o, actions to 0e $er,ormed. (3ere must 0e at least one

    statement e5istin" in t3is section. (3ere s3ould 0e at least a N,LLA statement?

    t3at is considered an e5ecuta0le statement.

    (3e e5ce$tion section 0eteen EXCEPTIONand ENDis o$tional. (3is section

    tra$s $rede,ined error conditions. In t3is section? ou de,ine actions to tae i,

    t3e s$eci,ied error condition arises.

    3en a se@uence o, statements is re$eated more t3an once in a PL2SQL

    su0$ro"ram? ou can create a su0$ro"ram it3 t3e re$eated code.

    Cou can invoe t3e su0$ro"ram at multi$le locations in a PL2SQL 0loc.

    +,ter t3e su0$ro"ram is created and stored in t3e data0ase? it can 0e invoed an

    num0er o, times and ,rom multi$le a$$lications.

    =ere is an e5am$le o, a PL2SQL $rocedure addtu$le1 t3at? "iven an inte"er i? inserts t3e

    tu$le i? E555E into t3e ,olloin" e5am$le relation:

    CREATE TABLE T- (

    a INTEGER.

    & C/AR(01)

    );

    CREATE PROCED,RE addt%pl0(i IN N,2BER) A$

    BEGIN

    IN$ERT INTO T- 3AL,E$(i. 4+++4);

    END addt%pl0;

    (o ,ind out 3at $rocedures and ,unctions ou 3ave created? use t3e ,olloin" SQL

    @uer:

    $5L! $ELECT o&6t7typ. o&6t7nam

    - 8RO2 %*r7o&6t*

    9 :/ERE o&6t7typ 4PROCED,RE4

    OR o&6t7typ 48,NCTION4;

    (o ,i"ure our $rocedures e5istin" in t3e sc3ema? c3ec user9$rocedures

    $5L! DE$C %*r7prod%r*

    $5L! $ELECT o&6t7nam. prod%r7nam 8RO2 %*r7prod%r* ;

    (o dro$ a stored $rocedure2,unction:

    $5L! DROP PROCED,REprocedure_name;

    $5L! DROP 8,NCTION function_name;

    Creating Procedure

    + $rocedure is a t$e o, su0$ro"ram t3at $er,orms an action.

    #

  • 8/13/2019 Unit 5 PLSQL Fundamentals - Part II

    6/63

    DBMS Unit 4 Procedural SQL Fundamentals: Part II

    + $rocedure can 0e stored in t3e data0ase? as a sc3ema o08ect? ,or re$eated e5ecution.

    + $rocedure is introduced 0 t3e eords CREATE PROCED,RE,olloed 0 t3e

    $rocedure name and its $arameters. +n o$tion is to ,ollo CREATE0 OR REPLACE.

    (3e advanta"e o, doin" so is t3at s3ould ou 3ave alread made t3e de,inition? ou ill

    not "et an error. On t3e ot3er 3and? s3ould t3e $revious de,inition 0e a di,,erent

    $rocedure o, t3e same name? ou ill not 0e arned? and t3e old $rocedure ill 0e lost.

    (3ere can 0e an num0er o, $arameters? eac3 ,olloed 0 a mode and a t$e. (3e

    $ossi0le modes are INread>onl? O,Trite>onl? and IN O,Tread and rite.

    Note: (3e t$e s$eci,ier in a $arameter declaration must 0e unconstrained. For e5am$le?

    C/AR(01)and 3ARC/AR(-1)are ille"alA C/ARor 3ARC/ARs3ould 0e used instead.

    (3e Snta5 ,or !reatin" Procedures

    $ynta+=

    CREATE >OR REPLACE? PROCED,REprocedure_name

    >(paramtr0 >mod0? datatyp0.

    paramtr- >mod-? datatyp-.

    @ @ @)?

    I$#A$

    PL$5L Blo;

    Snta5 De,initions

    Parameter Description

    procedure_name &ame o, t3e $rocedure

    parameter &ame o, a PL2SQL varia0le 3ose value is $assed to or $o$ulated 0 t3e

    callin" environment? or 0ot3? de$endin" on t3e mode 0ein" used

    mode ($e o, ar"ument:

    INde,ault

    OU(

    I& OU(

    Data type Data t$e o, t3e ar"umentcan 0e an SQL 2 PLSQL data t$e. !an 0e o,

    TPE? RO:TPE? or an scalar or com$osite data t$e.

    PL/SQL block Procedural 0od t3at de,ines t3e action $er,ormed 0 t3e $rocedure

    PL2SQL 0locs start it3 eit3er BEGINor t3e declaration o, local varia0les and end

    it3 eit3er ENDor END$rocedure9name. Cou cannot re,erence 3ost or 0ind

    varia0les in t3e PL2SQL 0loc o, a stored $rocedure.

    (3e REPLACEo$tion indicates t3at i, t3e $rocedure e5ists? it ill 0e dro$$ed and

    re$laced it3 t3e ne version created 0 t3e statement.

    Cou cannot restrict t3e siGe o, t3e data t$e in t3e $arameters.

    4

  • 8/13/2019 Unit 5 PLSQL Fundamentals - Part II

    7/63

    DBMS Unit 4 Procedural SQL Fundamentals: Part II

    Developing Procedures

    Folloin" are t3e main ste$s ,or develo$in" a stored $rocedure.

    1. Write the syntax: *nter t3e code to create a $rocedure in a sstem editor or ord

    $rocessor and save it as a SQL scri$t ,ile .s@l e5tension.

    /. Compile the code: Usin" iSQLHPlus? load and run t3e SQL scri$t ,ile. (3e source

    code is com$iled intoP codeand t3e $rocedure is created.

    In iSQLHPlus? use $/O: ERROR$to see an com$ilation errors. Fi5 t3e errors in

    t3e code usin" t3e editor and recom$ile t3e code.

    #. *5ecute t3e $rocedure to $er,orm t3e desired action. +,ter t3e source code is

    com$iled and t3e $rocedure is success,ull created? t3e $rocedure can 0e e5ecuted

    an num0er o, times usin" t3e EXEC,TEcommand ,rom iSQLHPlus. (3e PL2SQLcom$iler "enerates t3epseudocodeorP code? 0ased on t3e $arsed code. (3e

    PL2SQL en"ine e5ecutes t3is 3en t3e $rocedure is invoed.

    &ote: I, t3ere are an com$ilation errors? and ou mae su0se@uent c3an"es to t3e

    CREATE PROCED,REstatement? ou must eit3er DROPt3e $rocedure ,irst? or use

    t3e OR REPLACEsnta5.

    Formal ;ersus +ctual Parameters

    Formal $arameters: varia0les declared in t3e $arameter list o, a su0$ro"ram

    s$eci,ication. For e5am$le? in t3e $rocedure RAI$E7$AL0elo? t3e varia0les

    P7IDand P7A2O,NTare ,ormal $arameters.

    %

  • 8/13/2019 Unit 5 PLSQL Fundamentals - Part II

    8/63

    DBMS Unit 4 Procedural SQL Fundamentals: Part II

    CREATE PROCED,RE rai*7*al(p7id N,2BER. p7amo%nt N,2BER)

    @@@

    END rai*7*al;

    +ctual $arameters: varia0les or e5$ressions re,erenced in t3e $arameter list o, a

    su0$ro"ram call. For e5am$le? in t3e call rai*7*al(7id . -111)to t3e

    $rocedure RAI$E7$AL? t3e varia0le 37IDand -111are actual $arameters.

    Met3ods ,or Passin" Parameters

    Positional: List actual $arameters in t3e same order as ,ormal $arametersA i.e.? lists

    values in t3e order in 3ic3 t3e $arameters are declared.

    &amed: List actual $arameters in ar0itrar order 0 associatin" eac3 it3 its

    corres$ondin" ,ormal $arameter. It lists values in ar0itrar order 0 associatin"

    eac3 one it3 its $arameter name? usin" s$ecial snta5 J

    !om0ination: List some o, t3e actual $arameters as $ositional and some as named.

    Lists t3e ,irst values $ositionall? and t3e remainder usin" t3e s$ecial snta5 o, t3e

    named met3od.

    Procedural Parameter Modes

    IN (da%lt) Passes a constant value ,rom t3e callin" environment into t3e

    $rocedure

    O,T Passes a value ,rom t3e $rocedure to t3e callin" environment

    IN O,T Passes a value ,rom t3e callin" environment into t3e $rocedure and a

    $ossi0l di,,erent value ,rom t3e $rocedure 0ac to t3e callin" environment usin"

    t3e same $arameter

    Note: D+(+(CP* can 0e onl t3eTPEde,inition? t3e RO:TPEde,inition? or

    an e5$licit data t$e it3 no siGe s$eci,ication.

    !reatin" Procedures it3 Parameters

    IN O,T IN O,T

    De,ault mode Must 0e s$eci,ied Must 0e s$eci,ied

    ;alue is $assed into

    su0$ro"ram

    eturned to callin"

    environment

    Passed into su0$ro"ramA

    returned to callin"environment

    Formal $arameter acts as a

    constant

    UninitialiGed varia0le InitialiGed varia0le

    +ctual $arameter can 0e a

    literal? e5$ression? constant? or

    initialiGed varia0le

    Must 0e a varia0le Must 0e a varia0le

    !an 0e assi"ned a de,ault

    value

    !annot 0e assi"ned a de,ault

    value

    !annot 0e assi"ned a de,ault

    value

    6

  • 8/13/2019 Unit 5 PLSQL Fundamentals - Part II

    9/63

    DBMS Unit 4 Procedural SQL Fundamentals: Part II

    + @uic e5am$le:

    (3e ,olloin" $rocedure also inserts a tu$le into (/? 0ut it taes 0ot3 com$onents as

    ar"uments:

    CREATE PROCED,RE addt%pl-( + T-@aTPE.

    y T-@&TPE)

    A$

    BEGIN

    IN$ERT INTO T-(a. &)

    3AL,E$(+. y);

    END addt%pl-;

    &o? to add a tu$le 1-? Ea0cE to (/:

    BEGIN

    addt%pl-(01. 4a&4);

    END;

    (3e ,olloin" illustrates t3e use o, an O,T$arameter:

    CREATE TABLE T9 (

    a INTEGER.

    & INTEGER

    );

    CREATE PROCED,RE addt%pl9(a N,2BER. & O,T N,2BER)

    A$

    BEGIN

    & = ;

    IN$ERT INTO T9 3AL,E$(a. &);

    END;

    *5ecute t3e $rocedure

    DECLARE

    N,2BER;

    BEGIN

    addt%pl9(01. );

    END;

    7

  • 8/13/2019 Unit 5 PLSQL Fundamentals - Part II

    10/63

    DBMS Unit 4 Procedural SQL Fundamentals: Part II

    &ote t3at assi"nin" values to $arameters declared as O,Tor IN O,Tcauses t3e

    corres$ondin" in$ut ar"uments to 0e ritten. Because o, t3is? t3e in$ut ar"ument ,or

    an O,Tor IN O,T$arameter s3ould 0e somet3in" it3 an KlvalueK? suc3 as a

    varia0le lie v in t3e e5am$le a0ove. + constant or a literal ar"ument s3ould not 0e

    $assed in ,or an O,TIN O,T$arameter.

    INParameters

    *5am$le

    unnin" t3is statement in iSQLHPlus creates t3e RAI$E7$ALAR$rocedure.

    3en invoed? RAI$E7$ALARacce$ts t3e $arameter ,or t3e em$loee ID and

    u$dates t3e em$loees record it3 a salar increase o, 1- $ercent.

    CREATE OR REPLACE PROCED,RE rai*7*alary

    (p7id IN mploy*@mploy7idTPE)

    I$

    BEGIN

    ,PDATE mploy*

    $ET *alary *alary F 0@01

    :/ERE mploy7id p7id;

    END rai*7*alary;

    (o invoe a $rocedure in iSQLHPlus? use t3e EXEC,TEcommand.

    EXEC,TE rai*7*alary (0H)

    (o invoe a $rocedure ,rom anot3er $rocedure? use a direct call. +t t3e location o,

    callin" t3e ne $rocedure? enter t3e $rocedure name and actual $arameters.

    rai*7*alary (0H);

    OUTParameters

    *5am$le edit a scri$t ,ile [email protected]@l ,or ,olloin" e5am$le

    !reate a $rocedure it3 O,T$arameters to retrieve in,ormation a0out an em$loee.

    CREATE OR REPLACE PROCED,RE %ry7mp

    (p7id IN mp@mpnoTPE.

    p7nam O,T mp@namTPE.

    p7*alary O,T mp@*alTPE.

    p7omm O,T mp@ommTPE)

    I$

    BEGIN

    $ELECT nam. *al. omm

    '

  • 8/13/2019 Unit 5 PLSQL Fundamentals - Part II

    11/63

    DBMS Unit 4 Procedural SQL Fundamentals: Part II

    INTO p7nam. p7*alary. p7omm

    8RO2 mp

    :/ERE mpno p7id;

    END %ry7mp; (3e $rocedure acce$ts a value 76%4 ,or em$loee ID and retrieves t3e name? salar?

    and commission $ercenta"e o, t3e em$loee it3 ID 76%4 into t3e t3ree out$ut

    $arameters.

    $5L! 3ARIABLE '7nam 3ARC/AR-(0J)

    $5L! 3ARIABLE '7*al N,2BER(J)

    $5L! 3ARIABLE '7omm N,2BER()

    $5L! EXEC %ry7mp (HJ. ='7nam. ='7*al. ='7omm)

    PL$5L prod%r *%**%lly ompltd@

    $5L! PRINT '7nam '7*al '7omm@

    G7NA2E G7$AL G7CO22

    """"""""""""""""""""""""""""

    2ARTIN 0-J1 011

    ;iein" O,TParameters

    1. un t3e SQL scri$t ,ile to "enerate and com$ile t3e source code.

    /. !reate 3ost varia0les in iSQLHPlus? usin" t3e ;+I+BL* command.

    #. Invoe t3e QU*C9*MP $rocedure? su$$lin" t3ese 3ost varia0les as t3e

    OU( $arameters. &ote t3e use o, t3e colon : to re,erence t3e 3ost varia0les in

    t3e **!U(* command.

    4. (o vie t3e values $assed ,rom t3e $rocedure to t3e callin" environment? use

    t3e PI&( command.

    Note: Passin" a constant or e5$ression as an actual $arameter to t3e OU( varia0le

    causes com$ilation errors.

    For e5am$le:

    EXEC,TE %ry7mp(00. ='7nam. rai*K011. ='7omm)

    causes a com$ilation error.

    IN OUTParameters

    *5am$le

    +n IN O,T$arameter acts as an initialiGed varia0le. !reate a $rocedure it3 an

    IN O,T$arameter to acce$t a c3aracter strin" containin" 1- di"its and return a

    $3one num0er ,ormatted as '-- 6##>-%7%.

    )

  • 8/13/2019 Unit 5 PLSQL Fundamentals - Part II

    12/63

    DBMS Unit 4 Procedural SQL Fundamentals: Part II

    un t3e statement to create t3e 8OR2AT7P/ONE$rocedure.

    CREATE OR REPLACE PROCED,RE ormat7phon

    (p7phon7no IN O,T 3ARC/AR-)

    I$BEGIN

    p7phon7no = 4(4 ## $,B$TR(p7phon7no.0.9) ##

    4)4 ## $,B$TR(p7phon7no..9) ##

    4"4 ## $,B$TR(p7phon7no.);

    END ormat7phon;

    ;iein" IN O,TParameters

    1. !reate a 3ost varia0le? usin" t3e 3ARIABLEcommand.

    /. Po$ulate t3e 3ost varia0le it3 a value? usin" an anonmous PL2SQL 0loc.

    #. Invoe t3e 8OR2AT7P/ONE$rocedure? su$$lin" t3e 3ost varia0le as t3e IN

    O,T$arameter.

    4. &ote t3e use o, t3e colon : to re,erence t3e 3ost varia0le in t3e EXEC,TE

    command.

    %. (o vie t3e value $assed 0ac to t3e callin" environment? use t3e PRINT

    command.

    $5L! 3ARIABLE '7phon7no 3ARC/AR-(0J)

    $5L! BEGIN

    - ='7phon7no = 411H991JJ4;

    9 END;

    PL$5L prod%r *%**%lly ompltd@

    $5L! PRINT '7phon7no

    G7P/ONE7NO

    """"""""""""""""""""""""""""""""

    11H991JJ

    $5L! EXEC,TE ormat7phon (='7phon7no)

    PL$5L prod%r *%**%lly ompltd@

    $5L! PRINT '7phon7no

    G7P/ONE7NO

    """"""""""""""""""""""""""""""""

    (11)H99"1JJ

    DEFAULTOption for Parameters

    Cou can initialiGe I& $arameters to de,ault values. (3at a? ou can $ass di,,erent

    1-

  • 8/13/2019 Unit 5 PLSQL Fundamentals - Part II

    13/63

    DBMS Unit 4 Procedural SQL Fundamentals: Part II

    num0ers o, actual $arameters to a su0$ro"ram? acce$tin" or overridin" t3e de,ault values

    as ou $lease.

    Moreover? ou can add ne ,ormal $arameters it3out 3avin" to c3an"e ever call to t3e

    su0$ro"ram.

    Cou can assi"n de,ault values onl to $arameters o, t3e INmode. O,Tand IN O,T

    $arameters are not $ermitted to 3ave de,ault values.

    I, de,ault values are $assed to t3ese t$es o, $arameters? ou "et t3e ,olloin"

    com$ilation error:

    PLS>--/#-: O,Tand IN O,T,ormal $arameters ma not 3ave de,ault e5$ressions

    *5am$le:

    CREATE OR REPLACE PROCED,RE add7dpt

    (p7no IN dpt@dptnoTPE DE8A,LT J1.

    p7nam IN dpt@dnamTPE DE8A,LT 4%nnoMn4.

    p7lo IN dpt@loTPE DE8A,LT 4TAIPEI4)

    I$

    BEGIN

    IN$ERT INTO dpt(dptno. dnam. lo)

    3AL,E$ (p7no. p7nam. p7lo);

    END add7dpt;

    I, an actual $arameter is not $assed? t3e de,ault value o, its corres$ondin" ,ormal

    $arameter is used.

    *5am$les o, Passin" Parameters

    BEGIN

    add7dpt;

    add7dpt (H1. 4TRAINING4. 4TAIC/,NG4);

    add7dpt (p7lo ! 4TAINAN4. p7nam !4ED,CATION4);

    add7dpt (p7lo ! 4/$INC/,4) ;

    END;

    $ELECT dptno. dnam. lo 8RO2 dpt;

    (3e anonmous 0loc a0ove s3os t3e di,,erent as t3e ADD7DEPT$rocedure

    can 0e invoed? and t3e out$ut o, eac3 a t3e $rocedure is invoed.

    &ote: +ll t3e $ositional $arameters s3ould $recede t3e named $arameters in a

    su0$ro"ram call. Ot3erise? ou ill receive an error messa"e? as s3on in t3e

    ,olloin" e5am$le:

    $5L! EXEC,TE add7dpt(p7no!H1. p7nam!4TRAINING4.

    4TAIC/,NG4);

    11

  • 8/13/2019 Unit 5 PLSQL Fundamentals - Part II

    14/63

    DBMS Unit 4 Procedural SQL Fundamentals: Part II

    BEGIN add7dpt(p7no!H1. p7nam!4TRAINING4. 4TAIC/,NG4); END;

    F

    ERROR at lin 0=

    ORA"1HJJ1= lin 0. ol%mn H=PL$"1190-= a po*itional paramtr a**oiation may not olloM a

    namd a**oiation

    ORA"1HJJ1= lin 0. ol%mn =

    PL$5L= $tatmnt i'nord

    Invoking Procedure

    Declaring Subprograms

    Cou can declare su0$ro"rams in an PL2SQL 0loc. (3is is an alternative to creatin" t3e

    stand>alone $rocedure LOG7EXECit3in LEA3E7E2P. For e5am$le?

    CREATE OR REPLACE PROCED,RE la7mp

    (p7id IN mploy*@mploy7idTPE)

    I$

    PROCED,RE lo'7+

    I$

    BEGIN

    IN$ERT INTO lo'7ta&l (%*r7id. lo'7dat)

    3AL,E$ (,$ER. $$DATE);

    END lo'7+;

    BEGIN

    DELETE 8RO2 mp

    :/ERE mpno p7id;

    lo'7+;

    END la7mp;

    Su0$ro"rams declared in t3is manner are called local su0$ro"rams or local modules.

    Because t3e are de,ined it3in a declaration section o, anot3er $ro"ram.

    (3e sco$e o, local su0$ro"rams is limited to t3e $arent enclosin" 0loc in 3ic3 t3e

    are de,ined. (3is means t3at local su0$ro"rams cannot 0e called ,rom outside t3e 0loc

    in 3ic3 t3e are declared.

    Declarin" local su0$ro"rams en3ances t3e clarit o, t3e code 0 assi"nin" a$$ro$riate

    0usiness>rule identi,iers to 0locs o, code.

    &ote:

    Cou must declare t3e su0$ro"ram in t3e declaration section o, t3e 0loc? and it must

    0e t3e last item? a,ter all t3e ot3er $ro"ram items.

    1/

  • 8/13/2019 Unit 5 PLSQL Fundamentals - Part II

    15/63

    DBMS Unit 4 Procedural SQL Fundamentals: Part II

    For e5am$le? a varia0le declared a,ter t3e end o, t3e su0$ro"ram? 0e,ore t3e BEGIN

    o, t3e $rocedure? ill cause a com$ilation error.

    I, t3e code must 0e accessed 0 multi$le a$$lications? $lace t3e su0$ro"ram in a

    $aca"e or create a stand>alone su0$ro"ram it3 t3e code.

    Invoking a Procedure from an Anonymous PL/SQL Block

    For e5am$le? invoe t3e RAI$E7$ALAR$rocedure ,rom an anonmous PL2SQL

    0loc. Procedures are calla0le ,rom an tool or lan"ua"e t3at su$$orts PL2SQL.

    DECLARE

    7id N,2BER = 0H9;

    BEGIN

    rai*7*alary(7id); ""ino prod%r

    CO22IT;

    @@@

    END;

    Invoking a Procedure from Anoter Procedure

    For e5am$le:

    CREATE OR REPLACE PROCED,RE pro**7mp*

    I$

    C,R$OR mp7%r*or I$

    $ELECT mpno 8RO2 mp;

    BEGIN

    8OR mp7r IN mp7%r*or

    LOOP

    rai*7*alary(mp7r@mpno);

    END LOOP;

    CO22IT;

    END pro**7mp*;

    (3is e5am$le s3os ou 3o to invoe a $rocedure ,rom anot3er stored $rocedure.

    (3e PROCE$$7E2P$stored $rocedure uses a cursor to $rocess all t3e records in

    t3e E2Pta0le and $asses eac3 em$loees ID to t3e RAI$E7$ALAR$rocedure?

    3ic3 results in a 1- $ercent salar increase across t3e com$an.

    !emoving Procedures

    Dro$ a $rocedure stored in t3e data0ase.

    $ynta+=

    1#

  • 8/13/2019 Unit 5 PLSQL Fundamentals - Part II

    16/63

    DBMS Unit 4 Procedural SQL Fundamentals: Part II

    DROP PROCED,REprocedure_name;

    E+ampl=

    DROP PROCED,RE raise_salary;

    Issuin" roll0ac does not 3ave an e,,ect a,ter e5ecutin" a data de,inition lan"ua"e DDLcommand suc3 as DROP PROCED,RE? 3ic3 commits an $endin" transactions.

    Creating Functions

    e can also rite ,unctions instead o, $rocedures.

    + ,unction is a named PL2SQL 0loc t3at returns a value.

    + ,unction can 0e stored in t3e data0ase as a sc3ema o08ect ,or re$eated e5ecution.

    + ,unction is called as $art o, an e5$ression.

    In a ,unction declaration? e ,ollo t3e $arameter list 0 RET,RNand t3e t$e o, t3e

    return value. (3e snta5 is:

    CREATE >OR REPLACE? 8,NCTION %ntion7nam

    >(paramtr0 >mod0? datatyp0.

    paramtr- >mod-? datatyp-.

    @ @ @)?

    RET,RN datatyp

    I$#A$

    PL$5L Blo;

    (3e REPLACEo$tion indicates t3at i, t3e ,unction e5ists? it ill 0e dro$$ed and

    re$laced it3 t3e ne version created 0 t3e statement.

    (3e RET,RNdata t$e must not include a siGe s$eci,ication.

    PL2SQL 0locs start it3 eit3er BEGINor t3e declaration o, local varia0les and end

    it3 eit3er ENDor END %ntion7nam.

    (3ere must 0e at least one RET,RN+pr**ion statement.

    Cou cannot re,erence 3ost or 0ind varia0les in t3e PL2SQL 0loc o, a stored

    ,unction.

    Snta5 De,initions:

    function_name &ame o, t3e ,unction

    parameter &ame o, a PL2SQL varia0le 3ose value is $assed into t3e ,unction

    mode (3e t$e o, t3e $arameterA onl I& $arameters s3ould 0e declared

    datatype Data t$e o, t3e $arameter

    RETURN datatype Data t$e o, t3e *(U& value t3at must 0e out$ut 0 t3e

    ,unction

    PL/SQL block Procedural 0od t3at de,ines t3e action $er,ormed 0 t3e ,unction

    14

  • 8/13/2019 Unit 5 PLSQL Fundamentals - Part II

    17/63

    DBMS Unit 4 Procedural SQL Fundamentals: Part II

    Develop Stored Functions

    (3e ,olloin" are t3e 0asic ste$s ou use to develo$ a stored ,unction. (3e ne5t to

    $a"es $rovide ,urt3er details a0out creatin" ,unctions.

    1. rite t3e snta5: *nter t3e code to create a ,unction in a te5t editor and save it as a

    SQL scri$t ,ile.

    /. !om$ile t3e code: Usin" iSQLHPlus? u$load and run t3e SQL scri$t ,ile. (3e source

    code is com$iled into P code. (3e ,unction is created.

    #. Invoe t3e ,unction ,rom a PL2SQL 0loc.

    eturnin" a ;alue

    +dd a RET,RNclause it3 t3e data t$e in t3e 3eader o, t3e ,unction.

    Include one RET,RNstatement in t3e e5ecuta0le section.

    *5am$le: "et9salar.s@l

    CREATE OR REPLACE 8,NCTION 't7*al

    (p7id IN mp@mpnoTPE)

    RET,RN N,2BER

    I$

    7*alary mp@*alTPE =1;

    BEGIN

    $ELECT *al INTO 7*alary

    8RO2 mp

    :/ERE mpno p7id;

    RET,RN 7*alary;

    END 't7*al;

    xecuting Functions

    *5ecution a ,unction ma acce$t one or man $arameters? 0ut must return a sin"le

    value.

    Invoe a ,unction as $art o, a PL2SQL e5$ression.

    !reate a varia0le to 3old t3e returned value.

    *5ecute t3e ,unction. (3e varia0le ill 0e $o$ulated 0 t3e value returned t3rou"3 a

    RET,RNstatement.

    *5am$le: Load and run t3e "et9salar.s@l ,ile to create t3e ,unction

    $5L! 3ARIABLE '7*alary N,2BER

    $5L! EXEC ='7*alary = 't7*al(9)

    PL$5L prod%r *%**%lly ompltd@

    $5L! PRINT '7*alary

    G7$ALAR

    1%

  • 8/13/2019 Unit 5 PLSQL Fundamentals - Part II

    18/63

    DBMS Unit 4 Procedural SQL Fundamentals: Part II

    """"""""""

    J111

    Invoking "unctions in SQL #$pressions *5am$le: create a ,unction ta5 t3at is invoed ,rom a $ELECTstatement. (3e ,unction

    acce$ts a N,2BER$arameter and returns t3e ta5 a,ter multi$lin" t3e $arameter value

    it3 -.-'.

    $5L! CREATE OR REPLACE 8,NCTION ta+(p7al% IN N,2BER)

    - RET,RN N,2BER

    9 I$

    BEGIN

    J RET,RN (p7al% F 1@1);

    H END ta+;

    *5ecute:

    $5L! $ELECT mpno. nam. *al. ta+(*al)

    - 8RO2 mp

    9 :/ERE dptno 01;

    E2PNO ENA2E $AL TAX($AL)

    """""""""" """""""""" """""""""" """"""""""

    - CLAR -J1 0H

    9 ING J111 11

    9 2ILLER 0911 01

    0111 T7E7$TT -111 0H1

    Usa"e o, User>De,ined Functions

    Select list o, a S*L*!( command

    !ondition o, t3e =** and =+;I&< clauses

    CONNECT B? $TART :IT/? ORDER B? and GRO,P Bclauses

    3AL,E$clause o, t3e IN$ERTcommand

    $ETclause o, t3e ,PDATEcommand

    *5am$le: Find em$loees 3ose ta5 is more t3an t3e ma5imum ta5 in t3e

    de$artment de$tno #-.

    $5L! $ELECT mpno. ta+(*al)

    - 8RO2 mp

    9 :/ERE ta+(*al)!($ELECT 2AX(ta+(*al))

    8RO2 mp :/ERE dptno 91)

    16

  • 8/13/2019 Unit 5 PLSQL Fundamentals - Part II

    19/63

    DBMS Unit 4 Procedural SQL Fundamentals: Part II

    J ORDER B ta+(*al) DE$C;

    !estrictions on %alling "unctions from SQL #$pressions

    3en called ,rom a $ELECTstatement or a $aralleliGed ,PDATEor DELETEstatement?t3e ,unction cannot modi, an data0ase ta0les.

    3en called ,rom an ,PDATE? or DELETEstatement? t3e ,unction cannot @uer or

    modi, an data0ase ta0les modi,ied 0 t3at statement.

    3en called ,rom a $ELECT? IN$ERT? ,PDATE? or DELETEstatement? t3e ,unction

    cannot e5ecute SQL transaction control statements suc3 as CO22IT? session control

    statements suc3 as $ET ROLE? or sstem control statements suc3 as ALTER

    $$TE2. +lso? it cannot e5ecute DDL statements suc3 as CREATE 0ecause t3e are

    ,olloed 0 an automatic commit.

    (3e ,unction cannot call anot3er su0$ro"ram t3at 0reas one o, t3e a0ove restrictions.

    !onsider t3e ,olloin" e5am$le 3ere t3e ,unction 5,ER7CALL7$5L@ueries t3e

    $ALcolumn o, t3e E2Pta0le:

    CREATE OR REPLACE 8,NCTION %ry7all7*l(a N,2BER)

    RET,RN N,2BER

    I$

    * N,2BER;

    BEGIN

    $ELECT *al INTO * 8RO2 mp

    :/ERE mpno 9;

    RET,RN (* K a);

    END;

    (3e a0ove ,unction? 3en invoed ,rom t3e ,olloin" ,PDATEstatement? returns

    t3e error messa"e.

    $5L! ,PDATE mp $ET *al %ry7all7*l()

    - :/ERE mpno 9;

    ,PDATE mp $ET *al %ry7all7*l()

    F

    ERROR at lin 0=

    ORA"110= ta&l $NO:BALL@E2P i* m%tatin'. tri''r%ntion

    may not * it

    ORA"1HJ0-= at $NO:BALL@5,ER7CALL7$5L. lin H

    17

  • 8/13/2019 Unit 5 PLSQL Fundamentals - Part II

    20/63

    DBMS Unit 4 Procedural SQL Fundamentals: Part II

    !emoving "unctions

    Dro$ a stored ,unction.

    $ynta+=

    DROP 8,NCTION function_name;E+ampl=

    DROP 8,NCTION get_sal;

    +ll t3e $rivile"es "ranted on a ,unction are revoed 3en t3e ,unction is dro$$ed.

    (3e CREATE OR REPLACEsnta5 is e@uivalent to dro$$in" a ,unction and

    recreatin" it. Privile"es "ranted on t3e ,unction remain t3e same 3en t3is snta5 is

    used.

    Comparing Procedures and Functions

    Procedures "unctions

    *5ecute as a PL2SQL statement Invoe as $art o, an e5$ression

    Do not contain RET,RNclause in t3e 3eader Must contain a RET,RNclause in t3e 3eader

    !an return none? one? or man values Must return a sin"le value

    !an contain a RET,RNstatement Must contain at least one RET,RNstatement

    Managing Stored PL/SQL Obects

    Stored Information Description Access Method

    code !om$iled o08ect code &ot accessi0le

    !om$ile errors PL2SQL snta5 errors (3e,$ER7ERROR$data dictionar vie

    iSQLHPlus: $/O: ERROR$command

    un>time de0u"

    in,ormation

    User>s$eci,ied de0u"

    varia0les and messa"es

    (3e DB2$7O,TP,TOracle>su$$lied

    $aca"e

    USER_OBJECTSData Dictionary !iew

    Column Column Description

    OB*!(9&+M* &ame o, t3e o08ect

    OBQECT7ID Internal identi,ier ,or t3e o08ect

    OBQECT7TPE ($e o, o08ect? ,or e5am$le? TABLE. PROCED,RE. 8,NCTION.

    PACAGE. PACAGE. BOD. TRIGGER

    CREATED Date 3en t3e o08ect as created

    1'

  • 8/13/2019 Unit 5 PLSQL Fundamentals - Part II

    21/63

    DBMS Unit 4 Procedural SQL Fundamentals: Part II

    LA$T7DDL7TI2E Date 3en t3e o08ect as last modi,ied

    TI2E$TA2P Date and time 3en t3e o08ect as last recom$iled

    $TAT,$ 3ALIDor IN3ALID

    USER_SOURCEData Dictionary !iew

    Column Column Description

    &+M* &ame o, t3e o08ect

    TPE ($e o, o08ect? ,or e5am$le? PO!*DU*?

    LINE FU&!(IO&? P+!N+

  • 8/13/2019 Unit 5 PLSQL Fundamentals - Part II

    22/63

    DBMS Unit 4 Procedural SQL Fundamentals: Part II

    (3e snta5 o, $/O: ERROR$is:

    $/O: ERROR$ >8,NCTION#PROCED,RE#PACAGE#PACAGE BOD#

    TRIGGER#3IE:S >*hma@?nam?

    Summary

    ame Data Dictionary !ie" or

    Command

    Description

    US*9OB*!(S Data dictionar vie Provides "eneral in,ormation a0out t3e

    o08ect

    ,$ER7$O,RCE Data dictionar vie Provides t3e te5t o, t3e o08ect? t3at is? t3e

    PL2SQL 0loc

    DE$CRIBE iSQLHPlus command Provides t3e declaration o, t3e o08ect,$ER7ERROR$ Data dictionar vie S3os com$ilation errors

    $/O: ERROR$ iSQLHPlus command S3os com$ilation errors? $er $rocedure or

    ,unction

    DB2$7O,TP,T Oracle>su$$lied $aca"e Provides user>s$eci,ied de0u""in"? "ivin"

    varia0le values and messa"es

    GRANT iSQL command Provides t3e securit $rivile"es ,or t3e

    oner 3o creates t3e $rocedure and t3e

    user 3o runs it? ena0lin" t3em to $er,orm

    t3eir res$ective o$erations

    Package

    Overview o" Packages

  • 8/13/2019 Unit 5 PLSQL Fundamentals - Part II

    23/63

    DBMS Unit 4 Procedural SQL Fundamentals: Part II

    com$iled? t3e contents can 0e s3ared 0 man a$$lications.

    +llo t3e Oracle server to read multi$le o08ects into memor at once

    Later calls to constructs in t3e same $aca"e re@uire no dis in$ut2out$ut I2O.

    !om$onents o, a Paca"e

    Cou create a $aca"e in to $arts: ,irst t3e $aca"e s$eci,ication? and t3en t3e

    $aca"e 0od.

    Pu0lic $aca"e constructs are t3ose t3at are declared in t3e $aca"e

    s$eci,ication and de,ined in t3e $aca"e 0od.

    Private $aca"e constructs are t3ose t3at are de,ined solel it3in t3e $aca"e

    0od.

    Scope o" the Construct Description Placement within the Package

    Pu0lic !an 0e re,erenced ,rom anOracle server environment

    Declared it3in t3e $aca"es$eci,ication and ma 0e de,ined

    it3in t3e $aca"e 0od

    Private !an 0e re,erenced onl 0

    ot3er constructs 3ic3 are $art

    o, t3e same $aca"e

    Declared and de,ined it3in t3e

    $aca"e 0od

    &ote: (3e Oracle server stores t3e s$eci,ication and 0od o, a $aca"e se$aratel in

    t3e data0ase. (3is ena0les ou to c3an"e t3e de,inition o, a $ro"ram construct in t3e

    $aca"e 0od it3out causin" t3e Oracle server to invalidate ot3er sc3ema o08ects

    /1

  • 8/13/2019 Unit 5 PLSQL Fundamentals - Part II

    24/63

    DBMS Unit 4 Procedural SQL Fundamentals: Part II

    t3at call or re,erence t3e $ro"ram construct.

    e,erencin" Paca"e O08ects

    !isi#ility o" the Construct Description

    Local + varia0le de,ined it3in a su0$ro"ram t3at is not visi0le toe5ternal users. Private local to t3e $aca"e varia0le: Cou can

    de,ine varia0les in a $aca"e 0od. Onl ot3er o08ects in t3e

    same $aca"e can access t3ese varia0les. (3e are not visi0le to

    an su0$ro"rams or o08ects outside o, t3e $aca"e.

  • 8/13/2019 Unit 5 PLSQL Fundamentals - Part II

    25/63

    DBMS Unit 4 Procedural SQL Fundamentals: Part II

    InitialiGe a varia0le it3 a constant value or ,ormula it3in t3e declaration? i,

    re@uiredA ot3erise? t3e varia0le is initialiGed im$licitl to N,LL.

    Declarin" Pu0lic !onstructs

    In t3e $aca"e s$eci,ication? ou declare $u0lic varia0les? $u0lic $rocedures? and

    $u0lic ,unctions.

    (3e $u0lic $rocedures or ,unctions are routines t3at can 0e invoed re$eatedl 0

    ot3er constructs in t3e same $aca"e or ,rom outside t3e $aca"e.

    For e5am$le 0elo? G7CO22is a $u0lic "lo0al varia0le? and RE$ET7CO22is a

    $u0lic $rocedure t3at is im$lemented in t3e $aca"e 0od..

    CREATE OR REPLACE PACAGE omm7paa' I$

    '7omm N,2BER = 1@01; ""initialid to 1@01

    PROCED,RE r*t7omm

    (p7omm IN N,2BER);

    END omm7paa';

    %reating te Package Body

    Snta5:

    CREATE >OR REPLACE? PACAGE BODpackage_name

    I$#A$

    priate type and item declarations

    subprogram bodies

    END paa'7nam;

    In t3e snta5:

    Parameter Description

    $aca"e9name Is t3e name o, t3e $aca"e

    $rivate t$e and item

    declarations

    Declares varia0les? constants? cursors? e5ce$tions? or t$es

    su0$ro"ram 0odies De,ines t3e PL2SQL su0$ro"rams? $u0lic and $rivate

    De,ine all $u0lic and $rivate $rocedures and ,unctions in t3e $aca"e 0od.

    (3e REPLACEo$tion dro$s and recreates t3e $aca"e 0od. S$eci, t3e t3e o$tion

    3en t3e $aca"e 0od alread e5ists.

    Identi,iers de,ined onl in t3e $aca"e 0od are $rivate constructs. (3ese are not

    visi0le outside t3e $aca"e 0od.

    +ll $rivate constructs must 0e declared 0e,ore t3e are used in t3e $u0lic constructs.

    !reate a Paca"e Bod *5am$le comm.9$ac.s@l

    CREATE OR REPLACE PACAGE BOD omm7paa'

    I$

    /#

  • 8/13/2019 Unit 5 PLSQL Fundamentals - Part II

    26/63

    DBMS Unit 4 Procedural SQL Fundamentals: Part II

    8,NCTION alidat7omm (p7omm IN N,2BER)

    RET,RN BOOLEAN

    I$

    7ma+7omm N,2BER;BEGIN

    $ELECT 2AX(ommi**ion7pt)

    INTO 7ma+7omm

    8RO2 mploy*;

    I8 p7omm ! 7ma+7omm T/EN RET,RN(8AL$E);

    EL$E RET,RN(TR,E);

    END I8;

    END alidat7omm;

    PROCED,RE r*t7omm (p7omm IN N,2BER)

    I$

    BEGIN

    I8 alidat7omm(p7omm) T/EN

    '7omm=p7omm; ""r*t 'lo&al aria&l

    EL$E

    RAI$E7APPLICATION7ERROR("-1-01.4Inalid ommi**ion4);

    END I8;

    END r*t7omm;

    END omm7paa';

    /4

  • 8/13/2019 Unit 5 PLSQL Fundamentals - Part II

    27/63

    DBMS Unit 4 Procedural SQL Fundamentals: Part II

    1 is a $u0lic "lo0al varia0le

    / is a $u0lic $rocedure

    # is a $rivate ,unction

    Invoking Package Constructs

    *5am$le 1: Invoe a ,unction ,rom a $rocedure it3in t3e same $aca"e.

    CREATE OR REPLACE PACAGE BOD omm7paa' I$

    @ @ @

    PROCED,RE r*t7omm

    (p7omm IN N,2BER)

    I$

    BEGIN

    I8 alidat7omm(p7omm) T/EN

    '7omm = p7omm;

    EL$E

    RAI$E7APPLICATION7ERROR("-1-01. 4Inalid ommi**ion4);

    END I8;

    END r*t7omm;

    END omm7paa';

    !all t3e 3ALIDATE7CO22,unction ,rom t3e RE$ET7CO22$rocedure. Bot3

    su0$ro"rams are in t3e CO227PACAGE$aca"e.

    *5am$le /: Invoe a $aca"e $rocedure ,rom iSQLHPlus.

    EXEC,TE omm7paa'@r*t7omm(1@0J)

    !all t3e RE$ET7CO22$rocedure ,rom iSQLHPlus? main" t3e $revailin"

    commission -.1% ,or t3e user session.

    *5am$le #: Invoe a $aca"e $rocedure in a di,,erent sc3ema.

    EXEC,TE *ott@omm7paa'@r*t7omm(1@0J)

    !all t3e RE$ET7CO22$rocedure t3at is located in t3e $COTTsc3ema ,rom

    iSQLHPlus? main" t3e $revailin" commission -.1% ,or t3e user session.

    *5am$le 4: Invoe a $aca"e $rocedure in a remote data0ase.

    EXEC,TE omm7paa'@r*t7ommUny(1@0J)

    !all t3e RE$ET7CO22$rocedure t3at is located in a remote data0ase t3at is

    determined 0 t3e data0ase lin named N,rom iSQLHPlus? main" t3e $revailin"

    commission -.1% ,or t3e user session.

    Declaring a Bodiless Package

    *5am$le: a $aca"e s$eci,ication containin" several conversion rates is de,ined. +ll t3e

    /%

  • 8/13/2019 Unit 5 PLSQL Fundamentals - Part II

    28/63

    DBMS Unit 4 Procedural SQL Fundamentals: Part II

    "lo0al identi,iers are declared as constants.

    CREATE OR REPLACE PACAGE 'lo&al7on*t* I$

    mil7-7ilo CON$TANT N,2BER = 0@H19;

    ilo7-7mil CON$TANT N,2BER = 1@H-0;yard7-7mtr CON$TANT N,2BER = 1@0;

    mtr7-7yard CON$TANT N,2BER = 0@19H;

    END 'lo&al7on*t*;

    EXEC,TE DB2$7O,TP,T@P,T7LINE(4-1 mil* 4##-1F

    'lo&al7on*t*@mil7-7ilo##4 m4)

    Cou can declare $u0lic "lo0al varia0les t3at e5ist ,or t3e duration o, t3e user

    session.

    Cou can create a $aca"e s$eci,ication t3at does not need a $aca"e 0od.

    + $aca"e 0od is not re@uired to su$$ort t3is $aca"e s$eci,ication 0ecause

    im$lementation details are not re@uired ,or an o, t3e constructs o, t3e $aca"e

    s$eci,ication.

    e,erencin" a Pu0lic ;aria0le ,rom a Stand>+lone Procedure

    *5am$le:

    CREATE OR REPLACE PROCED,RE mtr7to7yard

    (p7mtr IN N,2BER. p7yard O,T N,2BER)

    I$

    BEGIN

    p7yard = p7mtr F 'lo&al7on*t*@mtr7-7yard;

    END mtr7to7yard;

    3ARIABLE yard N,2BER

    EXEC,TE mtr7to7yard (0. =yard)

    PRINT yard

    Use t3e 2ETER7TO7ARD$rocedure to convert meters to ards? usin" t3e

    conversion rate $aca"ed in GLOBAL7CON$T$.

    3en ou re,erence a varia0le? cursor? constant? or e5ce$tion ,rom outside t3e

    $aca"e? ou must @uali, its name it3 t3e name o, t3e $aca"e.

    $emoving Packages

    (o remove t3e $aca"e s$eci,ication and t3e 0od? use t3e ,olloin" snta5:

    DROP PACAGE paa'7nam;

    (o remove t3e $aca"e 0od? use t3e ,olloin" snta5:

    /6

  • 8/13/2019 Unit 5 PLSQL Fundamentals - Part II

    29/63

    DBMS Unit 4 Procedural SQL Fundamentals: Part II

    DROP PACAGE BOD paa'7nam;

    %uidelines "or Developing Packages

    !onstruct $aca"es ,or "eneral use. De,ine t3e $aca"e s$eci,ication 0e,ore t3e 0od.

    (3e $aca"e s$eci,ication s3ould contain onl t3ose constructs t3at ou ant to 0e

    $u0lic.

    Place items in t3e declaration $art o, t3e $aca"e 0od 3en ou must maintain t3em

    t3rou"3out a session or across transactions.

    !3an"es to t3e $aca"e s$eci,ication re@uire recom$ilation o, eac3 re,erencin"

    su0$ro"ram.

    (3e $aca"e s$eci,ication s3ould contain as ,e constructs as $ossi0le.

    Overload: Local or $aca"ed su0$ro"rams can 0e overloaded. Cou cannot overload

    stand>alone su0$ro"rams.

    *na0les ou to use t3e same name ,or di,,erent su0$ro"rams inside a PL2SQL 0loc?

    a su0$ro"ram? or a $aca"e

    e@uires t3e ,ormal $arameters o, t3e su0$ro"rams to di,,er in num0er? order? or

    data t$e ,amil

    *na0les ou to 0uild more ,le5i0ilit 0ecause a user or a$$lication is not restricted

    0 t3e s$eci,ic data t$e or num0er o, ,ormal $arameters

    Cou must declare identi,iers 0e,ore re,erencin" t3em? i.e.? PL2SQL does not allo

    ,orard re,erences. (3ere,ore? a su0$ro"ram must 0e declared 0e,ore callin" it.

    !ommand Summar:

    Command #ask

    CREATE >OR REPLACE? PACAGE !reate or modi, an e5istin" $aca"e s$eci,ication

    CREATE >OR REPLACE? PACAGE

    BOD

    !reate or modi, an e5istin" $aca"e 0od

    DROP PACAGE emove 0ot3 t3e $aca"e s$eci,ication and t3e

    $aca"e 0od

    DROP PACAGE BOD emove t3e $aca"e 0od onl

    Oracle Supplied Packages

    rite dnamic SQL statements usin" DB2$7$5Land EXEC,TE I22EDIATE

    SQL statement contains varia0les t3at can c3an"e durin" runtime

    SQL statement is it3 $lace3olders and is stored as a c3aracter strin"

    +$$lication o, some Oracle server>su$$lied $aca"es:

    DB2$7DDL

    /7

  • 8/13/2019 Unit 5 PLSQL Fundamentals - Part II

    30/63

    DBMS Unit 4 Procedural SQL Fundamentals: Part II

    DB2$7QOB

    DB2$7O,TP,T

    ,TL78ILE

    ,TL7/TTP and ,TL7TCP

    Ste$s to Process SQL Statements +ll SQL statements 3ave to "o t3rou"3 various

    sta"es. Some sta"es ma 0e si$$ed.

    Parse: *ver SQL statement must 0e $arsed. Parsin" t3e statement includes

    c3ecin" t3e statementEs snta5 and validatin" t3e statement? ensurin" t3at all

    re,erences to o08ects are correct? and ensurin" t3at t3e relevant $rivile"es to t3ose

    o08ects e5ist.

    Bind: +,ter $arsin"? t3e Oracle server nos t3e meanin" o, t3e Oracle statement

    0ut still ma not 3ave enou"3 in,ormation to e5ecute t3e statement. (3e Oracle

    server ma need values ,or an 0ind varia0le in t3e statement. (3e $rocess o,

    o0tainin" t3ese values is called 0indin" varia0les.

    *5ecute: +t t3is $oint? t3e Oracle server 3as all necessar in,ormation and resources?

    and t3e statement is e5ecuted.

    Fetc3: In t3e ,etc3 sta"e? ros are selected and ordered i, re@uested 0 t3e @uer?

    and eac3 successive ,etc3 retrieves anot3er ro o, t3e result? until t3e last ro 3as

    0een ,etc3ed. Cou can ,etc3 @ueries? 0ut not t3e DML statements.

    &sing te DBMS_SQLPackage

    (3e DB2$7$5L$aca"e is used to rite dnamic SQL in stored $rocedures and to $arse

    DDL statements.

    $unction or Procedure Description

    OP*&9!USO O$ens a ne cursor and assi"ns a cursor ID num0er

    PAR$E Parses t3e DDL or DML statement: t3at is? c3ecs t3e statements

    snta5 and associates it it3 t3e o$ened cursor DDL statements

    are immediatel e5ecuted 3en $arsed

    BIND73ARIABLE Binds t3e "iven value to t3e varia0le identi,ied 0 its name in t3e$arsed statement in t3e "iven cursor

    EXEC,TE *5ecutes t3e SQL statement and returns t3e num0er o, ros

    $rocessed

    8ETC/7RO:$ etrieves a ro ,or t3e s$eci,ied cursor ,or multi$le ros? call in a

    loo$

    CLO$E7C,R$OR !loses t3e s$eci,ied cursor

    *5am$le: (3e ta0le name is $assed into t3e DELETE7ALL7RO:$$rocedure 0 usin" an

    I& $arameter. (3e $rocedure uses dnamic SQL to delete ros ,rom t3e s$eci,ied ta0le.

    /'

  • 8/13/2019 Unit 5 PLSQL Fundamentals - Part II

    31/63

    DBMS Unit 4 Procedural SQL Fundamentals: Part II

    (3e num0ers o, ros t3at are deleted as a result o, t3e success,ul e5ecution o, t3e

    dnamic SQL are $assed to t3e callin" environment t3rou"3 an O,T$arameter.

    CREATE OR REPLACE PROCED,RE dlt7all7roM*

    (p7ta&7nam IN 3ARC/AR-. p7roM*7dl O,T N,2BER)I$

    %r*or7nam INTEGER;

    BEGIN

    %r*or7nam = DB2$7$5L@OPEN7C,R$OR;

    DB2$7$5L@PAR$E(%r*or7nam. 4DELETE 8RO2 4##p7ta&7nam.

    DB2$7$5L@NATI3E );

    p7roM*7dl = DB2$7$5L@EXEC,TE (%r*or7nam);

    DB2$7$5L@CLO$E7C,R$OR(%r*or7nam);

    END;

    Use dnamic SQL to delete ros

    3ARIABLE dltd N,2BER

    EXEC,TE dlt7all7roM*(4mploy*4. =dltd)

    PRINT dltd

    Use OPEN7C,R$ORto esta0lis3 an area in memor to $rocess a SQL

    statement.

    Use PAR$Eto esta0lis3 t3e validit o, t3e SQL statement.

    Use t3e EXEC,TE,unction to run t3e SQL statement. (3is ,unction returns t3e

    num0er o, ro $rocessed.

    Use CLO$E7C,R$ORto close t3e cursor.

    Use t3e EXEC,TE I22EDIATEstatement ,or native dnamic SQL it3 0etter

    $er,ormance.

    $ynta+=

    EXEC,TE I22EDIATE dynami7*trin'

    >INTO din7aria&l

    >. din7aria&l? @@@ # rordS?

    >,$ING >IN#O,T#IN O,T? &ind7ar'%mnt

    >. >IN#O,T#IN O,T? &ind7ar'%mnt? @@@ ?;

    De,inition:

    Parameter Description

    dnamic9strin" + strin" e5$ression t3at re$resents a dnamic SQL statement it3out

    terminator or a PL2SQL 0loc it3 terminator

    din7aria&l+ varia0le t3at stores t3e selected column value record + user>de,ined

    or RO:TPErecord t3at stores a selected ro

    /)

  • 8/13/2019 Unit 5 PLSQL Fundamentals - Part II

    32/63

    DBMS Unit 4 Procedural SQL Fundamentals: Part II

    &ind7ar'%mnt +n e5$ression 3ose value is $assed to t3e dnamic SQL statement or

    PL2SQL 0loc

    INTOis used ,or sin"le>ro @ueries and s$eci,ies t3e varia0les or records into

    3ic3 column values are retrieved. But? ou must use OPEN"8OR? 8ETC/? andCLO$E,or a multiro @uer.

    ,$INGis used to 3old all 0ind ar"uments. (3e de,ault $arameter mode is IN.

    *5am$le: Dnamic SQL Usin" EXEC,TE I22EDIATE

    CREATE PROCED,RE dl7roM*

    (p7ta&l7nam IN 3ARC/AR-.

    p7roM*7dld O,T N,2BER)

    I$

    BEGIN

    EXEC,TE I22EDIATE 4dlt rom 4##p7ta&l7nam;

    p7roM*7dld = $5LRO:CO,NT;

    END;

    Dnamic SQL Usin" EXEC,TE I22EDIATE

    3ARIABLE dltd N,2BER

    EXEC,TE dl7roM*(4t*t7mploy*4.=dltd)

    PRINT dltd

    &sing te DB'S(DDL Package

    (3is $aca"e $rovides access to some SQL DDL statements? 3ic3 ou can use in

    PL2SQL $ro"rams.

    DB2$7DDLis not alloed in tri""ers? in $rocedures called ,rom Forms Builder? or in

    remote sessions.

    (3is $aca"e runs it3 t3e $rivile"es o, callin" user? rat3er t3an t3e $aca"e oner $$.

    Includes some $rocedures:

    ALTER7CO2PILE (o&6t7typ. oMnr. o&6t7nam)

    E+ampl=

    DB2$7DDL@ALTER7CO2PILE(4PROCED,RE4.4A7,$ER4.45,ER7E2P4)

    ANALVE7OBQECT (o&6t7typ. oMnr. nam. mthod)

    E+ampl=

    DB2$7DDL@ANALVE7OBQECT(4TABLE4.4A7,$ER4.4QOB$4.4CO2P,TE4)

    &sing DB'S()OB for Sceduling

    DBMS9OB *na0les t3e sc3edulin" and e5ecution o, PL2SQL $ro"rams:

    Su0mittin" 8o0s

    #-

  • 8/13/2019 Unit 5 PLSQL Fundamentals - Part II

    33/63

    DBMS Unit 4 Procedural SQL Fundamentals: Part II

    *5ecutin" 8o0s

    !3an"in" e5ecution $arameters o, 8o0s

    emovin" 8o0s

    Sus$endin" o0s

    +vaila0le su0$ro"rams:

    Subpro%ram Description

    SUBMI( Su0mits a 8o0 to t3e 8o0 @ueue

    RE2O3E emoves a s$eci,ied 8o0 ,rom t3e 8o0 @ueue

    C/ANGE +lters a s$eci,ied 8o0 t3at 3as alread 0een su0mitted to t3e 8o0 @ueue ou

    can alter t3e 8o0 descri$tion? t3e time at 3ic3 t3e 8o0 ill 0e run? or t3e

    interval 0eteen e5ecutions o, t3e 8o0

    :/AT +lters t3e 8o0 descri$tion ,or a s$eci,ied 8o0

    NEXT7DATE +lters t3e ne5t e5ecution time ,or a s$eci,ied 8o0

    INTER3AL +lters t3e interval 0eteen e5ecutions ,or a s$eci,ied 8o0

    BROEN Disa0les 8o0 e5ecution i, a 8o0 is mared as 0roen? t3e Oracle server does

    not attem$t to e5ecute it

    R,N Forces a s$eci,ied 8o0 to run

    DB2$7QOB@$,B2IT. (3e $rocedure adds a ne 8o0 to t3e 8o0 @ueue. It acce$ts ,ive

    $arameters and returns t3e num0er o, a 8o0 su0mitted t3rou"3 t3e OU( $arameter OB.

    Parameter Mode #ype Default Description

    QOB O,T BI&+C9I&(*

  • 8/13/2019 Unit 5 PLSQL Fundamentals - Part II

    34/63

    DBMS Unit 4 Procedural SQL Fundamentals: Part II

    );

    CO22IT;

    END;

    PI&( 8o0no

    (3e 0loc o, code su0mits t3e ADD7DEPT$rocedure o, t3e O3ER7PAC

    $aca"e to t3e 8o0 @ueue.

    (3e 8o0 num0er is returned t3rou"3 t3e QOB$arameter.

    (3e :/AT$arameter must 0e enclosed in sin"le @uotation mars and must

    include a semicolon at t3e end o, t3e te5t strin".

    (3e transactions in t3e su0mitted 8o0 are not committed until eit3er CO22IT

    is issued? or DB2$7QOB@R,Nis e5ecuted to run t3e 8o0. CO22ITin t3e slide

    commits t3e transaction.

    !3an"in" o0 !3aracteristics

    DB2$7QOB@C/ANGE: !3an"es t3e :/AT? NEXT7DATE? and INTER3AL

    $arameters

    DB2$7QOB@INTER3AL: !3an"es t3e INTER3AL$arameter

    DB2$7QOB@NEXT7DATE: !3an"es t3e ne5t e5ecution date

    DB2$7QOB@:/AT: !3an"es t3e =+( $arameter

    *5am$le (3e ,olloin" code c3an"es 8o0 num0er 1 to e5ecute on t3e ,olloin"

    da at 6:-- a.m. and ever ,our ours a,ter t3at.

    BEGIN

    DB2$7QOB@C/ANGE(0. N,LL. TR,NC($$DATEK0)KH-.

    W$$DATEK-4);

    END;

    &ote: *ac3 o, t3ese $rocedures can 0e e5ecuted on 8o0s oned 0 t3e

    username to 3ic3 t3e session s connected. I, t3e $arameter 3at? ne5t9date?

    or interval is &ULL? t3en t3e last values assi"ned to t3ose $arameters are used.

    unnin"? emovin"? and Breain" o0s

    DB2$7QOB@R,N: uns a su0mitted 8o0 immediatel? ,or e5am$le? $ass t3e 8o0

    num0er t3at ou ant to run immediatel to t3e $rocedure

    EXEC,TE DB2$7QOB@R,N(0)

    DB2$7QOB@RE2O3E: emoves a su0mitted 8o0 ,rom t3e 8o0 @ueue? ,or e5am$le?

    Pass t3e 8o0 num0er t3at ou ant to remove ,rom t3e @ueue to t3e $rocedure.

    EXEC,TE DB2$7QOB@RE2O3E(0)

    DB2$7QOB@BROEN: Mars a su0mitted 8o0 as 0roen? and a 0roen 8o0 ill not

    run? ,or e5am$le?

    #/

  • 8/13/2019 Unit 5 PLSQL Fundamentals - Part II

    35/63

    DBMS Unit 4 Procedural SQL Fundamentals: Part II

    EXEC,TE DB2$7QOB@BROEN(0. TR,E)

    ;iein" In,ormation on Su0mitted o0s

    Use t3e DBA7QOB$dictionar vie to see t3e status o, su0mitted 8o0s.

    $ELECT 6o&. lo'7%*r. n+t7dat. n+t7*. &ron. Mhat8RO2 DBA7QOB$;

    Use t3e DBA7QOB$7R,NNINGdictionar vie to dis$la 8o0s t3at are currentl

    runnin".

    &sing te DBMS_OUTPUTPackage

    (3e DB2$7O,TP,T$aca"e out$uts values and messa"es ,rom an PL2SQL 0loc.

    $unction or Procedure Description

    PU( +$$ends te5t ,rom t3e $rocedure to t3e current line o, t3e line out$ut

    0u,,er

    NE:7LINE Places an end9o,9line marer in t3e out$ut 0u,,er

    P,T7LINE !om0ines t3e action o, P,Tand NE:7LINE

    GET7LINE etrieves t3e current line ,rom t3e out$ut 0u,,er into t3e $rocedure

    GET7LINE$ etrieves an arra o, lines ,rom t3e out$ut 0u,,er into t3e $rocedure

    ENABLEDI$ABLE *na0les or disa0les calls to t3e DB2$7O,TP,T$rocedures

    UTL_FILEPackage

    (3e Procedures and Functions it3in ,TL78ILEPaca"e:

    $unction or Procedure Description

    FOP*& + ,unction t3at o$ens a ,ile ,or in$ut or out$ut and returns a ,ile

    3andle used in su0se@uent I2O o$erations

    I$7OPEN + ,unction t3at returns a Boolean value 3enever a ,ile 3andle re,ers

    to an o$en ,ile

  • 8/13/2019 Unit 5 PLSQL Fundamentals - Part II

    36/63

    DBMS Unit 4 Procedural SQL Fundamentals: Part II

    NE:7LINE Procedure t3at terminates a line in an out$ut ,ile

    88L,$/ Procedure t3at rites all data 0u,,ered in memor to a ,ile

    8CLO$E Procedure t3at closes an o$ened ,ile

    8CLO$E7ALL Procedure t3at closes all o$ened ,ile 3andles ,or t3e session &ote: (3e ma5imum siGe o, an in$ut record is 1?-/# 0tes unless ou s$eci, a

    lar"er siGe in t3e overloaded version o, 8OPEN.

    *5ce$tions S$eci,ic to t3e ,TL78ILEPaca"e: (3e ,TL78ILE$aca"e declares

    se&ene5ce$tions t3at are raised to indicate an error condition in t3e o$eratin" sstem ,ile

    $rocessin".

    '(ception ame Description

    IN3ALID7PAT/ (3e ,ile location or ,ilename as invalid.

    IN3ALID72ODE (3e OP*&9MOD* $arameter in FOP*& as invalid.

    IN3ALID78ILE/ANDLE (3e ,ile 3andle as invalid.

    IN3ALID7OPERATION (3e ,ile could not 0e o$ened or o$erated on as re@uested.

    READ7ERROR +n o$eratin" sstem error occurred durin" t3e read o$eration.

    :RITE7ERROR +n o$eratin" sstem error occurred durin" t3e rite o$eration.

    INTERNAL7ERROR +n uns$eci,ied error occurred in PL2SQL.

    &ote: (3ese e5ce$tions must 0e $re,aced it3 t3e $aca"e name. ,TL78ILE

    $rocedures can also raise $rede,ined PL2SQL e5ce$tions suc3 as

    NO7DATA78O,NDor 3AL,E7ERROR.

    (3e 8OPENand I$7OPENFunctions

    (3e Snta5:

    8,NCTION 8OPEN

    (loation IN 3ARC/AR-.

    ilnam IN 3ARC/AR-.

    opn7mod IN 3ARC/AR-)

    RET,RN ,TL78ILE@8ILE7TPE;

    8,NCTION I$7OPEN

    (il7handl IN 8ILE7TPE)

    RET,RN BOOLEAN;

    Snta5 De,initions o, 8OPEN

    location Is t3e o$eratin">sstem>s$eci,ic strin" t3at s$eci,ies t3e director or area in

    3ic3 to o$en t3e ,ile

    filename Is t3e name o, t3e ,ile? includin" t3e e5tension? it3out an $at3in"

    in,ormation

    open_mode Is strin" t3at s$eci,ies 3o t3e ,ile is to 0e o$enedA Su$$orted values are:

    #4

  • 8/13/2019 Unit 5 PLSQL Fundamentals - Part II

    37/63

    DBMS Unit 4 Procedural SQL Fundamentals: Part II

    r read te5t use GET7LINE

    rite te5t P,T? P,T7LINE? NE:7LINE? P,T8? 88L,$/

    a a$$end te5t P,T? P,T7LINE? NE:7LINE? P,T8? 88L,$/

    (3e ,unction I$7OPENtests a ,ile 3andle to see i, it identi,ies an o$ened ,ile. It

    returns a Boolean value indicatin" 3et3er t3e ,ile 3as 0een o$ened 0ut not et

    closed.

    &ote: For t3e ,ull snta5? re,er to Oracle)i Su$$lied PL2SQL Paca"es and ($es

    e,erence.

    *5am$le o, Usin" ,TL78ILE sal9status.s@l: creates a re$ort o, em$loees ,or eac3

    de$artment and t3eir salaries.

    CREATE OR REPLACE PROCED,RE *al7*tat%*

    (p7ildir IN 3ARC/AR-. p7ilnam IN 3ARC/AR-)

    I$

    7ilhandl ,TL78ILE@8ILE7TPE;

    C,R$OR mp7ino I$

    $ELECT la*t7nam. *alary. dpartmnt7id

    8RO2 mploy*

    ORDER B dpartmnt7id;

    7nMdptno mploy*@dpartmnt7idTPE;

    7olddptno mploy*@dpartmnt7idTPE = 1;

    BEGIN

    7ilhandl = ,TL78ILE@8OPEN (p7ildir. p7ilnam.4M4);

    ,TL78ILE@P,T8 (7ilhandl.4$ALAR REPORT= GENERATED ON

    *n4. $$DATE);

    ,TL78ILE@NE:7LINE (7ilhandl);

    8OR 7mp7r IN mp7ino LOOP

    7nMdptno = 7mp7r@dpartmnt7id;

    I8 7nMdptno

    ,TL78ILE@P,T8 (7ilhandl. 4DEPART2ENT= *n4.7mp7r@dpartmnt7id);

    END I8;

    ,TL78ILE@P,T8 (7ilhandl.4 E2PLOEE= * arn*= *n4.

    7mp7r@la*t7nam. 7mp7r@*alary);

    7olddptno = 7nMdptno;

    END LOOP;

    ,TL78ILE@P,T7LINE (7ilhandl. 4FFF END O8 REPORT FFF4);

    ,TL78ILE@8CLO$E (7ilhandl);

    #%

  • 8/13/2019 Unit 5 PLSQL Fundamentals - Part II

    38/63

    DBMS Unit 4 Procedural SQL Fundamentals: Part II

    EXCEPTION

    :/EN ,TL78ILE@IN3ALID78ILE/ANDLE T/EN

    RAI$E7APPLICATION7ERROR ("-1110. 4Inalid 8il@4);

    :/EN ,TL78ILE@:RITE7ERROR T/ENRAI$E7APPLICATION7ERROR ("-111-. 4,na&l to Mrit to

    il4);

    END *al7*tat%*;

    (3is in,ormation is sent to a te5t ,ile 0 usin" t3e ,TL78ILE$rocedures and

    ,unctions.

    (3e varia0le v9,ile3andle uses a t$e de,ined in t3e ,TL78ILE$aca"e. (3is

    $aca"e>de,ined t$e is a record it3 a ,ield called ID o, t3e BINAR7INTEGER

    datat$e.

    TPE il7typ I$ RECORD (id BINAR7INTEGER);

    (3e contents o, ,ile9t$e are $rivate to t3e ,TL78ILE$aca"e. Users o, t3e

    $aca"e s3ould not re,erence or c3an"e com$onents o, t3is record.

    (3e names o, t3e te5t ,ile and t3e location ,or t3e te5t ,ile are $rovided as

    $arameters to t3e $ro"ram.

    EXEC,TE *al7*tat%*(4C=,TL78ILE4. 4$AL7RPT@TXT4)

    &ote: (3e ,ile location s3on in t3e a0ove e5am$le is de,ined as value o,

    ,TL78ILE7DIRin t3e init&ora,ile as ,ollos:

    ,TL78ILE7DIR C=,TL78ILE@

    3en readin" a com$lete ,ile in a loo$? ou need to e5it t3e loo$ usin" t3e

    NO7DATA78O,NDe5ce$tion. ,TL78ILEout$ut is sent snc3ronousl.

    DB2$7O,TP,T$rocedures do not $roduce out$ut until t3e $rocedure is com$leted.

    Out$ut: (3e out$ut ,or t3is re$ort in t3e sal9r$t.t5t ,ile is as ,ollos:

    $ALAR REPORT= GENERATED ON 1"2AR"10

    DEPART2ENT= 01

    E2PLOEE= :haln arn*= 11

    DEPART2ENT= -1

    E2PLOEE= /art*tin arn*= 09111

    E2PLOEE= 8ay arn*= H111

    DEPART2ENT= 91

    E2PLOEE= Raphaly arn*= 00111

    E2PLOEE= hoo arn*= 9011

    @@@

    DEPART2ENT= 011

    E2PLOEE= Grn&r' arn*= 0-111

    #6

  • 8/13/2019 Unit 5 PLSQL Fundamentals - Part II

    39/63

    DBMS Unit 4 Procedural SQL Fundamentals: Part II

    @@@

    DEPART2ENT= 001

    E2PLOEE= /i''in* arn*= 0-111

    E2PLOEE= Git arn*= 911E2PLOEE= Grant arn*= 111

    FFF END O8 REPORT FFF

    *e UTL_HTTPPackage

    (3e ,TL7/TTP$aca"e:

    *na0les =((P callouts ,rom PL2SQL and SQL to access data on t3e Internet

    !ontains t3e ,unctions RE5,E$Tand RE5,E$T7PIECE$3ic3 tae t3e UL o,

    a site as a $arameter? contact t3at site? and return t3e data o0tained ,rom t3at site

    e@uires a $ro5 $arameter to 0e s$eci,ied in t3e a0ove ,unctions? i, t3e client is

    0e3ind a ,ireall

    aises INIT78AILEDor RE5,E$T78AILEDe5ce$tions i, =((P call ,ails

    e$orts an =(ML error messa"e i, s$eci,ied UL is not accessi0le

    *5am$le: retrieve contents ,rom t3e UL .oracle.com.

    $ELECT ,TL7/TTP@RE5,E$T(4http=MMM@oral@om4. 4d%"

    pro+y@%*@oral@om4)

    8RO2 D,AL;

    (3e second $arameter to t3e ,unction indicates t3e $ro5 0ecause t3e client 0ein"

    tested is 0e3ind a ,ireall.

    (3e retrieved out$ut is in =(ML ,ormat.

    *5am$le: retrieves u$ to 1-- $ieces o, data? eac3 o, ma5imum /--- 0tes ,rom t3e

    UL. (3e num0er o, $ieces and t3e total len"t3 o, t3e data retrieved are $rinted.

    DECLARE

    + ,TL7/TTP@/T2L7PIECE$;

    BEGIN

    + = ,TL7/TTP@RE5,E$T7PIECE$(4http=MMM@[email protected].

    4d%"pro+y@%*@oral@om4);

    DB2$7O,TP,T@P,T7LINE(+@CO,NT ## 4 pi* Mr rtrid@4);

    DB2$7O,TP,T@P,T7LINE(4Mith total ln'th 4);

    I8 +@CO,NT < 0 T/EN DB2$7O,TP,T@P,T7LINE(414);

    EL$E DB2$7O,TP,T@P,T7LINE((-111F(+@CO,NT " 0))

    KLENGT/(+(+@CO,NT)));

    END I8;

    END;

    #7

  • 8/13/2019 Unit 5 PLSQL Fundamentals - Part II

    40/63

    DBMS Unit 4 Procedural SQL Fundamentals: Part II

    &sing te UTL_TCPPackage

    (3e ,TL7TCPPaca"e:

    *na0les PL2SQL a$$lications to communicate it3 e5ternal (!P2IP>0ased servers

    usin" (!P2IP

    !ontains ,unctions to o$en and close connections? to read or rite 0inar or te5t

    data to or ,rom a service on an o$en connection

    e@uires remote 3ost and $ort as ell as local 3ost and $ort as ar"uments to its

    ,unctions

    aises e5ce$tions i, t3e 0u,,er siGe is too small? 3en no more data is availa0le to

    read ,rom a connection? 3en a "eneric netor error occurs? or 3en 0ad

    ar"uments are $assed to a ,unction call

    (3e $aca"e contains ,unctions suc3 as:

    OPEN7CONNECTION: (3is ,unction o$ens a (!P2IP connection it3 t3e s$eci,ied

    remote and local 3ost and $ort details. (3e remote 3ost is t3e 3ost $rovidin" t3e

    service. (3e remote $ort is t3e $ort num0er on 3ic3 t3e service is listenin" ,or

    connections. (3e local 3ost and $ort num0ers re$resent t3ose o, t3e 3ost $rovidin"

    t3e service. (3e ,unction returns a connection o, PL2SQL record t$e.

    CLO$E7CONNECTION: (3is $rocedure closes an o$en (!P2IP connection. It taes

    t3e connection details o, a $reviousl o$ened connection as $arameter. (3e

    $rocedure !LOS*9+LL9!O&&*!(IO&S closes all o$en connections.

    READ7BINAR()TEXT()LINE(): (3is ,unction receives 0inar? te5t? or te5t

    line data ,rom a service on an o$en connection.

    :RITE7BINAR()TEXT()LINE(): (3is ,unction transmits 0inar? te5t? or

    te5t line messa"e to a service on an o$en connection.

    Oter Oracle+supplied packages

    Packa%e Description

    DBMS9+L*( Provides noti,ication o, data0ase eventsDB2$7APPLICATION

    7IN8O

    +llos a$$lication tools and a$$lication develo$ers to in,orm t3e

    data0ase o, t3e 3i"3 level o, actions t3e are currentl $er,ormin"

    DB2$7DE$CRIBE eturns a descri$tion o, t3e ar"uments ,or a stored $rocedure

    DB2$7LOC e@uests? converts? and releases userlocs? 3ic3 are mana"ed 0 t3e

    DBMS loc mana"ement services

    DB2$7$E$$ION Provides access to SQL session in,ormation

    DB2$7$/ARED7POOLNee$s o08ects in s3ared memor

    DB2$7TRAN$ACTION!ontrols lo"ical transactions and im$roves t3e $er,ormance o, s3ort?

    #'

  • 8/13/2019 Unit 5 PLSQL Fundamentals - Part II

    41/63

    DBMS Unit 4 Procedural SQL Fundamentals: Part II

    nondistri0uted transactions

    DB2$7,TILIT +nalGes o08ects in a $articular sc3ema? c3ecs 3et3er t3e server is

    runnin" in $arallel mode? and returns t3e time

    !+L*&D+ Provides calendar maintenance ,unctionsDB2$7ALERT Su$$orts asnc3ronous noti,ication o, data0ase events. Messa"es or

    alerts are sent on a !OMMI( command. Messa"e transmittal is one

    a? 0ut one sender can alert several receivers.

    DB2$7APPLICATION

    7IN8O

    Is used to re"ister an a$$lication name it3 t3e data0ase ,or auditin"

    or $er,ormance tracin" $ur$oses

    DB2$7A5 Provides messa"e @ueuin" as $art o, t3e Oracle serverA is used to add

    a messa"e o, a $rede,ined o08ect t$e onto a @ueue or de@ueue a

    messa"e

    DB2$7A5AD2 Is used to $er,orm administrative ,unctions on a @ueue or @ueue ta0le

    ,or messa"es o, a $rede,ined o08ect t$e

    DB2$7DDL Is used to em0ed t3e e@uivalent o, t3e SQL commands +L(*?

    !OMPIL*? and +&+LC* it3in our PL2SQL $ro"rams

    DBMS9D*BU< + PL2SQL +PI to t3e PL2SQL de0u""er laer?

    Pro0e? in t3e Oracle server

    DB$27DE8ER

    DB2$7DE8ER75,ER

    DB2$7DE8ER7$$

    Is used to 0uild and administer de,erred remote $rocedure calls use

    o, t3is ,eature re@uires t3e e$lication O$tion

    DB2$7DE$CRIBE Is used to descri0e t3e ar"uments o, a stored $rocedure

    DB2$7

    DI$TRIBR,TED7

    TR,$T7AD2IN

    Is used to maintain t3e (rusted Servers list? 3ic3 is used in

    con8unction it3 t3e list at t3e central aut3orit to determine 3et3er

    a $rivile"ed data0ase lin ,rom a $articular server can 0e acce$ted

    DB2$7/$ Is used to administer 3etero"eneous services 0 re"isterin" or

    dro$$in" distri0uted e5ternal $rocedures? remote li0raries? and non>

    Oracle sstems ou use d0ms93s to create or dro$ some

    initialiGation varia0les ,or non>Oracle sstems

    DB2$7/$7EXTPROC *na0les 3etero"eneous services to esta0lis3 securit ,or distri0uted

    e5ternal $rocedures

    DB2$7/$7

    PA$$T/RO,G/

    *na0les 3etero"eneous services to send $ass>t3rou"3 SQL statements

    to non>Oracle sstems

    DB2$7IOT Is used to sc3edule administrative $rocedures t3at ou ant

    $er,ormed at $eriodic intervalsA is also t3e inter,ace ,or t3e 8o0 @ueue

    DB2$7QOB Is used to sc3edule administrative $rocedures t3at ou ant

    $er,ormed at $eriodic intervals

    #)

  • 8/13/2019 Unit 5 PLSQL Fundamentals - Part II

    42/63

    DBMS Unit 4 Procedural SQL Fundamentals: Part II

    DB2$7LOB Provides "eneral $ur$ose routines ,or o$erations on Oracle lar"e

    o08ects LOBs data t$es: BLOB? !LOB read onl and BFIL*S

    read>onl

    DB2$7LOC Is used to re@uest? convert? and release locs t3rou"3 Oracle LocMana"ement services

    DB2$7LOG2NR Provides ,unctions to initialiGe and run t3e lo" reader

    DB2$7LOG2NR7D Queries t3e dictionar ta0les o, t3e current data0ase? and creates a

    te5t 0ased ,ile containin" t3eir contents

    DB2$7O88LINE7OG Provides $u0lic +PIs ,or o,,line instantiation o, master "rou$s

    DB2$7O88LINE7

    $NAP$/OT

    Provides $u0lic +PIs ,or o,,line instantiation o, sna$s3ots

    DB2$7OLAP Provides $rocedures ,or summaries? dimensions? and @uer rerites

    DB2$7ORACLE7

    TRACE7AGENT

    Provides client calla0le inter,aces to t3e Oracle (+!*

    instrumentation it3in t3e Oracle7 server

    DB2$7ORACLE7

    TRACE7,$ER

    Provides $u0lic access to t3e Oracle7 release server Oracle (+!*

    instrumentation ,or t3e callin" user

    DB2$7O,TP,T +ccumulates in,ormation in a 0u,,er so t3at it can 0e retrieved out

    later

    DB2$7PCLX,TIL Provides intra$artition $arallelism ,or creatin" $artitionise local

    inde5es

    DB2$7PIPE Provides a DBMS $i$e service t3at ena0les messa"es to 0e sent

    0eteen sessions

    DB2$7PRO8ILER Provides a Pro0e Pro,iler +PI to $ro,ile e5istin" PL2SQL a$$lications

    and identi, $er,ormance 0ottlenecs

    DB2$7RANDO2 Provides a 0uilt>in random num0er "enerator

    DB2$7RECTI8IER7

    DI88

    Provides +PIs used to detect and resolve data inconsistencies

    0eteen to re$licated sites

    DB2$7RE8RE$/ Is used to create "rou$s o, sna$s3ots t3at can 0e re,res3ed to"et3er to

    a transactionall consistent $oint in timeA re@uires t3e Distri0uted

    o$tion

    DB2$7REPAIR Provides data corru$tion re$air $rocedures

    DB2$7REPCAT Provides routines to administer and u$date t3e re$lication catalo" and

    environmentA re@uires t3e e$lication o$tion

    DB2$7REPCAT7

    AD2IN

    Is used to create users it3 t3e $rivile"es needed 0 t3e smmetric

    re$lication ,acilitA re@uires t3e e$lication o$tion

    DB2$7REPCAT7

    IN$TATIATE

    Instantiates de$loment tem$latesA re@uires t3e e$lication o$tion

    4-

  • 8/13/2019 Unit 5 PLSQL Fundamentals - Part II

    43/63

    DBMS Unit 4 Procedural SQL Fundamentals: Part II

    DB2$7REPCAT7RGT !ontrols t3e maintenance and de,inition o, re,res3 "rou$ tem$latesA

    re@uires t3e e$lication o$tion

    DB2$7REP,TIL Provides routines to "enerate s3ado ta0les? tri""ers? and $aca"es

    ,or ta0le re$licationDB2$7RE$O,RCE7

    2ANAGER

    Maintains $lans? consumer "rou$s? and $lan directivesA it also

    $rovides semantics so t3at ou ma "rou$ to"et3er c3an"es to t3e

    $lan sc3ema

    DB2$7RE$O,RCE7

    2ANAGER7PRI3$

    Maintains $rivile"es associated it3 resource consumer "rou$s

    DB2$7RL$ Provides ro>level securit administrative inter,ace

    DB2$7RO:ID Is used to "et in,ormation a0out OIDs? includin" t3e data 0loc

    num0er? t3e o08ect num0er? and ot3er com$onents

    DB2$7$E$$ION *na0les $ro"rammatic use o, t3e SQL +L(* S*SSIO& statement

    as ell as ot3er session>level commands

    DB2$7$/ARED7POOL Is used to ee$ o08ects in s3ared memor? so t3at t3e are not a"ed

    out it3 t3e normal LU mec3anism

    DB2$7$NAP$/OT Is used to re,res3 one or more sna$s3ots t3at are not $art o, t3e same

    re,res3 "rou$ and $ur"e lo"sA use o, t3is ,eature re@uires t3e

    Distri0uted o$tion

    DB2$7$PACE Provides se"ment s$ace in,ormation not availa0le t3rou"3 standard

    vies

    DB2$7$PACE7AD2IN Provides ta0les$ace and se"ment s$ace administration not availa0le

    t3rou"3 standard SQL

    D$2$7$5L Is used to rite stored $rocedure and anonmous PL2SQL 0locs

    usin" dnamic SQLA also used to $arse an DML or DDL statement

    DB2$7$TANDARD Provides lan"ua"e ,acilities t3at 3el$ our a$$lication interact it3

    t3e Oracle server

    DB2$7$TAT$ Provides a mec3anism ,or users to vie and modi, o$timiGer

    statistics "at3ered ,or data0ase o08ects

    DB2$7TRACE Provides routines to start and sto$ PL2SQL tracin"

    DB2$7TRAN$ACTION Provides $rocedures ,or a $ro"rammatic inter,ace to transaction

    mana"ement

    DB2$7TT$ !3ecs 3et3er i, t3e trans$orta0le set is sel,>contained

    DB2$7,TILIT Provides ,unctionalit ,or mana"in" $rocedures? re$ortin" errors? and

    ot3er in,ormation

    DEB,G7EXTPROC Is used to de0u" e5ternal $rocedures on $lat,orms it3 de0u""ers

    t3at can attac3 to a runnin" $rocess

    41

  • 8/13/2019 Unit 5 PLSQL Fundamentals - Part II

    44/63

    DBMS Unit 4 Procedural SQL Fundamentals: Part II

    O,TLN7PG Provides t3e inter,ace ,or $rocedures and ,unctions associated it3

    mana"ement o, stored outlines

    PLITBL2 =andles inde5>ta0le o$erations

    $DO7AD2IN Provides ,unctions im$lementin" s$atial inde5 creation andmaintenance ,or s$atial o08ects

    $DO7GEO2 Provides ,unctions im$lementin" "eometric o$erations on s$atial

    o08ects

    $DO72IGRATE Provides ,unctions ,or mi"ratin" s$atial data ,rom release 7.#.# and

    7.#.4 to '.1.5

    $DO7T,NE Provides ,unctions ,or selectin" $arameters t3at determine t3e

    0e3avior o, t3e s$atial inde5in" sc3eme used in t3e S$atial !artrid"e

    $TANDARD Declares t$es? e5ce$tions? and su0$ro"rams t3at are availa0le

    automaticall to ever PL2SQL $ro"ram

    TI2E$ERIE$ Provides ,unctions t3at $er,orm o$erations? suc3 as e5traction?

    retrieval? arit3metic? and a""re"ation? on time series data

    TI2E$CALE Provides scale>u$ and scale>don ,unctions

    T$TOOL$ Provides administrative tools $rocedures

    ,TL7COLL *na0les PL2SQL $ro"rams to use collection locators to @uer and

    u$date

    ,TL78ILE *na0les our PL2SQL $ro"rams to read and rite o$eratin" sstem

    OS te5t ,iles and $rovides a restricted version o, standard OS

    stream ,ile I2O

    ,TL7/TTP *na0les =((P callouts ,rom PL2SQL and SQL to access data on t3e

    Internet or to call Oracle e0 Server !artrid"es

    ,TL7PG Provides ,unctions ,or convertin" !OBOL numeric data into Oracle

    num0ers and Oracle num0ers into !OBOL numeric data

    ,TL7RA: Provides SQL ,unctions ,or + data t$es t3at concatenate? o0tain

    su0strin"? and so on? to and ,rom + data t$es

    ,TL7RE8 *na0les a PL2SQL $ro"ram to access an o08ect 0 $rovidin" a

    re,erence to t3e o08ect

    3IR7PG Provides analtical and conversion ,unctions ,or visual in,ormation

    retrieval

    Trigger

    ($e o, a (ri""er:

    Is a PL2SQL 0loc or a PL2SQL $rocedure associated it3 a ta0le? vie? sc3ema? or

    t3e data0ase

    4/

  • 8/13/2019 Unit 5 PLSQL Fundamentals - Part II

    45/63

    DBMS Unit 4 Procedural SQL Fundamentals: Part II

    *5ecutes im$licitl 3enever a $articular event taes $lace

    !an 0e eit3er:

    +$$lication tri""er: Fires 3enever an event occurs it3 a $articular a$$lication

    Data0ase tri""er: Fires 3enever a data event suc3 as DML or sstem event

    suc3 as lo"on or s3utdon occurs on a sc3ema or data0ase

    Data0ase tri""ers e5ecute im$licitl 3en a data event suc3 as DML on a ta0le

    an IN$ERT? ,PDATE? or DELETEtri""erin" statement? an IN$TEAD O8

    tri""er on a vie? or data de,inition lan"ua"e DDL statements suc3 as

    CREATEand ALTER are issued? no matter 3ic3 user is connected or 3ic3

    a$$lication is used.

    *5am$le o, Data0ase (ri""er

    Creating D'( )riggers

    (3e com$onents o, t3e tri""er:

    Part Description Possible !alues

    (ri""er timin" 3en t3e tri""er ,ires in relation to t3e

    tri""erin" event

    BE8ORE

    A8TERIN$TEAD O8

    (ri""erin" event 3ic3 data mani$ulation o$eration on t3e

    ta0le or vie causes t3e tri""er to ,ire

    IN$ERT

    ,PDATE

    DELETE

    (ri""er t$e =o man times t3e tri""er 0od e5ecutes Statement

    o

    (ri""er 0od 3at action t3e tri""er $er,orms !om$lete PL2SQL 0loc

    BE8ORE(ri""ers (3is t$e o, tri""er is ,re@uentl used in t3e ,olloin"

    4#

  • 8/13/2019 Unit 5 PLSQL Fundamentals - Part II

    46/63

  • 8/13/2019 Unit 5 PLSQL Fundamentals - Part II

    47/63

    DBMS Unit 4 Procedural SQL Fundamentals: Part II

    DML Statement:

    IN$ERT INTO dpartmnt* (dpartmnt7id.

    dpartmnt7nam. loation7id)

    3AL,E$ (11. 4CON$,LTING4. -11); (ri""er +ction:

    Basic *rigger Synta$,

    + tri""er is ,olloin" t3e ,ormat 0elo

    CREATE >OR REPLACE? TRIGGER trigger_name

    timing

    eent!>OR eent"OR eent#?

    ON table_name

    trigger_body

    In t3e snta5

    trigger name Is t3e name o, t3e tri""er

    timing Indicates t3e time 3en t3e tri""er ,ires in relation to t3e tri""erin"

    event:

    BE8ORE

    A8TER

    eent Identi,ies t3e data mani$ulation o$eration t3at causes t3e tri""er to

    ,ire:

    IN$ERT

    ,PDATE >O8 ol%mn?

    DELETE

    table/ie$_nam

    e

    Indicates t3e ta0le associated it3 t3e tri""er

    trigger body Is t3e tri""er 0od t3at de,ines t3e action $er,ormed 0 t3e tri""er?

    0e"innin" it3 eit3er DECLAREor BEGIN? endin" it3 END? or a call

    to a $rocedure

    *5am$le: create a tri""er to restrict inserts into t3e *MP ta0le to certain 0usiness 3ours?

    4%

  • 8/13/2019 Unit 5 PLSQL Fundamentals - Part II

    48/63

    DBMS Unit 4 Procedural SQL Fundamentals: Part II

    Monda t3rou"3 Frida.

    CREATE OR REPLACE TRIGGER *%r7mp

    BE8ORE IN$ERT ON mp

    BEGINI8 (TO7C/AR($$DATE.4D4) IN (4$AT4.4$,N4)) OR

    (TO7C/AR($$DATE.4//-=2I4)

    NOT BET:EEN 41=114 AND 40=114)

    T/EN RAI$E7APPLICATION7ERROR ("-1J11.4o% may

    in*rt into E2P ta&l only

    d%rin' &%*in** ho%r*@4);

    END I8;

    END;

    I, a user attem$ts to insert a ro into t3e E2PLOEE$ta0le on Saturda? t3e user

    sees t3e messa"e? t3e tri""er ,ails? and t3e tri""erin" statement is rolled 0ac.

    emem0er t3at t3eRAI$E7APPLICATION7ERRORis a server>side 0uilt>in

    $rocedure t3at returns an error to t3e user and causes t3e PL2SQL 0loc to ,ail.

    3en a data0ase tri""er ,ails? t3e tri""erin" statement is automaticall rolled 0ac

    0 t3e Oracle server.

    (estin" S*!U*9*MP

    IN$ERT INTO mp (mpno. nam. hirdat. 6o&. *al. dptno)

    3AL,E$ (911. 4$mith4. $$DATE. 4IT7PROG4. J11. H1);

    3en t3e date and time are out o, t3e 0usiness timin"s s$eci,ied in t3e tri""er?

    ou "et t3e error messa"e

    *5am$le: Usin" !onditional Predicates

    CREATE OR REPLACE TRIGGER *%r7mp

    BE8ORE IN$ERT OR ,PDATE OR DELETE ON mploy*

    BEGIN

    I8 (TO7C/AR ($$DATE.4D4) IN (4$AT4.4$,N4)) OR

    (TO7C/AR ($$DATE. 4//-4) NOT BET:EEN 414 AND 404)

    T/EN

    I8 DELETING T/EN

    RAI$E7APPLICATION7ERROR ("-1J1-.4o% may dlt rom

    E2P ta&l only d%rin' &%*in** ho%r*@4);

    EL$I8 IN$ERTING T/EN

    RAI$E7APPLICATION7ERROR ("-1J11.4o% may in*rt into

    E2P ta&l only d%rin' &%*in** ho%r*@4);

    EL$I8 ,PDATING (4$ALAR4) T/EN

    46

  • 8/13/2019 Unit 5 PLSQL Fundamentals - Part II

    49/63

    DBMS Unit 4 Procedural SQL Fundamentals: Part II

    RAI$E7APPLICATION7ERROR ("-1J19.4o% may %pdat

    $ALAR only d%rin' &%*in** ho%r*@4);

    EL$E

    RAI$E7APPLICATION7ERROR ("-1J1.4o% may %pdatE2P ta&l only d%rin' normal ho%r*@4);

    END I8;

    END I8;

    END;

    Cou can com0ine several tri""erin" events into one 0 tain" advanta"e o, t3e

    s$ecial conditional $redicates I&S*(I&

  • 8/13/2019 Unit 5 PLSQL Fundamentals - Part II

    50/63

    DBMS Unit 4 Procedural SQL Fundamentals: Part II

    enclosed in $arent3esis and is evaluated ,or eac3 ro to determine 3et3er

    or not t3e tri""er 0od is e5ecuted.

    tri''r &ody Is t3e tri""er 0od t3at de,ines t3e action $er,ormed 0 t3e tri""er?

    0e"innin" it3 eit3er DECLAREor BEGIN? endin" it3 END? or a call to a$rocedure

    Some im$ortant $oints to note:

    Cou can create onl BE8OREand A8TERtri""ers ,or ta0les. IN$TEAD O8

    tri""ers are onl availa0le ,or viesA t$icall t3e are used to im$lement vie

    u$dates.

    Cou ma s$eci, u$ to t3ree tri""erin" events usin" t3e eord OR.

    Furt3ermore? ,PDATEcan 0e o$tionall ,olloed 0 t3e eord O8and a

    list o, attri0utes in ta0le9nameJ. I, $resent? t3e O8clause de,ines t3e event

    to 0e onl an u$date o, t3e attri0utes listed a,ter O8. =ere are some

    e5am$les:

    @@@ IN$ERT ON R @@@

    @@@ IN$ERT OR DELETE OR ,PDATE ON R @@@

    @@@ ,PDATE O8 A. B OR IN$ERT ON R @@@

    I, 8OR EAC/ RO:o$tion is s$eci,ied? t3e tri""er is ro>levelA ot3erise? t3e

    tri""er is statement>level.

    Onl ,or ro>level tri""ers:

    (3e s$ecial varia0les NE:and OLDare availa0le to re,er to ne and old

    tu$les res$ectivel. &ote: In t3e tri""er 0od? NE:and OLDmust 0e

    $receded 0 a colon K:K? 0ut in t3e :/ENclause? t3e do not 3ave a

    $recedin" colon See e5am$le 0elo.

    (3e RE8ERENCINGclause can 0e used to assi"n aliases to t3e varia0les

    NE:and OLD.

    + tri""er restriction can 0e s$eci,ied in t3e :/ENclause? enclosed 0

    $arent3eses. (3e tri""er restriction is a SQL condition t3at must 0e

    satis,ied in order ,or Oracle to ,ire t3e tri""er. (3is condition cannotcontain su0@ueries.

    it3out t3e :/ENclause? t3e tri""er is ,ired ,or eac3 ro.

  • 8/13/2019 Unit 5 PLSQL Fundamentals - Part II

    51/63

    DBMS Unit 4 Procedural SQL Fundamentals: Part II

    Cou cannot modi, t3e same relation 3ose modi,ication is t3e event

    tri""erin" t3e tri""er.

    Cou cannot modi, a relation connected to t3e tri""erin" relation 0

    anot3er constraint suc3 as a ,orei"n>e constraint.

    *5am$le: e illustrate OracleEs snta5 ,or creatin" a tri""er t3rou"3 an e5am$le 0ased

    on t3e ,olloin" to ta0les:

    CREATE TABLE T (a INTEGER. & C/AR(01));

    CREATE TABLE TJ ( C/AR(01). d INTEGER);

    e create a tri""er t3at ma insert a tu$le into (% 3en a tu$le is inserted into (4.

    S$eci,icall? t3e tri""er c3ecs 3et3er t3e ne tu$le 3as a ,irst com$onent 1- or

    less? and i, so inserts t3e reverse tu$le into (%:

    CREATE TRIGGER tri'0

    A8TER IN$ERT ON T

    RE8ERENCING NE: A$ nMRoM

    8OR EAC/ RO:

    :/EN (nMRoM@a

  • 8/13/2019 Unit 5 PLSQL Fundamentals - Part II

    52/63

    DBMS Unit 4 Procedural SQL Fundamentals: Part II

    c3an"e 0 $re,i5in" it it3 t3e OLDand NE:@uali,ier.

    Data )peration )ld !alue e" !alue

    IN$ERT &ULL Inserted value

    ,PDATE ;alue 0e,ore u$date ;alue a,ter u$dateDELETE ;alue 0e,ore delete &ULL

    (3e OLDand NE:@uali,iers are availa0le onl in RO:tri""ers.

    Pre,i5 t3ese @uali,iers it3 a colon : in ever SQL and PL2SQL statement.

    (3ere is no colon : $re,i5 i, t3e @uali,iers are re,erenced in t3e :/EN

    restrictin" condition.

    &ote: o tri""ers can decrease t3e $er,ormance i, ou do a lot o, u$dates on

    lar"er ta0les.

    *5am$le: Usin" A%dit7Emp7Ta&l

    IN$ERT INTO mp

    (mpno. nam. 6o&. *al. @@@)

    3AL,E$ (. 4Tmp mp4. 4$A7REP4. 0111. @@@);

    ,PDATE mp

    $ET *al -111. nam 4$mith4

    :/ERE mpno ;

    !reate a tri""er on t3e *MP ta0le to add ros to a user ta0le?

    A,DIT7E2P7TABLE? lo""in" a users activit a"ainst t3e E2Pta0le.

    (3e tri""er records t3e values o, several columns 0ot3 0e,ore and a,ter t3e data

    c3an"es 0 usin" t3e OLDand NE:@uali,iers it3 t3e res$ective column name.

    *5am$le o, estrictin" a o (ri""er: !reate a tri""er on t3e E2Pta0le to calculate an

    em$loees commission 3en a ro is added to t3e E2Pta0le? or 3en an em$loees

    salar is modi,ied.

    CREATE OR REPLACE TRIGGER dri7omm

    BE8ORE IN$ERT OR ,PDATE O8 *alary ON mp

    8OR EAC/ RO:

    :/EN (NE:@6o& 4$A7REP4)

    BEGIN

    I8 IN$ERTING

    T/EN =NE:@omm = 1;

    EL$I8 =OLD@omm I$ N,LL

    T/EN =NE:@omm = 1;

    EL$E

    =NE:@omm = =OLD@omm K 1@1J;

    %-

  • 8/13/2019 Unit 5 PLSQL Fundamentals - Part II

    53/63

    DBMS Unit 4 Procedural SQL Fundamentals: Part II

    END I8;

    END;

    (o restrict t3e tri""er action to t3ose ros t3at satis, a certain condition? $rovide a

    :/ENclause.

    INSTEAD OF)riggers

    Use IN$TEAD O8tri""ers to modi, data in 3ic3 t3e DML statement 3as 0een issued

    a"ainst an in3erentl nonu$data0le vie.

    (3ese tri""ers are called IN$TEAD O8tri""ers 0ecause? unlie ot3er tri""ers? t3e

    Oracle server ,ires t3e tri""er instead o, e5ecutin" t3e tri""erin" statement. (3is tri""er

    is used to $er,orm an IN$ERT? ,PDATE? or DELETEo$eration directl on t3e

    underlin" ta0les.

    &ote: I, a vie is in3erentl u$datea0le and 3as IN$TEAD O8tri""ers? t3e tri""ers tae

    $recedence. IN$TEAD O8tri""ers are ro tri""ers.

    %reating an INSTEAD OF*rigger

    Snta5:

    CREATE >OR REPLACE? TRIGGER tri''r7nam

    IN$TEAD O8

    nt0 >OR nt- OR nt9?

    %1

  • 8/13/2019 Unit 5 PLSQL Fundamentals - Part II

    54/63

    DBMS Unit 4 Procedural SQL Fundamentals: Part II

    ON iM7nam

    >RE8ERENCING OLD A$ old # NE: A$ nM?

    >8OR EAC/ RO:?

    tri''r7&ody Snta5 ,or !reatin" an IN$TEAD O8(ri""er

    tri%%er_name Is the name of the tri%%er*

    IN$TEAD O8 Indicates t3at t3e tri""er 0elon"s to a vie

    nt Identi,ies t3e data mani$ulation o$eration t3at causes t3e tri""er to ,ire:

    IN$ERT

    ,PDATE >O8 column?

    DELETE

    iM7nam Indicates t3e vie associated it3 tri""erRE8ERENCING S$eci,ies correlation names ,or t3e old and ne values o, t3e current ro

    (3e de,aults are OLDand NE:

    8OR EAC/ RO: Desi"nates t3e tri""er to 0e a ro tri""erA IN$TEAD O8tri""ers can

    onl 0e ro tri""ers: i, t3is is omitted? t3e tri""er is still de,ined as a ro

    tri""er.

    tri''r &ody Is t3e tri""er 0od t3at de,ines t3e action $er,ormed 0 t3e tri""er?

    0e"innin" it3 eit3er DECLAREor BEGIN? and endin" it3 ENDor a

    call to a $rocedure

    &ote: IN$TEAD O8tri""ers can 0e ritten onl ,or vies. BE8OREand A8TER

    o$tions are not valid.

    *5am$le:

    (3e ,olloin" e5am$le creates to ne ta0les? NE:7E2P$and NE:7DEPT$?

    0ased on t3e E2Pand DEPTta0les res$ectivel. It also creates an E2P7DETAIL$

    vie ,rom t3e E2Pand DEPTta0les.

    (3e e5am$le also creates an IN$TEAD O8tri""er? NE:7E2P7DEPT.