Unit 12 (Program Units 1)

Embed Size (px)

Citation preview

  • 8/12/2019 Unit 12 (Program Units 1)

    1/39

    ALCHEMY SOLUTIONS PL/SQL PROGRAM UNITS

    1

  • 8/12/2019 Unit 12 (Program Units 1)

    2/39

    ALCHEMY SOLUTIONS PL/SQL PROGRAM UNITS

    Objectives

    At the end of this unit you will be able to:

    List the advantages of building PL/SQL subprograms.

    Create & !e"ute PL/SQL fun"tions.

    Call a stored fun"tion from within SQL.

    Create & !e"ute #atabase $riggers.

    Topics

    %ntrodu"tion

    PL/SQL Pro"edure

    PL/SQL un"tion

    Pa"'ages

    #atabase $riggers

    2

  • 8/12/2019 Unit 12 (Program Units 1)

    3/39

    ALCHEMY SOLUTIONS PL/SQL PROGRAM UNITS

    Intro!ction

    (ra"le allows a""essing and manipulating database information usingpro"edural s"hema ob)e"ts "alled PL/SQL program units. Pro"edures*fun"tions* and pa"'ages are all e!amples of PL/SQL program units.

    A pro"edure or a fun"tion is a s"hema ob)e"t that logi"ally groups a setof SQL and other PL/SQL programming language statements together toperform a spe"ifi" tas'. Pro"edures and fun"tions are "reated in a user+ss"hema and stored in a database for "ontinued use. ,ou "an e!e"ute apro"edure or fun"tion intera"tively using an ora"le tool* su"h as SQL -Plus or in (ra"le orms or in the "ode of another pro"edure or trigger.

    Pro"edures and fun"tions are nearly identi"al. $he only differen"es are:

    un"tions always return a single value to the "aller.

    Pro"edures return one or more than one values to the "aller.

    Pro"edures provide advantages in the following areas:

    Se"urity

    Performan"e

    emory allo"ation

    Produ"tivity

    %ntegrity

    Sec!rit"Stored pro"edures "an help enfor"e data se"urity. ,ou "an restri"tthe database operations that users "an perform by allowing themto a""ess data only through pro"edures and fun"tions.

    Per#or$%nceStored pro"edures "an improve database performan"e. se ofpro"edures dramati"ally redu"es the amount of information thatmust be sent over a networ' "ompared to issuing individual SQLstatements or sending the te!t of an entire PL/SQL blo"' toora"le. urthermore be"ause a pro"edure+s "ompiled form isreadily available in the database no "ompilation step is re0uiredto e!e"ute the "ode. Additionally if the pro"edure is already

    3

  • 8/12/2019 Unit 12 (Program Units 1)

    4/39

    ALCHEMY SOLUTIONS PL/SQL PROGRAM UNITS

    present in the shared pool of the S1A retrieval from dis' is notre0uired and e!e"ution "an begin immediately.

    Me$or" %&&oc%tion2e"ause stored pro"edures ta'e advantage of the shared memory

    "apabilities of (ra"le only a single "opy of the pro"edure needs tobe loaded into memory for e!e"ution by multiple users. Sharingthe same "ode among many users results in a substantialredu"tion in (ra"le memory re0uirements for appli"ations.

    Pro!ctivit"Stored pro"edures in"rease development produ"tivity. 2ydesigning appli"ations around a "ommon set of pro"edures* you"an avoid redundant "oding and in"rease your produ"tivity.

    Inte'rit" Stored pro"edures improve the integrity and "onsisten"y ofyour appli"ations. 2y developing all your appli"ations around a"ommon group of pro"edures you "an redu"e the li'elihood of"ommitting "oding errors.

    Anon"$o!s PL/SQL (&oc)s vs* Store Proce!res

    Sending an unnamed PL/SQL blo"' to (ra"le server from an

    (ra"le tool or an appli"ation "reates an anonymous PL/SQL blo"'.

    (ra"le "ompiles the PL/SQL blo"' and pla"es the "ompiled versionin the shared pool of the S1A but does not store the sour"e "odeor "ompiled version in the database for subse0uent reuse.

    Shared SQL area allows a "ompiled anonymous PL/SQL blo"'

    already in the shared pool to be reused and shared until it isflushed out of the shared pool.

    Alternatively a stored pro"edure is "reated and stored in the

    database as an ob)e"t. (n"e "reated and "ompiled it is a namedob)e"t that "an be e!e"uted without re"ompiling. Additionallydependen"y information is stored in the data di"tionary toguarantee the validity of ea"h stored pro"edure.

    %n summary by moving PL/SQL blo"'s out of a databaseappli"ation and into stored pro"edures you avoid unne"essarypro"edure re"ompilations by (ra"le at runtime improving theoverall performan"e of the appli"ation and (ra"le.

    4

  • 8/12/2019 Unit 12 (Program Units 1)

    5/39

    ALCHEMY SOLUTIONS PL/SQL PROGRAM UNITS

    PL/SQL Proce!re

    $ransfer values to and from the "alling environment through arguments.

    a"h argument in the pro"edure will have one of the three modes. %n mode isdefault.

    Ar'!$ent +escription

    IN Pass a value from the "alling environment into thepro"edure 3default4

    OUT 5eturn a value from the pro"edure to the "allingenvironment.

    5

    Procedure

    INArgument

    OUT Argument

    IN OUTArgument

    (Declare)

    BEGIN

    EXCEPTIN

    END

    Call!ng

    En"!ronment

  • 8/12/2019 Unit 12 (Program Units 1)

    6/39

    ALCHEMY SOLUTIONS PL/SQL PROGRAM UNITS

    IN OUT Pass a value from the "alling environment into thepro"edure* return a potentially different value from thepro"edure to the "alling environment.

    Cre%te % PL/SQL proce!re

    St%te$ent CREATE PROCE+URE

    S"nt%,

    -.ereREPLACE is spe"ified when pro"edure already e!ists.

    proce!ren%$e is the name of the pro"edure%r'!$ent is the name of a PL/SQL variable passed to

    the pro"edure

    $oe denotes the type of argument%6 3default4($%6 ($

    +%t%t"pe is the datatype of the argumentp&/s0&b&oc) is the pro"edural blo"' that defines the a"tion

    performed by the pro"edure.

    Note se the 'eyboard AS instead of %S* if desired7 they are

    e0uivalent.

    Start the sub8program blo"' with the 'eyword 21%6 or with a

    lo"al variable de"laration. 6ever start the sub8program blo"'swith the 'eyword #CLA5.

    #

    C$EATE %$ $EP&ACE' P$CED$E rocedure*name

    (argument1 %mode1' datat+e1,

    argument2 %mode2' datat+e2,

    -.)

    I/ 0 A/

    Pll*loc6

  • 8/12/2019 Unit 12 (Program Units 1)

    7/39

    ALCHEMY SOLUTIONS PL/SQL PROGRAM UNITS

    nd the blo"' with the 'eyboard 6#* or 6# followed by the

    pro"edure name.

    Invo)e t.e Proce!re

    $o invo'e the pro"edure "reated from variousenvironments.

    S"nt%,

    -.ereProce!ren%$e is the name of the pro"edure.

    Ar'!$ent is the variable* e!pression* "onstant* orliteral passed to the pro"edure.

    Note

    $he number and datatypes of the a"tual argumentsspe"ified when the pro"edure is invo'ed must mat"hthe number and datatypes of the formal argumentsspe"ified when the pro"edure was "reated. $he namesof the arguments do not have to mat"h.

    se 9C$ "ommand to invo'e pro"edure from SQL-

    Plus.

    Pass values from the "alling environment into thepro"edure using %6 argument.

    E,%$p&e pdate the salary of the spe"ified employee to thespe"ified amount

    PL/SQL Coe C5A$ (5 5PLAC P5(C#5 raisesalary3vempno %6 emp.empno;$,P* vnewsal %6 emp.sal;$,P4

    %S

    7

    Procedure*name (argument1, argument2,--)6

  • 8/12/2019 Unit 12 (Program Units 1)

    8/39

    ALCHEMY SOLUTIONS PL/SQL PROGRAM UNITS

    21%6P#A$ emp

    S$ sal < sal = vnewsal>?5 empno < vempno7

    C(%$ >(5@7

    6# raisesalary7/

    SQL 9C$ raisesalary 3BDE*FF47

    5eturn values from the pro"edure to the "alling environment into using ($arguments.

    E,%$p&e 5etrieve the salary of the spe"ified employee.

    PL/SQL C5A$ (5 5PLAC P5(C#5 getsal3vempno %6 emp.empno;$,P* vsal ($ emp.sal;$,P4

    %S21%6

    SLC$ sal %6$( vsal5( emp>?5 empno < vempno7

    6# getsal7/

    SQL GA5%A2L gsal number

    SQL9C$ getsal 3BDE*: gsal47

    SQLP5%6$ gsal

    Pass values from the "alling environment into the pro"edure and 5eturnpotentially different values from the pro"edure to the "alling environmentusing %6 ($ arguments.

    E,%$p&e Add a dash to the spe"ified phone number at the "orre"tposition.

    PL/SQL CoeC5A$ (5 5PLAC P5(C#5 adddash3vphone %6 ($ var"harD4

    %S21%6

    8

  • 8/12/2019 Unit 12 (Program Units 1)

    9/39

    ALCHEMY SOLUTIONS PL/SQL PROGRAM UNITS

    vphone :< S2S$5 3vphone* E*H4 II J8J II S2S$53vphone* K*K47

    6# adddash7/

    SQL GA5%A2L pno GA5C?A5D 34

    21%6: pno :< MNNKOKNK+7adddash 3:pno47

    6#7/SQL P5%6$ pno7

    PL/SQL 1!nction

    Create a PL/SQL fun"tion instead of a pro"edure wheninvo'ing the subprogram as part of an e!pression* ratherthan as a "omplete statement.

    9

    Procedure

    IN Argument

    (Declare)

    BEGIN

    EXCEPTIN

    END

    Call!ng

    En"!ronment

  • 8/12/2019 Unit 12 (Program Units 1)

    10/39

    ALCHEMY SOLUTIONS PL/SQL PROGRAM UNITS

    Create a fun"tion to return a value to the "alling environment.

    St%te$ent CREATE 1UNCTION

    S"nt%,

    -.ere

    REPLACE is spe"ified when pro"edure already e!ists.#!nctionn%$e is the name of the fun"tion%r'!$ent is the name of a PL/SQL variable passed to

    the fun"tion$oe denotes the %6 of argument%t%t"pe is the datatype of the argument

    RETURN denotes the argument outputted by thefun"tion.

    p&/s0&b&oc) is the pro"edural blo"' that defines the a"tionperformed by the fun"tion.

    Note

    se the 'eyword AS instead of %S* if desired7 they are e0uivalent.

    A return statement S$ e!ist within the PL/SQL blo"'.

    Invo)e t.e 1!nction

    $o invo'e the fun"tion within a PL/SQL e!pression.

    S"nt%,

    1:

    C$EATE %$ $EP&ACE' ;NCTIN

  • 8/12/2019 Unit 12 (Program Units 1)

    11/39

    ALCHEMY SOLUTIONS PL/SQL PROGRAM UNITS

    -.ere

    o!tp!tv%ri%b&e is the output variable for storing thevalue

    returned by the fun"tion.#!nctionn%$e is the name of the fun"tion%r'!$ent is the variable* e!pression* "onstant* or

    literal passed to the fun"tion.

    E,%$p&e 5etrieve the salary of the spe"ified employee

    PL/SQL Coe C5A$ (5 5PLAC 6C$%(6 getsalary3vempno %6 emp.empno;$,P4

    5$56 625

    %SGsal emp.sal;$,P7

    21%6SLC$ sal %6$( vsal

    5( emp >?5 empno < vempno75$56 3vsal47

    6# getsalary7/

    SQLGA5%A2L gsalary 625

    21%6: gsalary :< getsalary 3BDE47

    6#7/

    SQLP5%6$ gsalary

    E,%$p&e Create a fun"tion that returns an employee+s bonus whi"his

    2ased on their salary and department to whi"h they belong

    PL/SQL Coe C5A$ (5 5PLAC 6C$%(6 getbonus3vempno %6 emp.empno; $,P45$56 625%S

    2on emp."omm;$,P7

    11

  • 8/12/2019 Unit 12 (Program Units 1)

    12/39

    ALCHEMY SOLUTIONS PL/SQL PROGRAM UNITS

    Gdeptno emp.deptno;$,P7G)ob emp.)ob;$,P7G sal emp.sal;$,P7

    21%6SLC$ deptno* )ob* sal %6$(vdeptno* v)ob*

    and vsal 5( emp >?5 empno hen defining a trigger you "an spe"ify the trigger timing* i.e. you "anspe"ify when the triggering a"tion is to be e!e"uted in relation to thetriggering statement. 2(5 and A$5 apply to both row and

    statement triggers.

    2(5 triggers e!e"ute the trigger a"tion before the triggeringstatement. $hese types of triggers are "ommonly used in the followingsituations:

    >hen the trigger a"tion should determine whether or not triggering

    statement should be allowed to be "ompleted. 2y using 2(5

    22

  • 8/12/2019 Unit 12 (Program Units 1)

    23/39

    ALCHEMY SOLUTIONS PL/SQL PROGRAM UNITS

    trigger* you "an eliminate unne"essary pro"essing of the triggeringstatement.

    $o derive spe"ifi" "olumn values before "ompleting a triggering

    %6S5$ or P#A$ statement.

    A$5 trigger e!e"utes the trigger a"tion after the triggering statementis e!e"uted. $hese types of triggers are "ommonly used in the followingsituations.

    >hen you want triggering statement to "omplete before e!e"uting

    the trigger a"tion.

    %f a 2(5 trigger is already present* different a"tions on the same

    triggering statement "an be performed.

    Co$bin%tionssing "ombinations of the triggers e!plained so far* four types of triggers"ould be "reated.

    Before Statement Trigger2efore e!e"uting the triggering statement* the trigger a"tion is

    e!e"uted.

    Before Row Trigger2efore modifying ea"h row affe"ted by the triggering statement and

    beforeAppropriate integrity "onstraints* the trigger is e!e"uted* if the triggerrestri"tion either evaluated to $5 or was not in"luded.

    After Statement TriggerAfter e!e"uting the triggering statement and applying any deferred%ntegrity "onstraints* the trigger a"tion are e!e"uted.

    After Row TriggerAfter modifying ea"h row affe"ted by the triggering statement andPossibly applying appropriate integrity "onstraints* the trigger a"tion ise!e"uted for the "urrent row* if the trigger restri"tion either evaluatesto $5 or was not in"luded. nli'e 2(5 row trigger* A$5 rowtriggers have rows lo"'ed.

    23

  • 8/12/2019 Unit 12 (Program Units 1)

    24/39

    ALCHEMY SOLUTIONS PL/SQL PROGRAM UNITS

    Tri''er $oes

    En%b&eAn enabled trigger e!e"utes its trigger a"tion if a triggering statement isissued and the trigger restri"tion 3if any4 evaluates to $5.

    +is%b&eA disabled trigger e!e"utes its trigger a"tion if a triggering statement isissued and the trigger restri"tion 3if any4 would evaluate to $5.

    or enabled triggers* ora"le automati"ally:

    !e"utes triggers in a planned firing se0uen"e when a single SQL

    statement fires more than one trigger.

    Performs integrity "onstraint "he"'ing at a set point in time with

    respe"t to the different types of triggers and guarantees that triggers"annot "ompromise integrity "onstraints.

    Provides read8"onsistent views for 0ueries and "onstraints. anages the dependen"ies among the triggers and ob)e"ts referen"ed

    in the "ode of the trigger a"tion.

    ses two8phase "ommit if a trigger updates remote tables.

    Data Access for Triggers>hen a trigger is fired* the tables referen"ed in the trigger a"tion mightbe "urrently undergoing "hanges by SQL statements "ontained in otheruser+s transa"tions. %n all "ases* the SQL statements e!e"uted withintriggers follow the "ommon rules used for stand8alone SQL statements. %fan un"ommitted transa"tion has modified values that a trigger beingfired either needs to read 30uery4 or write 3update4* the SQL statementsin the body of the trigger being fired use the following guidelines:

    Queries see the "urrent read8"onsistent snapshot of referen"ed

    tables and any data "hanged within the same transa"tion.

    pdates wait for e!isting data lo"'s before pro"eeding.

    !ecution of Triggers

    (ra"le internally e!e"utes a trigger using the same steps used forpro"edure e!e"ution* the only subtle differen"e is that user a""ess tofire a trigger is verified if a user has the privilege to e!e"ute a triggeringstatement. (ther than this* triggers are validated and e!e"uted thesame way as stored pro"edures.

    24

  • 8/12/2019 Unit 12 (Program Units 1)

    25/39

    ALCHEMY SOLUTIONS PL/SQL PROGRAM UNITS

    St%te$ent CREATE TRIGGER

    S"nt%,

    WhereREPLACE re"reates the trigger if it already e!ists. ,ou "an use

    this option to "hange the definition of an e!isting triggerwithout first dropping it.

    Usern%$e is the same the user* in whose wor' area the trigger>ill be stored. %f you omit the username* ora"le "reatesthe trigger in the wor'8area of the user who "reated thetrigger.

    Tri''ern%$e is the name of the trigger to be "reated.

    (E1ORE indi"ates that ora"le fires the trigger before

    !e"uting the triggering statement.

    A1TER indi"ates that ora"le fires the trigger after e!e"utingthe triggering statement.

    +ELETE indi"ates that ora"le fires the trigger whenever a #L$statement removes a row from the table. $he (

    25

    C$EATE %$$EP&ACE' T$IGGE$ %uername.'Tr!ggername

    BE;$EA;TE$ DE&ETEIN/E$TPDATE%; columnname %, columnname, columnname-.''

    N %uername.' talename

    %;$ EAC $F %FEN cond!t!on'

    $E;E$ENCING &D A/ oldnameNEF A/ nename'

    DEC&A$E

    @ar!ale declarat!on

    Contant declarat!on

    BEGIN

    P&/H& tatement

    END6

  • 8/12/2019 Unit 12 (Program Units 1)

    26/39

    ALCHEMY SOLUTIONS PL/SQL PROGRAM UNITS

    "olumnname * "olumnname*T option is not available for#L$.

    INSERT indi"ates that ora"le fires the trigger whenever an %6S5$statement adds a row to the table. $he ( "olumnname *

    "olumnname*T option is not available for %6S5$.

    UP+ATE indi"ates that ora"le fires the trigger whenever an P#A$statement "hanges a value in one of the "olumns spe"ifiedin the ( "lause. %f the ( "olumnname * "olumnname*T"lause is spe"ified* ora"le fires a trigger whenever theP#A$ statement "hanges a value of a "olumn spe"ified inthis "lause* else it will be fired whenever the P#A$statement "hanges a value in any "olumn of the table.

    ON spe"ifies the username and the name of the table on whi"h

    the trigger is to be "reated. %f you omit the username*ora"le assumes the table is in your own wor'8area. ,ou "an"reate a trigger on a table in the wor'8area S,S.

    RE1ERENCING Spe"ifies "orrelation names. $he "orrelation names "an beused in the PL/SQL blo"' and in >?6 "lause of a rowtrigger to refer spe"ifi"ally to old and new values of the"urrent row. $he default "orrelation names are (L# and6>.

    1OR EACH designates the trigger to be a row trigger. (ra"le fires arow triggerRO- for ea"h row that is affe"ted by the triggering statement

    and meets the optional trigger "onstraint defined in the>?6 "lause. %f you omit this "lause* the trigger is astatement trigger.

    -HEN spe"ifies the trigger restri"tion. $he trigger restri"tion"ontains an SQL "ondition that must be satisfied for ora"le

    to fire the trigger. $his "ondition must "ontain "orrelationnames and "annot "ontain 0uery. (ra"le evaluates this"ondition for ea"h row affe"ted by the triggeringstatement.

    +ECLARE* %s the PL/SQL blo"' that ora"le e!e"utes to fire the triggerEN+ $his blo"' "annot "ontain transa"tion SQL statements i* e

    C(%$* 5(LL2AC@ and SAGP(%6$.

    2#

  • 8/12/2019 Unit 12 (Program Units 1)

    27/39

    ALCHEMY SOLUTIONS PL/SQL PROGRAM UNITS

    St%te$ent +ROPPING TRIGGER

    S"nt%,

    WhereTri''ern%$e is the name of the trigger to

    be dropped

    E,%$p&eA trigger to "he"' the salary of the employees before insert orupdate on emp table and raise e!"eption whenever the salary ofan employee goes out of range. $he minimum and ma!imumsalary limit for ea"h designation is stored in the sal table.

    PL/SQL CoeC5A$ (5 5PLAC $5%115 "he"'sal2(5 %6S5$ (5 P#A$ ( sal* )ob (6 emp(5 AC? 5(>>?6 3new.)obU+P5S%#6$+4#CLA5

    vminsal sal.minsal;$,P7vma!sal sal.ma!sal;$,P7saloutofrange 9CP$%(67

    21%6SLC$ minsal* ma!sal %6$( vminsal* vma!sal5( sal >?5 )ob ?6 saloutofrange $?65A%SAPPL%CA$%(6 55(5 38DFEFF*+Salary out of range.+47

    6#7

    /

    E,%$p&e A database trigger to automati"ally updateCommission of employees who are salesman.

    PL/SQL CoeC5A$ (5 5PLAC $5%115 derive"omm2(5 %6S5$ (5 P#A$ ( sal (6 emp

    27

    D$P T$IGGE$ tr!ggername=

  • 8/12/2019 Unit 12 (Program Units 1)

    28/39

    ALCHEMY SOLUTIONS PL/SQL PROGRAM UNITS

    (5 AC? 5(>>?6 3new.)ob

  • 8/12/2019 Unit 12 (Program Units 1)

    29/39

    ALCHEMY SOLUTIONS PL/SQL PROGRAM UNITS

    D A## C(6S$5A%6$ P(5%16@, H (5%16 @, 3#P$6(4 556CS # K P$ 3#P$6(47

    Res!&t $able altered.

    E,%$p&e pdate when referential "onstraint is present.

    SQL Co$$%n SQLP#A$ #P$ D S$ #P$6(?5 #P$6(

  • 8/12/2019 Unit 12 (Program Units 1)

    30/39

    ALCHEMY SOLUTIONS PL/SQL PROGRAM UNITS

    %6S$A# ( triggers provide a transparent way of modifying views that"annot be modified dire"tly through P#A$* %6S5$* and #L$statements.

    E,%$p&e $o update the base table through a )oin view

    SQL Coe Create or 5epla"e Giew Voinview asSele"t empno*ename*)ob*sal*emp.deptno*dname*lo"from emp* deptwhere emp.deptno21%6

    %6S5$ %6$( #ept GALS 3 :new.deptno*:new.dname*

    :new.lo"47%6S5$ %6$( mp 3mpno*name*Sal*#eptno4GALS3:new.empno*:new.ename*:new.sal*:new.deptno47

    6#7/

    6ow if an %nsert statement is fired on view Voinview* then the

    values are inserted in the mp and #ept table.

    SUMMARY 56

    3:

  • 8/12/2019 Unit 12 (Program Units 1)

    31/39

    ALCHEMY SOLUTIONS PL/SQL PROGRAM UNITS

    $he PL/SQL programs "an be stored in the database as stored programs and

    "an be invo'ed whenever re0uired. $his avoids reparsing when multipleusers invo'e it.

    PL/SQL has two types of subprograms "alled Pro"edures and un"tions

    Subprograms allows to brea' a program down into manageable* well defined

    logi" modules

    A Pro"edure is a subprogram that performs a spe"ifi" a"tion. A pro"edure

    "an be "alled from any PL/SQL program or from SQL prompt.

    A un"tion is a subprogram that retruns a value

    A fun"tion must have a 5$56 "lause. 5$56 statement is used to return

    the "ontrol to the "alling environment

    Act!%& P%r%$eters are the variables or e!pressions referen"ed in the

    parameter list of a subprogram

    1or$%& P%r%$eters are the variables de"lared in a subprogram

    spe"ifi"ation and referen"ed in the subprogram body

    $here are three argument modes whi"h "an be used with any subprograms

    %6 $he %6 parameter lets the user pass values to the "alled

    Subprogram. %nside the subprogram* the %6 parameter a"ts

    li'e a "onstant* therefore it "annot be modified. ($ $he ($ mode parameter lets the user return values to the

    "allingnvironment. %nside the subprogram* the ($ parameter

    a"ts li'ean unintialised variable. $herefore* its value "annot be

    assigned toanother variable or to itself.

    %6 ($ $he %6 ($ parameter lets the user pass intial values to the

    "alledSubprogram and returns updated values the "alling blo"'.

    Stored Pa"'age is a database ob)e"t that groups logi"allyrelated PL/SQL

    ob)e"ts. %t en"apsulate related pro"edures* fun"tions* asso"iated "ursorsand variables together as a logi"al unit in the database

    31

  • 8/12/2019 Unit 12 (Program Units 1)

    32/39

    ALCHEMY SOLUTIONS PL/SQL PROGRAM UNITS

    Pa"'ages are made of "omponents :

    $he spe"ifi"ations de"lares the types* variables* "onstants*

    e!"eptions* "ursors and subprograms

    $he body defines "ursors and subprograms. %t holds imlementation

    details and private de"larations* whi"h are hidden from theappli"ation

    Pa"'ages offer several advantages whi"h in"ludes modularity* easier

    appli"ation design* information hiding* added fun"tionality and betterperforman"e

    $o referen"e the types* ob)e"ts and subprograms de"lared within a pa"'age

    spe"ifi"ation* dot notation is used as follows :Pa"'agename.typenamePa"'agename.ob)e"tnamePa"'agename.subprogramname

    A #atabase $rigger is a stored PL/SQL program unit asso"iated with a

    database table. $he database triggers impli"itly gets fired whenever theaffe"ted by any SQL operation

    A database trigger has three parts :

    A tri''erin' event is the SQL statement 3 %6S5$* P#A$ or #L$statement for a spe"ifi" table4 that "auses a trigger to be used

    A tri''er restriction is spe"ified using a >?6 "lause. A trigger

    restri"tion spe"ifies a 2oolean e!pression that must be $5 to fire.$he trigger a"tion is not e!e"uted if the restri"tion evaluates toALS.

    A tri''er %ctionis the pro"edure that "ontains the SQL statements

    and PL/SQL "ode to be e!e"uted when a triggering statement isissued and the trigger restri"tion evaluates to $5

    $o "reate a database trigger there are three different options available to

    us :2(5 option (ra"le fires the trigger only on"e* before e!e"uting

    the$riggering statement

    A$5 option (ra"le fires the trigger only on"e* after e!e"utingthe

    32

  • 8/12/2019 Unit 12 (Program Units 1)

    33/39

    ALCHEMY SOLUTIONS PL/SQL PROGRAM UNITS

    triggering statement%6S$A# ( option (ra"le fires the trigger only on"e* to do something

    elseinstead of performing the a"tion that e!e"uted the

    trigger

    $here are two levels at whi"h trigger "an be fired

    5ow Level $rigger

    Statement Level $rigger

    PL/SQL PROGRAMMINGLA( E7ERCISES

    PL/SQL

    E. Create a table mployee with the following rows and "olumns:

    Eno +eptno

    Aress P.one S%&%r" (on!s Tot%&

    E D EH* S2% Colony*adras

    HKN FFFF

    D H DH* 5am Colony*adras

    NNKD EFFFF

    H E EBK* Anna6agar*adras

    BKNO FFF

    K D HK* 6aidu Street*adras

    HKHNH FFF

    H EK* 5a)a 6agar*

    adras

    DNKNH OFF

    D. #evelop a PL/SQL blo"' to do the following:

    Cal"ulate the value for the 2onus "olumn as F.KF - Salary. %f salary is

    greater than 5s. FFF* then no bonus should be rewarded to theemployee.

    Cal"ulate the value for the $otal "olumn as Salary = 2onus.

    33

  • 8/12/2019 Unit 12 (Program Units 1)

    34/39

    ALCHEMY SOLUTIONS PL/SQL PROGRAM UNITS

    Commit the updates made above.

    H. >rite PL/SQL "ode do the following:

    ind the average and the total of the salaries of all employees in

    department number H. ind the highest and the lowest of the salaries of all employees and

    the differen"e between them.

    ind the names* employees numbers and salaries of the five highest8

    paid employees.

    K. #evelop a PL/SQL blo"'* whi"h returns a number ea"h from two tables theninserts the sum of these numbers into a third table. $he pro"ess should

    terminate afterall the rows are fet"hed from either of the two tables.

    . #evelop a PL/SQL blo"' to:

    pdate the telephone number of an employee with employee number

    H to NDKFDHF.

    #elete the re"ord where the employee is e0ual to D.

    %nsert a new employee into the employee table.

    Commit the updates that are made to the data.

    N. #evelop a blo"' to store the number of employees belonging to

    departments whi"hnumber D toH.

    B. $ype the following "ommand at the SQL prompt:

    Create table 6umbers36umber integer not null47

    #evelop a blo"' that fills the table above with numbers E to EFF in"lusiveusing an % loop.

    . $ry to fill the above 6umbers table with numbers from E toEFF using a (5

    loop.

    O. ill the 6umbers table with values from E to EFF using a >?%L loop.

    EF.5ewrite the previous statement using the 9%$ statement.

    EE.Create table Players with the following rows and "olumns:

    34

  • 8/12/2019 Unit 12 (Program Units 1)

    35/39

    ALCHEMY SOLUTIONS PL/SQL PROGRAM UNITS

    P&%"erno

    N%$e Initi%&s Street Le%'!eno

    N ahesh 5 ldams 5oad KNB

    KK 2anu G 5' utt 5oad

    H ?arish G.P 1andhi Street ENF

    D lango S 6adu Street DKEEDB Chris 5.? 5am 6agar BO

    ED.Create table $eams with the following rows and "olumns:

    Te%$no P&%"erno +ivision

    E N irst

    D DB Se"ond

    EH.Create a table with the following rows and "olumns:

    M%tc.no Te%$no P&%"erno -on Lost

    E E N H E

    D E N D H

    H E N H F

    K E KK H D

    E H F H

    EK.Create a table with penalties with the following rows and "olumns:

    Paymentno Playerno Pendate Amount

    E N F8#e"8OF EFF.FF

    D KK F8#e"8OE B.FF

    H DB EE8Sep8OD EFF.FF

    K EFK F8#e"8OK F.FF

    KK F8#e"8OF D.FF

    N F8#e"8OF D.FF

    B DB ED86ov8OK B.FF

    35

  • 8/12/2019 Unit 12 (Program Units 1)

    36/39

    ALCHEMY SOLUTIONS PL/SQL PROGRAM UNITS

    E.#evelop a PL/SQL blo"' that deletes all the re"ords from the Penalties tablewherethe penalty amount is greater than 5s.F.

    EN.#evelop a PL/SQL blo"' that does the following:

    Cal"ulate the average of the amount "olumn in the Penalties table

    and store the result in a variable "alled Javerage+.

    %n"rement the value of the variable Javerage+ by EF.

    Compare the Amount "olumn of the Penalties with the variable

    Javerage+ and delete all the re"ords from the Penalties table wherethe value in the Amount "olumn is greater than the value stored inthe variable Javerage+.

    EB.#evelop a PL/SQL blo"' that does the following:

    Cal"ulate the average of the Amount "olumn and store in a variable

    "alled Javerage+.

    %f Javerage+ is greater than EFF then update the Penalties table by

    multiplying the "olumn Amount by F.O.

    E.>rite a PL/SQL blo"' to do the following:

    Cal"ulate the average of the Amount "olumn and store it in a variable

    Javerage+

    %f average is less than EF then per"entage 3a user defined variable4 is

    e0ual to * else if average is greater than EF* then per"entage ise0ual to F* else if average is greater than EFF* then per"entage ise0ual to X. %n other "onditions the per"entage should be e0ual to E.

    pdate table Penalties by setting the "olumn Amount as:

    Amount < Amount - 3E=3per"entage/EFF4.

    EO.#evelop a blo"' that "he"'s whether ea"h player in the at"hes table has aleaguenumber delete the player+s details from the at"hes table.

    DF.$ry solving the above problem by using a Loop8!it when8"ondition.

    DE.Solve the above problem by using a or loop.

    3#

  • 8/12/2019 Unit 12 (Program Units 1)

    37/39

    ALCHEMY SOLUTIONS PL/SQL PROGRAM UNITS

    DD.se a sub0uery in pla"e of the "ursor to a""omplish the same )ob.

    DH.#evelop a blo"' to store the numbers of the players born between EOF andEONF in help table using a "ursor.

    DK.#evelop a blo"' to store the numbers of the players born between EOF andEONF in help table using a "ursor but without using any (pen et"h or Closestatements.

    D.#evelop a blo"' to delete all teams from the $eams table on the "onditionthat five teams remain.

    DN.#evelop a blo"' to add a new team. %f the "aptain number does not o""ur inthe Players table the update must be rolled ba"'.

    DB.#evelop a blo"'* whi"h rolls ba"' the transa"tion if 3by a""ident4 a division

    by Yero o""urs.

    D.#evelop a blo"' to roll ba"' the transa"tion if too large a value is insertedinto the "olumn.

    DO.#evelop a PL/SQL blo"' that stores the relevant te!t of all SQL C(#S in thetable. >e assume the Codetable has been "reated with two "olumns.

    HF.Create a table Sales with the following rows and "olumns.

    Sno 6ame Salary 6ativity $arget Sales anage

    r

    Pro)e"t

    E 5aman FFF adras DFFFF EFFF #anapal EFE

    D 1opal NFF 2ombay HFFFF DFFFF EFH

    H $arun FFF Co"hin DFFFF FFF A'ila EFE

    K 1ovind BFFF adras EFFF FFF EFD

    5e'ha FF 2ombay DFFFF EFFF #anapal EFE

    N 5aa'hi BFF 2ombay DFFFF EBFFF A'ila EFH

    #evelop a PL/SQL blo"' to do the following:

    pdate the salary by 5s.EFF for all employees whose "odes are greater

    than K and for the remaining employees by 5s.FF.

    37

  • 8/12/2019 Unit 12 (Program Units 1)

    38/39

    ALCHEMY SOLUTIONS PL/SQL PROGRAM UNITS

    List the employees whose sales are below NF; of the target.

    ind all the employees whose native pla"es are either 2ombay or adras.

    HE.#evelop a PL/SQL blo"' to do the following:

    Assign the employee $arun together with his manager to pro)e"t numberEFH.

    Assign the employees with employee number greater than H to pro)e"t

    number EFE.

    Assign all other employees to pro)e"t number EFD.

    HD.Create a table "alled essages with "olumns Serial6o and essage. >ritePL/SQL

    "ode to insert numbers from E to in the Serial6o "olumn and a "onstantte!t in the

    message "olumn.

    HH. Create three "olumns "alled inventory* Custorders and Spe"ialorders asfollows:

    Inventor"

    6umber3N4T Char3HF4T Char3DF4T 6umber3H4T

    Produ"t8id Produ"t8name Produ"t8status Std8order80ty

    E Sugar %n sto"' EFF

    D 5i"e 2a"' ordered DFF

    H >heat Spe"ial order HFF

    C!storers

    38

  • 8/12/2019 Unit 12 (Program Units 1)

    39/39

    ALCHEMY SOLUTIONS PL/SQL PROGRAM UNITS

    6umber3ED4T 6umber3N4T 6umber3H4T

    (rder8no Produ"t8id Arrival8date

    E E

    D E

    H HK D

    D

    Speci%&orers

    6umber3ED4T 6umber3N4T 6umber3H4T

    (rder8no Produ"t8id (rder80ty

    $ype an order number and get the "orresponding P5(#C$%#. Sear"h the

    %nventory table. %f the produ"t is M%6 S$(C@R pla"e a date into the order+sasso"iated A55%GAL#A$ whi"h is seven days from today+s date se S,S#A$= BT.

    %f the produ"t is M2AC@ (5#5#R* pla"e a date into the order+s asso"iatedA55%GAL#A$ whi"h is one month from today+s date. se A##(6$?S3S,S#A$ = E4T

    %f the produ"t is MSPC%AL (5#5R* pla"e a date from today+s date into theorder+s asso"iated A55%GAL#A$ se A##=(6$?S 3S,S#A$* D4T and fulfilthe spe"ial order by inserting a row into the SPC%AL(5#5S table. se the

    (5#56( from the CS$(5#5S table. se the standard order 0uantity3S$#(5#5Q$,4 in the order.