PLSQL CourseWare.doc

download PLSQL CourseWare.doc

of 135

Transcript of PLSQL CourseWare.doc

  • 8/16/2019 PLSQL CourseWare.doc

    1/135

    System Consultant

     1

    ORACLE 9iPL/SQL

    By System Consultant 

  • 8/16/2019 PLSQL CourseWare.doc

    2/135

    System Consultant

     2

    Table of Contents

    Serial No. Topic Name Pae No.

    1 Programming Basics 3

    2 PLSQL Records 21

    3 Cursors 25

    4 PLSQL Tables 34

    5 Ece!tions 41" Procedures 4#

    $ %unctions "1

    & 'racle Su!!lied Pac(ages ""

    # Pac(ages $#

    1) Re* Cursors #4

    11 Ty!es #"

    12 +arrays ##

    13  ,ested Table 1)5

    14 B*ile and L'Bs 111

    15 Triggers 11&

    -ssignments 133

  • 8/16/2019 PLSQL CourseWare.doc

    3/135

    System Consultant

     3

    Prorammin !asics "it# PL/SQL

    PL/SQL features $$$

    PL.SQL is an etension o* SQL

    /t is an a!!lication de0elo!ment language containing !rocedural statements andcommands along it SQL commands

    /t bridges te ga! beteen database tecnology and !rocedural !rogramming

    languages

    /t allos you to !rocess data using *lo control statements li(e iterati0e loo!s and

    conditional brancing

    ses !rocedural tecniues o* control loo!ing and brancing

    Su!!orts SQL i6e6 cursor o!erations ece!tions *unctions and transactional

    commands

    +ariables and constants robust error andling and *unctions

    -dds *unctionality to non7!rocedural tools suc as SQL8%orms

    9e0elo!ers using SQL8%orms can enter an entire PL.SQL bloc( using a singletrigger 

    Structure of PL/SQL

    Stan%ar% PL/SQL co%e sement is calle% a !loc& 

    A bloc& consists of t#ree parts or sections

     –  'eclaration Part

     –  E(ecutable Part

     –  E(ception )an%lin Part

    9eclaration Part

     –  o!tional !art ere 0ariables are de*ined

    Eecutable Part

  • 8/16/2019 PLSQL CourseWare.doc

    4/135

    System Consultant

     4

     –  mandatory !art ic consists o* eecutable statements

    Ece!tion :andling Part

     –  o!tional !art ic consists o* code *or andling errors ;runtime<

      Pl/SQL *iles $ 

    PL.SQL !rograms can be ritten in any editor and sa0ed as *iles it 6sl

    etension

    Can also use =E9> command in SQL8Plus to create a PL.SQL !rogram *ile

    se te =? @*ilenameA> command to eecute a PL.SQL !rogram *ile

    o +ariables $$

    sed to store results o* a uery *or later !rocessing or to calculate 0alues to be

    inserted into database tables

    Can be used anyere in an e!ression eiter in SQL or PL.SQL statements

    ust be declared be*ore re*erencing it in oter statements including oterdeclarati0e statements

    -re declared by s!eci*ying te name along it te dataty!e

    Can be declared to be o* any dataty!e nati0e to 'racle

    Eam!les

      old*are ,BER;5

  • 8/16/2019 PLSQL CourseWare.doc

    5/135

    System Consultant

     5

    Ta&in ,alue from t#e user usin 3

    declare

      I number

      a 0arcar2;1)

  • 8/16/2019 PLSQL CourseWare.doc

    6/135

    System Consultant

     "

    /4 Selectin ename5sal from emp

    6se of more t#an one columns ,alue "it# 7nto clause4/declare

    n 0arcar2;5)

  • 8/16/2019 PLSQL CourseWare.doc

    7/135

    System Consultant

     $

    E(ample

    emprec employee8RO;T:PE1

    A specific fiel% can be reference% usin

    emprec.empnum1

    declare  E em!Mroty!e

      .8roty!e attribute olds te dataty!e o* te columns o* te  entire ro8.

     begin

      select 8 /,T' E

      *rom em!  ere ename F G-RT/,G

      dbmsDout!ut6!utDline;E6sal

  • 8/16/2019 PLSQL CourseWare.doc

    8/135

    System Consultant

     &

      dbmsDout!ut6!utDline;GPassedG

  • 8/16/2019 PLSQL CourseWare.doc

    9/135

    System Consultant

     #

     create table adm

    ;,ame 0arcar2;3)

  • 8/16/2019 PLSQL CourseWare.doc

    10/135

    System Consultant

     1)

      0alues;nmc*7nner !loc& ,ariable ,alue > 00 yD1

      en%1

    %bmsoutput.putline>Outer !loc& ,ariable ,alue > 00 (D1

    en%1

    Scope of ,ariables

    A ,ariable %eclare% in t#e outer bloc& is accessible in t#e inner bloc&. !ut a ,ariable

    %eclare% in t#e inner bloc& is accessible only in t#e inner bloc&.

    %eclare

     outer number1

    bein

     outer - ?@1

      %eclare

      inner number1

      bein

      inner - 9@1  %bmsoutput.putline>7nner !loc& ,ariable ,alue > 00 innerD1

      %bmsoutput.putline>Outer bloc& ,ariable is accessible in t#e inner

    bloc&D1

      %bmsoutput.putline>Outer bloc& ,ariable ,alue > 00 outerD1

    en%1

    %bmsoutput.putline>Outer !loc& ,ariable ,alue > 00 outerD1

  • 8/16/2019 PLSQL CourseWare.doc

    11/135

    System Consultant

     11

    %bmsoutput.putline>7nner !loc& ,ariable ,alue > 00 innerD1

    en%1

    /

    Labels

    7f t#e ,ariables names of t#e outer an% inner bloc&s are same t#en labels #a,e to be

    use% "it#in t#e inner bloc& to a,oi% ambiuity.

    outerbloc&FF

    %eclare

     ( number1

    bein

    innerbloc&FF

    %eclare  ( number - +alue of t#e inner bloc& ( is > 00 (D1

      $$ Gi,in ,alue of ( of t#e inner bloc& to t#e outer bloc& (

      outerbloc&.( -innerbloc&. (1

      en%1

      ( - ( H I@@1

    %bmsoutput.putline>+alue of t#e outer bloc& ( is > 00 (D1

    en%1

    .LOOPS

     Te ability to re!eat or s(i! sections o* a bloc( can be acie0ed it te usage o* 

    L''P or 'T' statements

    Tere are tree *orms o* te L''P statement

     –  L''P

     –  :/LE7L''P

     –  %'R7L''P

    LOOP Statement

    L''P re!eats a seuence o* statements

    Statements to be re!eated are !laced beteen (eyord L''P and E,9 L''P

    it eac iteration o* te loo! te seuence o* statements is eecuted ten

    control resumes at te to! o* te loo!

    L''P

    statementsE,9 L''P

    EJ7T Statement

  • 8/16/2019 PLSQL CourseWare.doc

    12/135

    System Consultant

     12

    sed to com!lete a loo! i* *urter !rocessing in a loo! is undesirable or

    im!ossible

    Tere are to *orms o* te E/T statement

     –  E/T

     –  E/T7:E,

    %orces a loo! to com!lete unconditionally

    ust be !laced inside a loo!

    L''P

    statements

    /% @conditionA T:E,E/T 77 eit loo! immediately

    E,9 /%

    E,9 L''P77 control resumes ere

    Eam!le o* Loo!  /4To s#o" < to

  • 8/16/2019 PLSQL CourseWare.doc

    13/135

    System Consultant

     13

    *OR LOOP

     -d0antages 77

      1< ,o need o* declaring loo! 0ariable

      2< ,o need o* gi0ing condition

     3< ,o need o* u!dation statement ;increment or decrement < 4

  • 8/16/2019 PLSQL CourseWare.doc

    14/135

    System Consultant

     14

    total number;4

  • 8/16/2019 PLSQL CourseWare.doc

    15/135

    System Consultant

     15

    E(ample < of "#ile loop to s#o" < to

  • 8/16/2019 PLSQL CourseWare.doc

    16/135

    System Consultant

     1"

    !asic Loop

    9eclare

      number

     Begin

      F 1  Loo!

      dbmsDout!ut6!utDline;

  • 8/16/2019 PLSQL CourseWare.doc

    17/135

    System Consultant

     1$

    %eclare

      number1

      m number1

      % number1

      %is ,arc#ar=1

      insert into %iscount%etails

      ,alues5m5%isD1

      % - % $

  • 8/16/2019 PLSQL CourseWare.doc

    18/135

    System Consultant

     1&

     –  *rom a bloc( to an eecutable statement

     –   branc *rom an ece!tion andler into an enclosing bloc( 

    Trans*er o* control using 'T' statement is ,'T alloed in te *olloing

     !laces

     –  *rom itin one /% statement or loo! clause to anoter 

     –  *rom an enclosing bloc( into a sub7bloc( 

     –  *rom an ece!tion andler into te current bloc( 

     –  out o* a sub!rogram

     –  to (eyords

    E(amples of GOTO  

    1< create table !rec;name 0arcar2;2)

  • 8/16/2019 PLSQL CourseWare.doc

    19/135

    System Consultant

     1#

      end

    ;ron usae of oto

    declare

    number begin

    F #)

    @@s1AA dbmsDout!ut6!utDline;GS1G

  • 8/16/2019 PLSQL CourseWare.doc

    20/135

    System Consultant

     2)

     

    dbmsDout!ut6!utDline;+E6eno HH G 7 G HH +E6name HH G7G HH+E6s

  • 8/16/2019 PLSQL CourseWare.doc

    21/135

    System Consultant

     21

    En%1

      7777777777777777777777777777777777777

  • 8/16/2019 PLSQL CourseWare.doc

    22/135

    System Consultant

     22

    8Ro"type "it# Recor%

    %eclare

    type t< is recor%

    e% emp8ro"type5

     %% %ept8ro"typeD1

    +T< tACCO6NT7NG>1

    %bmsoutput.putline+T

  • 8/16/2019 PLSQL CourseWare.doc

    23/135

    System Consultant

     23

     –  %ETC:

     –  CL'SE

    Cursor must be declared be*ore it can be re*erenced using te 'PE, CL'SE or

    %ETC: statements

    T#e OPEN Statement

    /nitialiIes or o!ens a cursor 

    Cursor must be o!ened be*ore any ros are returned by te uery

    'PE, @cursornameAEam!le 77

      'PE, em!Dcur

    T#e *ETC) Statement

    Can be eecuted re!eatedly until all ros a0e been retrie0ed

    %ETC: @cursornameA /,T' 0ar1 Y 0ar,

    'R %ETC: @cursornameA /,T' recordD0ariable

    Eam!le

    %ETC: em!Dcur /,T' mrec

    T#e CLOSE Statement

    Closes te cursor and ma(es te acti0e set unde*ined

    CL'SE @cursornameA Eam!le

    CL'SE em!Dcur

    'nce a cursor is closed it can be reo!ened by using te 'PE, statement

    Attributes of E(plicit Cursors

    E0ery cursor as *our attributes tat can be used to access te cursorUs contet

    area

     –  M,'T%',9

     –  M%',9

     –  MR'C',T

     –  M/S'PE,

    To use tese attributes sim!le a!!end tem to te name o* te cursor  M,'T%',9

     –  e0aluates to TRE i* last %ETC: *ailed because no more ros ere

    a0ailable

     –  e0aluates to %-LSE i* last %ETC: returned a ro

    M%',9

     –  e0aluates to TRE i* last %ETC: returned a ro

  • 8/16/2019 PLSQL CourseWare.doc

    24/135

    System Consultant

     24

     –  e0aluates to %-LSE i* last %ETC: *ailed because no more ros ere

    a0ailable

    MR'C',T

     –  returns te number o* ros %ETC:ed *rom te acti0e set so *ar 

    M/S'PE,

     –  e0aluates to TRE i* an e!licit cursor is o!en

     –  e0aluates to %-LSE i* an e!licit cursor is closed

    Eam!les o* Cursor

  • 8/16/2019 PLSQL CourseWare.doc

    25/135

  • 8/16/2019 PLSQL CourseWare.doc

    26/135

    System Consultant

     2"

      else

      Open cf1  dbmsDout!ut6!utDline;GCursor is no o!enedG

  • 8/16/2019 PLSQL CourseWare.doc

    27/135

    System Consultant

     2$

      *etc c* into

      i* c*Mrocount F 3 ten  dbmsDout!ut6!utDline;6em!noHHG7GHH6enameHHG7GHH6salHHG7GHH6de!tno

  • 8/16/2019 PLSQL CourseWare.doc

    28/135

    System Consultant

     2&

      Cursor c* is

      select 8  *rom em!

      ere sal AF 3)))

    Begin

      %or mrec in c*   Loo!

      dbmsDout!ut6!utDline;mrec6enameHHG GHHmrec6salHHG GHHmrec6de!tnoD1  L''P

      %ETC: C% /,T'   E/T :E, C%M,'T%',9

      dbmsDout!ut6!utDline;6ename

  • 8/16/2019 PLSQL CourseWare.doc

    29/135

    System Consultant

     2#

    o!en c* >CLER>D

      L''P  %ETC: C% /,T'

      E/T :E, C%M,'T%',9

      dbmsDout!ut6!utDline;6ename

  • 8/16/2019 PLSQL CourseWare.doc

    30/135

    System Consultant

     3)

    Cursor *OR 6P'ATE O* an% C6RRENT O*

    CRRE,T '% clause is used in an P9-TE or 9ELETE statement to re*er to

    te current ro o* te cursor 

    Te cursor must be declared it te %'R P9-TE '% clause and must be o!en

    and !ositioned on a ro /* te cursor is not o!en CRRE,T '% clause results in an error 

    ?D E(ample of  Cursor *OR 6P'ATE O* an% C6RRENT O* 

    create table esal

    ;em!no number sal number

  • 8/16/2019 PLSQL CourseWare.doc

    31/135

    System Consultant

     31

      eit en c*Mnot*ound

      /* 6Sal AF 1"))) Ten

      6Sal F 2))))

      Els/* 6Sal AF 14))) Ten  6Sal F 1&2))

      Els/* 6Sal AF 12))) Ten

      6Sal F 1"$))

      Els/* 6Sal AF 1)))) Ten  6Sal F 135))

      Els/* 6Sal AF &))) Ten  6Sal F 11)))

     Els/* 6Sal AF "))) Ten

      6Sal F #5))

     

    Els/* 6Sal AF 4))) Ten

      6Sal F $5))

      Else

      6Sal F 5))) 

    End /*

      !date esal

      set sal F 6Sal

      ;#ere Current Of cf1  End Loo!

    End

    7mplicit Cursors

    • -utomatically de*ined and o!ened by 'racle to !rocess eac

    SQL statement

    most recently o!ened contet area is re*erred to as a SQLMUcursor 

    Attributes of 7mplicit Cursors

  • 8/16/2019 PLSQL CourseWare.doc

    32/135

    System Consultant

     32

    -ltoug 'PE, CL'SE and %ETC: statements cannot be used to mani!ulate

    te SQLM cursor te attributes can be used to access its contet area

    -ttributes e0aluate to ,LL be*ore te cursor is o!ened automatically

    T#e follo"in four cursor attributes can be use% to access t#e SQL8

    cursors conte(t area

    SQL8NOT*O6N' SQL8*O6N'

    SQL8RO;CO6NT

    SQL87SOPEN

    SQL8NOT*O6N'

    e0aluates to TRE i* an /,SERT P9-TE or 9ELETE statement

    a**ected no ros else it e0aluates to %-LSE

    SQL8*O6N'

    logical o!!osite o* SQLM,'T%',9

    e0aluates to TRE i* an /,SERT P9-TE or 9ELETE a**ected one or

    more ros else it e0aluates to %-LSE

    SQL8RO;CO6NT

     –  returns te number o* ros a**ected by an /,SERT P9-TE or 9ELETE

    statement SQL87SOPEN

     –  'racle automatically closes an im!licit cursor a*ter eecuting its

    associated SQL statement

     –  %or an im!licit cursor SQLM/S'PE, alays e0aluates to %-LSE

    9D E(ample of 7mplicit Cursors

    Begin

      9elete *rom em!

      ere ename F GJnameG

      /* SQLM%ound Ten

      dbmsDout!ut6!utDline;GRecord *ound and it is deletedG

  • 8/16/2019 PLSQL CourseWare.doc

    33/135

    System Consultant

     33

    1)< /m!licit Cursor *or rocount

    9eclare

    C number F )

    Begin  !date Em!

      set sal F sal 5))  ere de!tno F Jde!tno

    /47f no recor% is up%ate% since t#e %eptno supplie% is "ron t#en i,in

    t#e customise% error messae.4/

      /* SQLMRocount F ) ten

      dbmsDout!ut6!utDline;G,o records are u!dated since te de!artment number entered

    is not in te table6G

  • 8/16/2019 PLSQL CourseWare.doc

    34/135

    System Consultant

     34

      B/,-RND/,TEER is a s!ecial data ty!e ic can be gi0en only to te

    column o* PL.SQL table *or itUs indeing !ur!ose to store and retrie0e 0alues6  Range o* binaryDinteger is 7214$4&3"4$ to 214$4&3"4$

    $< SiIe is unconstrained ;Table siIe gros as te ros are added to te table

  • 8/16/2019 PLSQL CourseWare.doc

    35/135

    System Consultant

     35

      i F i 1

      End Loo!  Close c*

    .8,o retrie0ing te names *rom te 0name !lsl table using *or loo!68.  %or n in 1660ros

      Loo!  dbmsDout!ut6!utDline;G,ame is GHH0name;n

  • 8/16/2019 PLSQL CourseWare.doc

    36/135

    System Consultant

     3"

      end i*

     dbmsDout!ut6!utDline;GTe total number o* elements in d are GHH d6count

  • 8/16/2019 PLSQL CourseWare.doc

    37/135

    System Consultant

     3$

    EJCEPT7ONS

    7ntro%uction to E(ceptions

    -n error condition is called an Ece!tion

    en an error occurs an ece!tion is raised i6e6 normal eecution sto!s andcontrol trans*ers to te ece!tion andling !art o* te PL.SQL bloc( or

    sub!rogram

    To andle raised ece!tions se!arate routines called ece!tion andlers are

    ritten

    Tere are to ty!es o* ece!tions

     –  Pre7de*ined ece!tions ;/nternal Ece!tions<

     –  ser7de*ined ece!tions

    Nou cannot declare an ece!tion tice in te same bloc( but can declare te

    same ece!tion in to di**erent bloc(s Ece!tions declared in a bloc( are local to tat bloc( and global to all its sub7

     bloc(s

    Enclosing bloc(s cannot re*erence ece!tions declared in a sub7bloc( because

     bloc(s can only re*erence local or global ece!tions

    Pre%efine% E(ceptions

    -re im!licitly raised ene0er a PL.SQL bloc( 0iolates an 'racle rule or eceeds

    a system7de!endent limit

    E0ery 'racle error as a number but ece!tions must be andled by name

    PL.SQL !rede*ines some common 'racle errors as ece!tions

    Tese !rede*ined ece!tions are declared globally by PL.SQL

    Some Pre7de*ined Ece!tions CRS'RD-LRE-9ND'PE,

     ,'D9-T-D%',9

    T''D-,NDR'S

    +-LEDERR'R 

    KER'D9/+/9E

    ore tan one ece!tion can be andled in a single ece!tion andler by

    se!arating tem it te (eyord 'R ECEPT/',

    :E, ,'D9-T-D%',9 'R T''D-,NDR'S T:E,statements:E, 'T:ERS T:E,

    statements

    E,9

  • 8/16/2019 PLSQL CourseWare.doc

    38/135

    System Consultant

     3&

    Eam!les o* Ece!tion andling  

  • 8/16/2019 PLSQL CourseWare.doc

    39/135

    System Consultant

     3#

    Ece!tion  en KER'D9/+/9E ten

      dbmsDout!ut6!utDline;GCannot di0ide by Iero[[[G

  • 8/16/2019 PLSQL CourseWare.doc

    40/135

    System Consultant

     4)

    Ece!tion  en tooDmanyDros ten

      dbmsDout!ut6!utDline;Gore tan one 0alueG

  • 8/16/2019 PLSQL CourseWare.doc

    41/135

    System Consultant

     41

    create table errorDlog;errorDnumber number errorDmessage 0arcar2;255

  • 8/16/2019 PLSQL CourseWare.doc

    42/135

    System Consultant

     42

    6ser$%efine% E(ceptions

    ser7de*ined ece!tions need to be de*ined in te declarati0e !art o* a PL.SQL

     bloc( sub!rogram or database trigger 

    9eclared by naming te ece!tion and de*ining it as dataty!e ECEPT/',

    Eam!le9ECL-RE

     !astDdue ECEPT/',IeroDerror ECEPT/',

    Li(e 0ariables user7de*ined ece!tions must be gi0en names

    nli(e 0ariables user7de*ined ece!tions cannot be assigned 0alues and cannot be

    used in SQL statements

    Tey need to be raised e!licitly using te R-/SE statement

    - bloc( sould R-/SE an ece!tion only en an error ma(es it im!ossible or

    im!ractical to *inis !rocessing

    R-/SE statement *or a gi0en e!ression can be coded anyere itin te sco!e

    o* tat e!ression

    /% mrec6ssD*are @F ) T:E,

    R-/SE IeroDerrorE,9 /%

    -n ece!tion raised inside a andler immediately !ro!agates to te enclosing

     bloc( ic is searced to *ind a andler *or te nely raised ece!tion

    %rom tere on te ece!tion !ro!agates normally

    To re7raise an ece!tion !lace a R-/SE statement in its local andler 

  • 8/16/2019 PLSQL CourseWare.doc

    43/135

    System Consultant

     43

    E(ample of E(ception ,ariable usin Raise &ey "or%

    declare

     ! number

      n number F "  si number

      r number F 1)65 E ece!tion

    Begin

      ! F J!  i* ! @ 1)) ten

      raise E

      elsesi F ;! 8 n 8 r< . 1))

      dbmsDout!ut6!utDline;GTe Sim!le /nterest is GHH si

  • 8/16/2019 PLSQL CourseWare.doc

    44/135

    System Consultant

     44

      end i*

     end  777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777

    E(ample of   Raiseapplicationerror an% error #an%lin toet#er  

    declare  number

     begin  F GJG

     i* @ ) ten

     raiseDa!!licationDerror;72)))#GtyG

  • 8/16/2019 PLSQL CourseWare.doc

    45/135

    System Consultant

     45

    PROCE'6RESA%,antaes of Subprorams

    Pro0ide Etensibility

     –  PL.SQL language can be tailored to suit te needs o* te a!!lication

    Promote reusability and maintainability

     –  'nce 0alidated tey can be used it con*idence in any number o*

    a!!lications

     –  Sim!li*ies maintenance.enancement as sub!rogram is only a**ected i*

    de*inition canges

    Pro0ide odularity

     –  Program can be bro(en don into manageable ell7de*ined logical

    modules

     –  Su!!orts to!7don design and ste!ise re*inement a!!roac to !roblem

    sol0ing

    -id in abstraction

     –  -llo mental se!aration *rom !articulars

     –  Stubs allo !rogrammers to de*er de*inition o* !rocedures.*unctions until

    main !rogram is tested and debugged

    Procedure !er*orms s!eci*ic action

    Stored in database and can be in0o(ed or called by any anonymous bloc(  Can ta(e !arameters

    9ataty!e s!eci*ier in !arameter declaration must be unconstrained

    :as to !arts

     –  S!eci*ication

    •  begins it (eyord PR'CE9RE ends it !rocedure name or

     !arameter list

     –  Body

    •  begins it (eyord /S ends it (eyord E,9 *olloed by

    o!tional !rocedure name

    CRE-TE V'R REPL-CEW PR'CE9RE @!rocedurenameA V;!arameter1 Y

     !arameter,

  • 8/16/2019 PLSQL CourseWare.doc

    46/135

    System Consultant

     4"

    ece!tion andlersW

    E,9 V@!rocedurenameAW

     !arameter stands *or 

    0ariablename V/,H'TH/, 'TW dataty!e V\F H 9E%-LT] 0alueW

    ;#en a proce%ure is create%5 Oracle automatically performs t#ese steps –  Compiles t#e proce%ure

     –  Stores t#e compile% co%e

     –  Stores t#e proce%ure in t#e %atabase

    T#e PL/SQL compiler use% to compile t#e co%e

    7f an error occurs5 t#e proce%ure is create% but it is in,ali%

    Enforce 'ata Security

     –  Can rant users access to a proce%ure t#at ueries a table5 but not

    rant access to t#e table itself 

    7mpro,e 'atabase Performance –  Less amount of information sent o,er net"or& 

     –  Compilation not reuire% to e(ecute co%e

     –  Proce%ure present in s#are% pool so retrie,al from %is& not reuire%

    emory Sa,ins

     –  Only one copy of proce%ure nee%s to be loa%e% in memory for

    e(ecution by multiple users

    7ncrease in 'e,elopment Pro%ucti,ity

     –  Can a,oi% re%un%ant co%in an% increase pro%ucti,ity5 by "ritin a

    sinle proce%ure

    7nterity

     –  Proce%ures nee% to be teste% only once5 to uarantee t#at it returns

    accurate results

    Callin a Store% Proce%ure

    Can call a proce%ure in a PL/SQL statement

     –  E(ample

    branc#sumBN:D1

    Can call a proce%ure from SQL4Plus

     –  E(ampleSQLF EJEC6TE branc#sumBN:D1

  • 8/16/2019 PLSQL CourseWare.doc

    47/135

    System Consultant

     4$

    E(amples of Proce%ures  

  • 8/16/2019 PLSQL CourseWare.doc

    48/135

    System Consultant

     4&

    3< Gi,in %efault ,alues to t#e parameters

    'ue to %efault ,alue i,en t#e parameter becomes optional also.

    !ut if any ot#er ,alue is i,en t#en it ta&es it.

    create or re!lace !rocedure !r3 ;Eno em!6em!noMty!e , em!6enameMty!e S em!6sal

    Mty!e dno em!6de!tnoMty!e 'E*A6LT

  • 8/16/2019 PLSQL CourseWare.doc

    49/135

    System Consultant

     4#

    e(ec %eptrecploc F >Pune>5 p%eptno F 5 -paymentD774

  • 8/16/2019 PLSQL CourseWare.doc

    50/135

    System Consultant

     5)

    6sin local ,ariable for out parameter "#en proce%ure is calle% insi%e anot#er

    bloc&.

    create or re!lace !rocedure !1;n in em!6enameMty!e s out emp.sal8type<

    is begin

    select sal into s

    *rom em!ere ename F n

    end

    declare

    em!6salMty!e

     begin !1;GS/T:G(D1dbmsDout!ut6!utDline;

  • 8/16/2019 PLSQL CourseWare.doc

    51/135

    System Consultant

     51

    7t #as to be calle% insi%e a plsl bloc&. 7t actually i,es t#e suare ,alue to t#e

    ,ariable of t#at plsl bloc&.

     7n s#ort 7N O6T type of paramter ma&es a proce%ure similar to function5 as t#e

    function also returns t#e ,alue to t#e callin en,ironment.4/

     b<

    declare

    a number

    Begin  a F Ja

      !r";as status is of 7N O6T. So 7N means t#e user

    input ,alue an% O6T means t#e c#anes suare fiure %ue to t#e proce%ure pr.After t#e proce%ure is calle% "it# a as parameter t#en a ,alue ets c#ane%. At t#is

    time a acts as a O6T parameter5 since t#e proce%ure is i,in t#e c#ane% ,alue to

    a.4/

      dbmsDout!ut6!utDline;a

  • 8/16/2019 PLSQL CourseWare.doc

    52/135

    System Consultant

     52

    D 7N O6T e(ample from "it# respect to %atabase

    aD

    create or re!lace !rocedure salrise;salary /, 'T number< is

    Begin

    salary F salary ;salary 8 )62)

  • 8/16/2019 PLSQL CourseWare.doc

    53/135

    System Consultant

     53

    'eclarin Sub proce%ures

    Create table logDtable;username 0arcar2;3)

  • 8/16/2019 PLSQL CourseWare.doc

    54/135

    System Consultant

     54

    )an%le% or 6n#an%le% E(ceptions for a proce%ure ettin calle% in anot#er.

    create or replace proce%ure innerproc( number5y numberD

    is

    bein%bmsoutput.putline(/yD1

    e(ception

    "#en 2ero%i,i%e t#en

    %bmsoutput.putline>y cannot be neati,e>D1

     en%1

    create or replace proce%ure outerproc

    as

    bein

    %bmsoutput.putline>AA>D1

    /4Callin t#e innerproc prece%ure.4/innerproc5@D1

    %bmsoutput.putline>ccD1

    e(ception

    "#en ot#ers t#en

    %bmsoutput.putline>A Run Time Error #as occurre%.>D1

    en%1

    7f t#e innerproc proce%ure is not #a,in any error #an%ler t#en t#e error #an%ler

    outer proce%ure ets e(ecute%.

    A6T)7' C6RRENT6SER 

    /* a !rocedure reads data *rom table and !er*orms some 9L ten -T:/9CRRE,TDSER is a!!licable6 9ue to tis clause te oner o* te !rocedure only can

    eecute tis !rocedure and read or !er*orm 9L6 E0en i* te oner as gi0en eecute

     !ri0ilege o* suc a !rocedure to any oter user still te oter user cannot eecute te

     !rocedure6 So *rom data security !oint o* 0ie tis clause is el!*ul6Te *olloing scenario ill e!lain tis conce!t6

    Case stu%y $$$$

    Lo on as System/anaer '!A LoinD

    create user a< i%entifie% by a

  • 8/16/2019 PLSQL CourseWare.doc

    55/135

    System Consultant

     55

    rant resource5 create session to a=1

    $$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$

    ;it#out A6T)7' C6RRENT6SER  

    conn a

  • 8/16/2019 PLSQL CourseWare.doc

    56/135

    System Consultant

     5"

  • 8/16/2019 PLSQL CourseWare.doc

    57/135

    System Consultant

     5$

    *unctions

    Sub!rogram tat returns a 0alue

    :a0e a RETR, clause

    Stored in database and can be in0o(ed or called by any anonymous bloc( 

    enerally ta(e !arameters

    9ataty!e s!eci*ier in !arameter declaration must be unconstrained

    :as to !arts

    S!eci*ication

     begins it (eyord %,CT/', ends it RETR, clause

    Body

     begins it (eyord /S ends it (eyord E,9 *olloed by

    o!tional *unction name

    Synta(  

    CRE-TE V'R REPL-CEW %,CT/', @*unctionnameA V;argument1 Y argument,

  • 8/16/2019 PLSQL CourseWare.doc

    58/135

    System Consultant

     5&

    cardays F dayD*n;3

  • 8/16/2019 PLSQL CourseWare.doc

    59/135

    System Consultant

     5#

    9eclare

      number y car;3)

  • 8/16/2019 PLSQL CourseWare.doc

    60/135

    System Consultant

     ")

    ;name 0arcar2;1)

  • 8/16/2019 PLSQL CourseWare.doc

    61/135

    System Consultant

     "1

    $$ *irst %eclare t"o bin% ,ariables location an% %eptname

    $$SQLF ,ariable %eptname ,arc#ar=

  • 8/16/2019 PLSQL CourseWare.doc

    62/135

    System Consultant

     "2

    ORACLE S6PPL7E' PACAGES

    • '!SSQL

    • '!S''L

    • '!SO!

    • 6TL*7LE

  • 8/16/2019 PLSQL CourseWare.doc

    63/135

    System Consultant

     "3

    '!SSQL Pac&aeWhat Is Dynamic SQL?

    'ynamic SQL enables you to "rite prorams t#ose reference SQL statements "#ose

    full te(t is not &no"n until runtime. Be*ore discussing dynamic SQL in detail a clear

    de*inition o* static SQL may !ro0ide a good starting !oint *or understanding dynamicSQL6 Static SQL statements do not cange *rom eecution to eecution6 Te *ull tet o*

    static SQL statements are (non at com!ilation ic !ro0ides te *olloing bene*its

    • Success*ul com!ilation 0eri*ies tat te SQL statements re*erence 0alid database

    obXects6

    • Success*ul com!ilation 0eri*ies tat te necessary !ri0ileges are in !lace to access

    te database obXects6

    • Per*ormance o* static SQL is generally better tan dynamic SQL6

    Because o* tese ad0antages you sould use dynamic SQL only i* you cannot use staticSQL to accom!lis your goals or i* using static SQL is cumbersome com!ared to

    dynamic SQL6 :oe0er static SQL as limitations tat can be o0ercome it dynamic

    SQL6 Nou may not alays (no te *ull tet o* te SQL statements tat must be eecuted

    in a PL.SQL !rocedure6 Nour !rogram may acce!t user in!ut tat de*ines te SQLstatements to eecute or your !rogram may need to com!lete some !rocessing or( to

    determine te correct course o* action6 /n suc cases you sould use dynamic SQL6

    %or eam!le a re!orting a!!lication in a data areouse en0ironment migt not (note eact table name until runtime6 Tese tables migt be named according to te starting

    mont and year o* te uarter *or eam!le INV_01_1997 INV_04_1997 INV_07_1997

    INV_10_1997 INV_01_1998 and so on6 :ou can use %ynamic SQL in your reportin

    application to specify t#e table name at runtime.

    Nou migt also ant to run a com!le uery it a user7selectable sort order6 /nstead o*

    coding te uery tice it di**erent ORDER BY clauses you can construct te uery

    dynamically to include a s!eci*ied ORDER BY clause6

    9ynamic SQL !rograms can andle canges in data de*initions itout te need to

    recom!ile6 Tis ma(es dynamic SQL muc more *leible tan static SQL6 9ynamic SQL

    lets you rite reusable code because te SQL can be easily ada!ted *or di**erent

    en0ironments6

    'ynamic SQL also lets you e(ecute %ata %efinition lanuae ''LD statements an%

    ot#er SQL statements t#at are not supporte% in purely static SQL prorams.

  • 8/16/2019 PLSQL CourseWare.doc

    64/135

    System Consultant

     "4

    Why Use Dynamic SQL?

    Nou sould use dynamic SQL in cases ere static SQL does not su!!ort te o!eration

    you ant to !er*orm or in cases ere you do not (no te eact SQL statements tatmust be eecuted by a PL.SQL !rocedure6 Tese SQL statements may de!end on userin!ut or tey may de!end on !rocessing or( done by te !rogram6 Te *olloing

    sections describe ty!ical situations ere you sould use dynamic SQL and ty!ical

     !roblems tat can be sol0ed by using dynamic SQL

    Executing DDL and SCL Statements in PL/SQL

    /n PL.SQL you can only eecute te *olloing ty!es o* statements using dynamic SQL

    rater tan static SQL

    9ata de*inition language ;99L< statements suc as CREATE DROP GRANT andREVOKE 

    • Session control language ;SCL< statements suc as ALTER SESSION and SET ROLE

    Executing Dynamic Queries

    Nou can use dynamic SQL to create a!!lications tat eecute dynamic ueries ose *ull

    tet is not (non until runtime6 any ty!es o* a!!lications need to use dynamic ueries

    including

    • -!!lications tat allo users to in!ut or coose uery searc or sorting criteria at

    runtime• -!!lications tat allo users to in!ut or coose o!timiIer ints at run time

    • -!!lications tat uery a database ere te data de*initions o* tables are

    constantly canging

    • -!!lications tat uery a database ere ne tables are created o*ten

  • 8/16/2019 PLSQL CourseWare.doc

    65/135

    System Consultant

     "5

    9BSDSQL is used to rite dynamic SQL in stored !rocedure and to !arse 99Lstatements6

    Some Procedures and %unctions in 9BSDSQL !ac(age are  

    OpenCursor  '!ens a ne cursor and assigns a cursor /9 number6

    PARSE  Parses te 99L or 9L statements i6e6 it cec(s te synta and associates itit te o!ened cursor6 /n case o* 99L statements tey are eecuted immediately a*ter

     !arsing6

    P-RSE ;/9 number o* te cursor 99L or 9L statement languageD*lag<

    languag_!lag

     9etermines o 'racle andles te SQL statement6 Te *olloingo!tions are recogniIed

    • V" ;or 0< s!eci*ies 0ersion " bea0ior6

    • NATIVE ;or 1< s!eci*ies normal bea0ior *or te database to

    ic te !rogram is connected6

    • V7 ;or #< s!eci*ies 'racle$ bea0ior6

    EJEC6TE  Eecutes te SQL statement and returns te number o* ros !rocessed6

    Es!ecially suitable *or (ee!ing trac( o* count o* ros a**ected by a 9L statement6

    create or re!lace !rocedure dro!Dtable;!Dtablename in 0arcar2<

    isC ,BER

     begin

    c F 9BSDSQL6'PE,DCRS'R9BSDSQL6P-RSE;CG9R'P T-BLE G HH !Dtablename 9BSDSQL6,-T/+E

  • 8/16/2019 PLSQL CourseWare.doc

    66/135

    System Consultant

     ""

    create or re!lace !rocedure deleteDros;tableDname 0arcar2<

    is c number

     rosDdeleted number begin

      c F 9BSDSQL6'PE,DCRS'R

      9BSDSQL6P-RSE;c G9elete *rom G HH tableDname 9BSDSQL6,-T/+E

  • 8/16/2019 PLSQL CourseWare.doc

    67/135

    System Consultant

     "$

    '!S''L Pac&ae

    Scenario of recompilation for a proce%ure  

    dro! table t1

    create table t1;a numberPJ1

    alter !rocedure !1 com!ile 'R Eec !1

    select status from userobUects

    "#ere obUectname>PJ1

  • 8/16/2019 PLSQL CourseWare.doc

    68/135

    System Consultant

     "&

    9BSD99L6-LTERDC'P/LE;obXectDty!eU oner nameU obXectDname<

    'bXectDty!e can be a !rocedure *unction !ac(age s!eci*ication !ac(age body or a

    trigger only6

    create or re!lace !rocedure com!ileD!rocedure;!rocedureDname 0arcar2<

    as begin

     '!S''L.ALTERCOP7LE>PROCE'6RE>5>SCOTT>5 proce%urenameD1

     dbmsDout!ut6!utDline;GTe !rocedure G HH !rocedureDname HH G is recom!iledG

  • 8/16/2019 PLSQL CourseWare.doc

    69/135

    System Consultant

     "#

    '!SO! Pac&ae

    Enables te sceduling and eecution o* PL.SQL !rograms6

    Submit is te !rocedure o* 9BSDZ'B !ac(age6

    Te !arameters o* Submit !rocedure are 777

    Z'B niue identi*ier o* te Xob ;'ut !arameter<:-T PL.SQL code to eecute as a Xob

     ,ETD9-TE ,et eecution date o* te Xob

    /,TER+-L 9ate *unction to com!ute te net eecution date o* a Xob6

    Eam!le  

    E0ery net day a ne record sould get added in te table dXt16

    Create table dXt1;a number

  • 8/16/2019 PLSQL CourseWare.doc

    70/135

    System Consultant

     $)

    /n te init6ora *ile O!Q6E6EPROCESSES n  as to

     be settedn can be beteen 1 and 3"6

    Cange te system date to te net date6 Te t1 table gets te net

    0alue o* te seuence6

    -gain re!eat te !rocess6

    /m! setting  Uobueueprocesses n n bet"een < an% D in t#e init.ora file

    Select Xobat *rom userDXobs

    Eec dbmsDXob6Bro(en;1true< 1 is Xob no

    Eec dbmsDXob6Remo0e;1<

    9bmsDXob6cange;Xobno at netDdate inter0al<

    Zobno cannot be canged6/* tere is no cange *or at netDdate inter0al ten s!eci*y ,LL

     %or having interval of &' seconds it will be (Ssdate ) !+ *&'*&'""/ 

  • 8/16/2019 PLSQL CourseWare.doc

    71/135

    System Consultant

     $1

    6TL*7LE Pac&ae

    TLD%/LE !ac(age is used to rite data to o!erating system *iles suc as

    tet *iles ord *iles ecel *iles etc6

    Te data *rom te oracle table is trans*erred to te o6s6 *iles6 So e can

    generate a re!ort o* 'racle data in a non7oracle *ormat6

    embers o* TLD%/LE Pac(age are as *ollos  

    FOPEN uncti!n

    Tis *unction o!ens a *ile *or in!ut or out!ut6 Te *ile location must be anaccessible directory as de*ined in te instanceGs initialiIation !arameter

    TLD%/LED9/R6 Te com!lete directory !at must already eist it is not

    created by %'PE,6

    /t ta(es 3 !arameters

    16 9irectory name Te !at

    26 %ile name ;6tt 6doc6ls<

    36 '!enDode 

    a6 rU Read Tet b6 U77 rite Tet

    c6 aU -!!end Tet

    PU"F #r!cedure

    Tis !rocedure is a *ormatted PT !rocedure6 /t or(s li(e a limited

     !rint*;

  • 8/16/2019 PLSQL CourseWare.doc

    72/135

    System Consultant

     $2

    FCLOSE #r!cedure

    Tis !rocedure closes an o!en *ile identi*ied by a *ile andle6

    NEW$LINE #r!cedure (Can specify how many blank lines are required.Default is 1)

    Tis !rocedure rites one or more line terminators to te *ile identi*ied by

    te in!ut *ile andle6 Tis !rocedure is se!arate *rom PT because te line

    terminator is a !lat*orm7s!eci*ic caracter or seuence o* caracters6

    Syntax'TL_(ILE)NE*_LINE +  !,l IN (ILE_TYPE-  l,n% IN NAT'RAL ./ 2

  • 8/16/2019 PLSQL CourseWare.doc

    73/135

    System Consultant

     $3

    Eam!le o* generating a tet *ile o* salary status *rom te em! table6

    create or replace proce%ure salstatus

    pfile%ir in ,arc#ar=5 pfilename in ,arc#ar=D

    is

    ,file#an%le 6TL*7LE.*7LET:PE1 Cursor empinfo is

      select ename5sal5%eptno

      from emp

      or%er by sal %esc1

    !ein

     ,file#an%le - 6TL*7LE.*OPENpfile%ir5pfilename5>">D1

     6TL*7LE.P6T*,file#an%le5>SALAR: REPORT - GENERATE' ON

    8sXn>5S:S'ATED1

     6TL*7LE.NE;L7NE,file#an%leD1

     for ,emprec in empinfo

    LOOP  6TL*7LE.P6T*,file#an%le5>'EPARTENT- 8s Xn>5

    ,emprec.%eptnoD1

      6TL*7LE.P6T*,file#an%le5> Employee-8s earns- 8sXn>5

    ,emprec.ename5,emprec.salD1

      EN' LOOP1

      6TL*7LE.P6T*,file#an%le5 >444 EN' O* REPORT 444>D1

      6TL*7LE.*CLOSE,file#an%leD1

    EJCEPT7ON

      ;)EN 6TL*7LE.7N+AL7'*7LE)AN'LE T)EN

      raiseapplicationerror$=@@@7n,ali% *ile>D1  ;)EN 6TL*7LE.;R7TEERROR  T)EN

      raiseapplicationerror$=@@@=5>6nable to "rite file>D1

     En%1

  • 8/16/2019 PLSQL CourseWare.doc

    74/135

    System Consultant

     $4

    Ste!s *or eecuting te !rocedure are as *ollos  

    16 /n te init6ora *ile o* te database te *ile location as to be de*ined

    as a 0alue o* TLD%/LED9/R 

    '!en te init6ora *ile and add te !ro!erty as *ollos7

    TLD%/LED9/R F C^-BC

    Step 0 is onl re1uired for earl version. 2f director ob3ect is not

    created then 4#L5%2L65728 path is re1uired"

    26 Create a *older -BC in C dri0e6

    36 Create a directory obXect in database as  

      create directory 91 as GC^-BCG

      9irectory is a nonscema database obXect tat !ro0ides a ay *or

    administering te o6s6 *iles troug 'racle Ser0er #i6

    - 9irectory s!eci*ies an alias *or te actual o6s6 !at 6

    46 Eecute te !rocedure

     

    Eec SalDStatus;G91GGa16ttG

  • 8/16/2019 PLSQL CourseWare.doc

    75/135

    System Consultant

     $5

    Pac&aes

     9atabase obXects tat grou! logically related PL.SQL ty!es obXects and

    sub!rograms

    Tey cannot be called !assed !arameters to or nested Tere are to !arts

     –  S!eci*ication

     –  Body

    A%,antaes of Pac&aes

    odularity

     –  allos enca!sulation o* related ty!es obXects and sub!rograms in a named

    PL.SQL module

     –  easy to understand it sim!le clear and ell de*ined inter*aces

     – el!s in a!!lication de0elo!ment

    Easier -!!lication 9esign

     –  en designing a!!lications only inter*ace in*ormation in !ac(age

    s!eci*ications initially reuired

     –  can code and com!ile s!eci*ication itout body

     –  stored sub!rograms re*erencing te !ac(age can be com!iled as ell

     –  need not de*ine !ac(age bodies until ready to com!lete te a!!lication

    /n*ormation :iding

     –  can s!eci*y ic ty!es items and sub!rograms are !ublic or !ri0ate

     –  de*inition o* !ri0ate sub!rograms is idden so tat only te !ac(age ;not

    te a!!lication< is a**ected i* te de*inition canges

     –  sim!li*ies maintenance and enancement and !rotects integrity o* te

     !ac(age

    Better !er*ormance

     –  en a !ac(aged sub!rogram is called *or te *irst time te ole

     !ac(age is loaded into memory

     –  later calls to related sub!rograms in te !ac(age reuire no dis( /.'

    Pac&ae Specification

    /s an inter*ace to te a!!lications

    9eclares te ty!es 0ariables constants ece!tions cursors and sub!rograms

    a0ailable *or use :olds !ublic declarations 0isible to te a!!lication

    Can be tougt o* as an o!erational inter*ace

    Sco!e o* te declarations are local to te database scema and global to te

     !ac(age

    Lists te !ac(age resources a0ailable to a!!lications

    Created using CRE-TE P-CO-E command

  • 8/16/2019 PLSQL CourseWare.doc

    76/135

    System Consultant

     $"

    Synta( for Pac&ae Specification  

    CRE-TE V'R REPL-CEW P-CO-E @!ac(agenameA -S

    lobal 0ariables declarationProcedure s!eci*ications

    %unction s!eci*ications

    Ty!e 9e*initions

    Cursor 9eclarationsE,9 V@!ac(agenameAW

    Pac&ae !o%y

    /m!lements te !ac(age s!eci*ication %ully de*ines cursors and sub!rograms

    :olds im!lementation details and !ri0ate declarations idden *rom te

    a!!lication

    Can be tougt o* as a blac( bodyU

    Can be re!laced enanced or re!laced itout canging te inter*ace

    Can be canged itout recom!iling calling !rograms

    Sco!e o* te declarations are local to te !ac(age body

    9eclared ty!es and obXects are inaccessible ece!t *rom itin te !ac(age body

    /nitialiIation !art o* a !ac(age is run only once te *irst time te !ac(age is

    re*erenced

    Synta( for Pac&ae !o%y  

    CRE-TE V'R REPL-CEW P-CO-E B'9N @!ac(agenameA -S

    Pri0ate members ;0ariables and !rocedure.*unctions.cursors.ty!es<

    Procedure Code

    %unction Code/m!lementation o* Ty!es

    se o* Cursors

    sing lobal 0ariables in te members o* te !ac(age6E,9 V@!ac(agenameAW

    Referencin Pac&ae ObUects

    Pac(aged obXects and sub!rograms must be re*erenced using te dot notation

     !ac(agename6ty!ename

     !ac(agename6obXectname !ac(agename6sub!rogramname

  • 8/16/2019 PLSQL CourseWare.doc

    77/135

    System Consultant

     $$

    E6g 7 '!SO6TP6T. P#"_$NE 

    aintainin a Pac&ae

    Can dro! a !ac(age using te 9R'P command

    9R'P P-CO-E @!ac(agenameA

    Eam!le

    9R'P P-CO-E airlinesTo dro! Xust one construct remo0e it *rom te !ac(age and ten recom!ile te

     !ac(age

    E(amples of Pac&aes $

  • 8/16/2019 PLSQL CourseWare.doc

    78/135

    System Consultant

     $&

      is

      Begin  dbmsDout!ut6!utDline;GProcedure !3G

  • 8/16/2019 PLSQL CourseWare.doc

    79/135

    System Consultant

     $#

      number

    Begin  F !(26m;$))

  • 8/16/2019 PLSQL CourseWare.doc

    80/135

    System Consultant

     &)

    D 6se of Type in a Proce%ure $

    Pac&ae Specification $

    create or re!lace !ac(age !(3 as

    Ty!e t1 is REC'R9;e1 Em!6Em!no MTy!e

    e2 Em!6EnameMTy!ee3 Em!6SalMTy!e

  • 8/16/2019 PLSQL CourseWare.doc

    81/135

    System Consultant

     &1

    Pac&ae !o%y $

    create or re!lace !ac(age body !(4 as

     !rocedure CP

    is

      Begin  '!en c*

      Loo!  *etc c* into m

     

    .8Soing te *irst entry o* manager8.

      i* c*Mrocount F 1 ten  dbmsDout!ut6!utDline;m6em!no HH G7G HH m6ename HH G7G HH m6sal

  • 8/16/2019 PLSQL CourseWare.doc

    82/135

    System Consultant

     &2

    -& Exam#'e ! #ri,ate mem(ers in #ac)age (!dy *

    create or re!lace !ac(age !r0members

    is

     !rocedure m1end

    create or re!lace !ac(age body !r0membersis

    .8Creating Pri0ate Procedure in te body8.

     !rocedure m2is

      begin

    dbmsDout!ut6!utDline;GTis is te !ri0ate member o* te !ac(age bodyG

  • 8/16/2019 PLSQL CourseWare.doc

    83/135

    System Consultant

     &3

    I the #ri,ate mem(er is n!t getting ca''ed in any g'!(a' mem(ers then !r.ard dec'arati!nis n!t reuired0

    create or replace package body prvmembersisprocedure m1

    isbegindbms_output.put_line('abc');end;/*Creating Private Procedure in te body*/procedure m!is  begindbms_output.put_line('"is is te private member o# te package body');end m!;end;/

    1& Exam#'e ! !ne time !n'y #r!cedure +Pr!cedure in #ac)age (!dy&

    Useu' !r setting rem!te c!nnecti,ity !r r!nt ends0In the sessi!n !r the irst time any ! the mem(ers ! the #ac)age is ca''ed then the#r!cedure .i'' (e im#'icit'y in,!)ed0"hen !r the uture ca''s ! the mem(ers ! the same #ac)age in the same sessi!n the#r!cedure .i'' n!t get executed0

    create or re!lace !ac(age !(1

    is

     !rocedure !1 !rocedure !2

    end

  • 8/16/2019 PLSQL CourseWare.doc

    84/135

    System Consultant

     &4

    create or re!lace !ac(age body !(1

    is !rocedure !1

      is

      begin

      dbmsDout!ut6!utDline;G!1GD1

     end !(1 

    create or re!lace !ac(age !(1

    is  ty!e namelist is table o* em!6enameMty!e inde by binaryDinteger

      0 namelist

      cursor c* is select ename *rom em!  c*Mroty!e

      !rocedure *irstD*i0e

      !rocedure netD*i0e

    end

  • 8/16/2019 PLSQL CourseWare.doc

    85/135

    System Consultant

     &5

    create or replace pac&ae bo%y p&<

    is

      i Number1

      proce%ure firstfi,e  is

      bein  for i in

  • 8/16/2019 PLSQL CourseWare.doc

    86/135

    System Consultant

     &"

    create or re!lace !ac(age !(1

    is  a0erageDsal number

      *unction calcDsalDde0iation;s number< return number

      !rocedure salDstatus;s number

  • 8/16/2019 PLSQL CourseWare.doc

    87/135

    System Consultant

     &$

    ?D E(ample of O,erloa%e% embers

    create or re!lace !ac(age !(1

    is

     !rocedure !;a number b number

  • 8/16/2019 PLSQL CourseWare.doc

    88/135

    System Consultant

     &&

    Exam#'e ! !,er'!aded mem(ers *Parameter data ty#es can (e same2 (ut names sh!u'd (e dierent0

    create or replace package pk!asprocedure p(salary number$ commission number);

    procedure p(salary number$ ta% number);end pk!;

    create or replace package body pk!as procedure p(salary number$ commission number)  is  total number;  begin  total & salary commission;  dbms_output.put_line(total);  end; procedure p(salary number$ ta% number)  is  take_ome number;  begin  take_ome & salary ta%;  dbms_output.put_line(take_ome);  end;end pk!;

    Whi'e executing such #r!cedure the #arameters need t! (eca''ed (y named meth!d !n'y0

    e%ec pk!.p(salary +,,,$ commission -,,);

    e%ec pk!.p(salary +,,,$ ta% !,,);

  • 8/16/2019 PLSQL CourseWare.doc

    89/135

    System Consultant

     

    Exam#'e ! Persistent Curs!rs *

    create or replace package pciscursor c# is select * #rom emp;

    procedure pp1;procedure pp!;c c#rotype;end ;

    create or replace package body pc isprocedure pp1 is begin

    open c#;  loop  #etc c# into c;  dbms_output.put_line(c.empno00''00c.ename00''00c.sal);  e%it en c#rocount ;  end loop; end pp1;procedure pp! is begin  loop  #etc c# into c;  dbms_output.put_line(c.empno00''00c.ename00''00c.sal);  e%it en c#rocount 2;  end loop;  close c#;  end pp!;end;

  • 8/16/2019 PLSQL CourseWare.doc

    90/135

    System Consultant

     #)

    PR/TN LE+ELS

    P34564 378"39C"_37:737C78

  • 8/16/2019 PLSQL CourseWare.doc

    91/135

    System Consultant

     #1

    Pac(age Body Code 7

    create or replace pac&ae bo%y pramapac&ae

    as

      function etTotalcommission in numberD

      return number

      is

      salary number - @1

      bein

      select a into salary from pt< "#ere a

  • 8/16/2019 PLSQL CourseWare.doc

    92/135

    System Consultant

     #2

      return area1

      en%1

    en%1

    E(ample of RNPS

    Pac&ae Specification Co%e

    create or replace pac&ae purityle,el<

    as

      sellinprice number - @@@1

      ta( number - I@1

      proce%ure cust%etails1

      PRAGA RESTR7CTRE*ERENCES cust%etails5 RNPSD1en%1

    Pac&ae !o%y Co%e $$

    create or replace pac&ae bo%y purityle,el<

    as

      proce%ure cust%etails

      is

      bein

      7nsert into pt< ,aluespurityle,el

  • 8/16/2019 PLSQL CourseWare.doc

    93/135

    System Consultant

     #3

    RE* C6RSORS

    Limitations of a normal cursors are $$

    1< - PL.SQL !rogram cannot pass a cursor as a parameter to anoter !rogram6

    2< - PL.SQL !rogram can only o!en te cursor and process t#e information "it#int#e proram itself.

    To o0ercome tese limitations tere is a conce!t o* RE* C6RSOR 6

      *eatures of RE* C6RSOR $$

    1< Tere can be a TNPE o* re* cursor6 Te 0ariable o* tis TNPE can be used to

     !ass te !arameters to a !rogram and return 0alue *rom te cursor6

    2< Te 0ariable o* RE% CRS'R ty!e returns te same data ty!e as te cursor0ariable6

    3< Te cursor 0ariable is !assed as a !arameter to a !rocedure6

    4< Te cursor 0ariable ta(es all te ros *rom te s!eci*ied table65< Tese ros are gi0en to te bind 0ariable6

      So te !arameter !assed sould satis*y to conditions 77  a< Te !arameter sould be ta(en *rom te T:PE of Ref Cursor.  b< /t sould be o* 7N O6T mode6

    "< %inally te data retrie0ed by te cursor 0ariable can be seen troug te bind

    0ariable6 %or tis te data ty!e o* te bind 0ariable sould be RE%CRS'R6

    $< ile eecuting te !rocedure bind 0ariable sould be directly gi0en6 -nd ten by !rint statement te data is dis!layed6

    &< Te cursor 0ariableGs data structure and te !rocedure bloc(Gs data structure sould

     be same6

    A%,antae of RE* C6RSOR$$

      %&tually we &an get the view of the entire data of the table with simpli&ity using 'E #'SO'*

      itout using re* cursor i* e a0e to acie0e tis ten te !arameter !assed ill

     be o* 0ariable ty!eand ten te user as to manual loo! using cursor to *etc all te records6 :ere in

    RE% CRS'R tere is no need o* loo!ing6

  • 8/16/2019 PLSQL CourseWare.doc

    94/135

    System Consultant

     #4

    E(ample of RE* C6RSOR  

    Pac&ae Specification  

    create or re!lace !ac(age PRC as

    TNPE Em!RC /S RE% CRS'R RETR, em!Mroty!e

    TNPE 9e!tRC /S RE% CRS'R RETR, de!tMroty!e

    Procedure Em!9etails;0e /, 'T Em!RC

  • 8/16/2019 PLSQL CourseWare.doc

    95/135

    System Consultant

     #5

    T:PES

    sers can create teir on data ty!es by combining !re0iously de*ined data ty!es

    -lso called 'bXect ty!es

    'bXect ty!es made u! o* attributes and members

    Creating ty!e /n*o ic olds te attributes  

    Create or re!lace ty!e /n*o as 'BZECT

    ; ,ame 0arcar2;3)

  • 8/16/2019 PLSQL CourseWare.doc

    96/135

  • 8/16/2019 PLSQL CourseWare.doc

    97/135

    System Consultant

     #$

    Alterin types

    'roppin t#e typeY 

    To dro! a ty!e *irst all te tables in ic tat ty!e is used sould be dro!!ed ten only

    te ty!e can be dro!!ed6

    6serTypes is te in built table *or ty!e in*ormation6

    select ty!eDnamety!ecode *rom userDty!es

    Alterin types  

    Te attributeUs data ty!e siIe can be increased at any time6

    create or re!lace ty!e as obXect

    ; number;3

  • 8/16/2019 PLSQL CourseWare.doc

    98/135

    System Consultant

     #&

    +ARRA:

    -lso (non as 0arying arrays

    /t is an aggregation o* 0alues stored in a single column

    - single column in te database ould !oint to a grou! o* elements

    Can associate a single identi*ier it an entire collection Can re*erence te entire collection as a ole or access te elements indi0idually

    To access indi0idual elements use standard subscri!ting synta i6e6

    arrayDname;subscri!t<

    aimum siIe must be s!eci*ied at time o* de*inition

    /nde as a *ied loer bound o* 1 and an etensible u!!er bound

    A ,aryin array allo"s to store repeatin attributes of a recor% in a sinle

    ro".

    Steps for Creatin +ARRA:s

    Create a ty!e ic ill old in*ormation *or a single line item

    Create an array o* ty!e (non as +array ty!e olding multi!le 0alues o* a

     !articular ty!e

    Create a table a0ing one o* te columns (non as 0array column based on te

    +array ty!e

    T#e S:NTAJ for creatin a +ARRA:

    CREATE T:PE ,arraytypenameF

    AS +ARRA:limitD O* typeF1

     E(ample   /n a *actory table tere are or(ers using di**erent tools6 Eac or(er isusing say 3 numbers o* tools6 Tus i* a single or(er is ta(ing 3 tools ten tat or(erUs

    name ill come trice in te table6 So tere ill be data redundancy6 +arrays ill re!eat

    0alues tat cange *or a !articular column ic ill sa0e te storage s!ace6

    A set of ro"s is repeate% in one column in ,array.

     Step < Create an ,array #ol%in elements of ,arc#ar==@D.

    create or replace type TOOLS+A as ,arrayD of ,arc#ar==@D1

     Step = $ Create a table #a,in one of t#e column as t#e ,array column

    base% on t#e ,array type.

      create table *actory  ;name 0arcar2;2)< !rimary (ey

      tools TOOLS+A

  • 8/16/2019 PLSQL CourseWare.doc

    99/135

    System Consultant

     ##

    Step 7nsertin recor% in t#e factory table

    7nsert into factory ,alues >o#n>5 TOOLS+A >)ammer>5 >Sle%e>5 >'rill>DD1

    7nsert into factory ,alues >Smit#>5 TOOLS+A >Scre" Gaue>5 >)ammer>5 >AJ>DD1

    7nsert into factory ,alues >artin>5 TOOLS+A null5 >Sle%e>5 nullDD1

    To see names of tools for eac# "or&er.

    select %6,ame +68 *rom %actory % TA!LE;%6Tools< +

    + is an alias table created *or te tool names6 T-BLE *unction is used to sim!li*y te !rocess o* selecting data *rom 0arying arrays6

    Conditional records

    To see records o* !ersons a0ing :ammer tool

    select %6,ame +68 *rom %actory % T-BLE;%6Tools< +

    ere +6Column+alue F G:ammerG

    Summary records

    To see count o* tools *or eac !erson

    select %6,ame CountColumn+alueD*rom %actory % T-BLE;%6Tools< +rou! By %6,ame

     

    6p%atin +ARRA:s

    /ndi0idual elements cannot be u!dated

    Entire +-RR-N as to be u!dated i* one o* te elements as to be canged

    To c#ane t#e ,alue of first in%e( tool of artin from null to +ernier C

    u!date *actory

    set tools F toolsD0a;>+ernier C>GSledgeG ,LL<ere name F GartinG

  • 8/16/2019 PLSQL CourseWare.doc

    100/135

    System Consultant

     1))

    Creatin customi2e% an% a%,ance report usin PL/SQL bloc&s

    'isplayin %ata from t#e ,array column  

    declare

      cursor c* is  select 8 *rom *actory

      0c* c*Mroty!e begin

      *or 0c* in c* 

      loo!

      .8Tis loo! is *or te normal column name68.  dbmsDout!ut6!utDline;GContact ,ame GHH 0c*6name

  • 8/16/2019 PLSQL CourseWare.doc

    101/135

    System Consultant

     1)1

      dbmsDout!ut6!utDline;G777777777777777777777777777 G

  • 8/16/2019 PLSQL CourseWare.doc

    102/135

    System Consultant

     1)2

      end loo!

    end loo!  i* count'*Sa*t:olders F ) ten

      dbmsDout!ut6!utDline;GSorry tere are no sa*t oldersG

  • 8/16/2019 PLSQL CourseWare.doc

    103/135

    System Consultant

     1)3

    Creating a 0array *rom a ty!e

    ulti!le attributes *or a single record and multi!le sets o* attributes *or a single record6

    create or re!lace ty!e ontlyDSales as 'bXect

     ;ont +arcar2;3

  • 8/16/2019 PLSQL CourseWare.doc

    104/135

    System Consultant

     1)4

    Nested "a('e• "able itin a table

    •  4 table is represented as a column itin anoter table

    • "here is n! 'imit t! the num(er ! r!.s in the nested ta('e !r each

    r!. in the main ta('e0• >asically used #or mapping masterdetail relationsips beteen tables.

    i.e. 7n t#e parent table t#ere "oul% be one column5 "#ic# "ill store t#e location of

    t#e neste% table.

    Ste#s !r Creating Nested "a('es Create a type ic ill old in#ormation #or a single line item (tis

    represents te nested table details) Create "ype o# "able to old details #or te multiple ros o# te nested

    table (tis ill be te nested details nested table type) Create te master table it one o# te columns ic ill old te nested

    table typeCreating a Nested "a('e

    S3N"45C6E4"E "3PE 7nested$ta('e$ty#e$name84S "49LE OF 7ty#ename8:

    7%ample "ere is main table :are_"ab1.9t as columns suc as 3oute_Coe$3oute_=esc$?rigin$=estination$ :irts_:are$>us_:are$7co_:are and @ourney_rs.

    "ere is a type as table :s_st_"ype.  "is type table olds column suc as :ligtno$ 4irbusno$=eprt_"ime$:ligt_=ay1 and :ligt_=ay!.

    o e are trying to establis te relation beteen :are_"ab1 table and tistype table :s_st_"ype.

    ?ne route_code #rom :are_"ab1 table can old multiple :ligtno$ 4irbusno$=eprt_"ime$ :ligt_=ay1 and :ligt_=ay!. :or tis purpose e illcreate a column in :are_"ab1 table ic ill so details o# te :s_st_"ype#or a particular route_code. 8o tat column actually represents te nested table.

  • 8/16/2019 PLSQL CourseWare.doc

    105/135

    System Consultant

     1)5

    Ste# ; B7 o# :ligt_8c_"ype;

    Ste#>

  • 8/16/2019 PLSQL CourseWare.doc

    106/135

    System Consultant

     1)"

    9nsert into :are_"abDalues ('5oa>an'$ '5oa >angalore'$ '5oa'$ '>angalore'$ +-,$ ,,$ !,,$ $ Fs$Nst$"y#e + F'ight$Sch$"y#e+AF=A2 A49B;A2A BBA2;2>&2

      F'ight$Sch$"y#e+AF>A2A49B=A2 A;;BBA2 >2 %& & &:

    Eere in tis insert statement #or one route_code '5oa>an' ! nested ros o# :!and : are inserted.

    Dis#'aying the data ! the nested ta('e c!'umns an')

      "$ :are_"ab1  ere ".:ligtno ':!';

    In Orac'e i "a('e uncti!n is used instead ! "GE c'ause .hich ma)es theuery ,ery easy t! understand

    select route_code$ ".#ligt_day1$ t.#ligt_day!$".=eprt_"ime$".#ligtno #rom :are_"ab$ "able(:are_"ab.:ligt_8c_=et) " ere route_code '5oa>an' 4nd ".#ligtno ':'

    S! Syntax in i isSe'ect master$ta('e$c!'s2 4'ias0Neste$"a('e$C!'sFr!m aster$"a('e2 "a('e+aster$"a('e0Nested$"a('e& 4'ias

    "o see all attribute columns o# te ested "able e can use * it alias name o#te nested table Fselect route_code$ ".*#rom :are_"ab1$ "able(:are_"ab1.:ligt_8c_=et) "

  • 8/16/2019 PLSQL CourseWare.doc

    107/135

    System Consultant

     1)$

    ere route_code '5oa>an' 4nd ".#ligtno ':'

    U#dating the nested r!. in i

    S3N"45UPD4"E "GE +SELEC" 7nested$c!'umn8F6O 7master$ta('e8WGE6E 7master$ta('e$c!nditi!n8& 7nested$a'ias8SE" 7nested$a'ias807attri(ute;$name8 7,a'ue820002WGE6E 7nested$ta('e$c!nditi!n8:

    "! change the ,a'ue ! 'ight$day; r!m > t! % !r the F'ightn! F> !n ther!ute$c!de AH!aB7(select nested_table_name)  :rom 6aster_"able 

  • 8/16/2019 PLSQL CourseWare.doc

    108/135

    System Consultant

     1)&

    De'eting a r!. r!m the nested ta('e

    S3N"45 in i

    DELE"E F6O "GE

    +SELEC" 7nested$c!'umn8F6O 7master$ta('e8WGE6E 7master$ta('e$c!nditi!n8& 7nested$a'ias8WGE6E 7nested$ta('e$c!nditi!n8:

    "! de'ete the detai's ! 'ightn! AF=A !r the r!ute$c!de AH!a

  • 8/16/2019 PLSQL CourseWare.doc

    109/135

    System Consultant

     1)#

    Dierence 9et.een 46643s and Nested "a('es

      46643s

    6a%imum siIe speci#ied attime o# de#inition

    =ata is stored inline

    3etain teir ordering and

    subscripts en stored indatabase

    Nested "a('es

    o ma%imum siIe =ata is stored outo#line in a

    store table =o not retain ordering and

    subscripts en stored indatabase

    When t! use Nested "a('es instead ! 46643s

  • 8/16/2019 PLSQL CourseWare.doc

    110/135

    System Consultant

     

    !file an% LO!s!file  Binary *ile ;tet sound image or 0ideo< is stored outside te database6 Telocator to tat *ile is stored in te database6 B*ile data is read only *or oracle6

    L'B !LO! and CLO! are te to ty!es o* L'Bs6 B is binary and C is caracter data6

    L'B *iles are stored inside te database6 Since te *iles are inside db tey can bemani!ulated toroug oracle6 - ma o* 4B data can be stored in a BL'B or CL'B data

    ty!e6

    'irectory is a non7scema obXect oned by =SNS> user6 /t is used *or managing te

    o!erating system *iles ;tat are eternal to oracle

  • 8/16/2019 PLSQL CourseWare.doc

    111/135

    System Consultant

     

    Ste! 4 Create a table mytable it to *ields *ileDid and *ileDdata

    Create table mytable

    ;*ileDid number

      file%ata clob

  • 8/16/2019 PLSQL CourseWare.doc

    112/135

    System Consultant

     

    CRE-TE 'R REPL-CE PR'CE9RE insertclob ;!D*ileDid number *ilename

    +-RC:-R2<

    -S  0Dclob CL'B

      0Db*ile B%/LE

    BE/,  /,SERT /,T' mytable +-LES ;!D*ileDidem!tyDclob;

  • 8/16/2019 PLSQL CourseWare.doc

    113/135

    System Consultant

     

    Note 9 2n a session, the number of B%2L6s that can be opened in one session is limitedb the parameter session5ma$5open5files and total number of files that can be open is

    limited b the parameter ma$5open5files. #hese parameters are to be setted in the

    init.ora file session5ma$5open5files:0'

    ma$5open5files:'"

    T#e '!SLO!.REA' Proce%ure

    Reads data *rom L'B starting at s!eci*ied o**set

    9BSDL'B6RE-9;loc num offset  buff <

    ere

    loc is locator o* te L'B

    num is number o* bytes.caracters to be read

    offset  is o**set in bytes.caracters *rom te start o* te L'Bbuff  is out!ut bu**er *or te read o!eration

    Eam!le To retrie0e a !art o* data *rom te *irst recordUs

    *ileDdata column

    declare

    0Dclob clob

    num numbero**set number

    0store 0arcar2;2)

  • 8/16/2019 PLSQL CourseWare.doc

    114/135

    System Consultant

     

    ere *ileDid F 1

    '!SLO!.REA',clob5num5offset5,storeD1

      dbmsDout!ut6!utDline;0store

  • 8/16/2019 PLSQL CourseWare.doc

    115/135

  • 8/16/2019 PLSQL CourseWare.doc

    116/135

    System Consultant

     

    Eam!le1o* Erase metod  

    9BSDL'B6Erase

    Synta 7 9BSDL'B6Erase;Source ,o6 o* caracters to erase

    Position *rom ere it as to erase<

    To remo0e some tet *rom clob column

    Remo0ing te *irst 5 caracters o* *ileDdata column *or *ileDid 2

    9eclare

      loc clob  num number

      o**set number

    Begin

      num F 5  o**set F 1

      select *ileDdata into loc *rom mytable  ere *ileDid F 1

      9BSDL'B6Erase;locnumo**set

  • 8/16/2019 PLSQL CourseWare.doc

    117/135

    System Consultant

     

    TR7GGERS

    /t is a stored PL.SQL !rogram unit associated it a s!eci*ic database

    table

    'racle eecutes ;*ires< te trigger automatically ene0er a gi0enSQL o!eration a**ects te table

    Tey are in0o(ed im!licitly

    Tey are use*ul *or customiIing a database

    Tey sould be used only en necessary

    Can automatically generate deri0ed column 0alues

    Can !re0ent in0alid transactions

    Can en*orce com!le security autoriIations

    Can en*orce re*erential integrity across nodes in a distributed database

    Can en*orce com!le business rules Can !ro0ide trans!arent e0ent logging

    Can !ro0ide so!isticated auditing

    Can maintain syncronous table re!licates

    Can gater statistics on table access

    Can deri0e column 0alues automatically

    Can restrict 9L o!erations to regular business ours

    Synta( $$CRE-TE V'R REPL-CEW TR/ER @triggernameA

    BE%'REH-%TER 

    /,SERTH9ELETEHP9-TE '% @columnnamesA ', @tablenameA

    V%'R E-C: R'W

    :E, ;@conditionA<

    @PL.SQL Bloc(A

     ,ame in te ', clause identi*ies te database table associated it te

    trigger 

    Te trigger e0ent s!eci*ies te SQL 9L statement ;/,SERT 9ELETE orP9-TE< tat a**ects te table

    -%TER s!eci*ies tat te trigger *ires a*ter te mani!ulation is done

    BE%'RE s!eci*ies tat te trigger *ires be*ore te mani!ulation is

    done

    By de*ault a trigger *ires once !er table

    11$

  • 8/16/2019 PLSQL CourseWare.doc

    118/135

    System Consultant

     

    %'R E-C: R' s!eci*ies tat te trigger *ires once !er ro

    %or te trigger to *ire te Boolean e!ression in te :E, clause

    must e0aluate to TRE

    REPL-CE can be added to te CRE-TE statement to dro! and re7

    create te trigger automaticallyCRE-TE TR/ER *ligtDu!date

    -%TER /,SERT ', reser0ation

    %'R E-C: R'

    BE/,

    /% ne6class F %U T:E,

    statements

    ELS/% ne6class F BU T:E,

    statements

    E,9 /%

    E,9

    Pre*i ne is a correlation name tat re*ers to te nely u!dated

    column 0alue

    itin a trigger te ne and old 0alues o* canging ros can be

    re*erenced

    - single trigger can andle more tan one o!eration

    se conditional !redicates to identi*y te ty!e o* statement used to

    in0o(e te section o* code

    E(amples of Triers $ Ro" Le,el

    A*TER clause

    1<

    77 ain table

    create table tem!as

    select 8 *rom em!

    77 Table to trans*er inserted record

    create table instem!

    as

    11&

  • 8/16/2019 PLSQL CourseWare.doc

    119/135

    System Consultant

     

    select enamesal

    *rom em!

    ere 1F2

    ;#ene,er a ro" is inserte% in t#e temp table t#en t#at ne" ro"

    s#oul% be transferre% in t#e instemp table

    Create or re!lace trigger trig1

    -*ter /,SERT on tem!

    %or Eac Ro

    Begin

      /nsert into /nsTem!

      +alues;ne6ename ne6sal

  • 8/16/2019 PLSQL CourseWare.doc

    120/135

    System Consultant

     

    *rom em!

    ere 1F2

    ene0er a record is u!dated *rom te tem! table ten te old record

    soul go in u!tem! table

    create or re!lace trigger trig3

    -*ter P9-TE on tem!

    %or Eac Ro

    Begin

      /nsert into !tem!

      +alues;old6ename old6salD1

      En% 7f1

    En%1

    =D $$To pre,ent user from %eletin recor%s of sal F I@@

    12)

  • 8/16/2019 PLSQL CourseWare.doc

    121/135

    System Consultant

     

    Create or re!lace trigger trig4

    Be*ore 9ELETE on tem!

    %or Eac Ro

    Begin

      i* old6sal AF 35)) Ten

      raiseDa!!licationDerror;72)))5GCannot delete records o* sal greater

    tan or eual to 35))G

  • 8/16/2019 PLSQL CourseWare.doc

    122/135

    System Consultant

     

    end

    6se of ;#en Cluase

    create or re!lace trigger useo*en

    a*ter insert on tem!

    *or eac ro

    "#en ne".Uob >CLER>D

    .8-*ter any cler( record is inserted in te tem! table te date and time o*

    entry ill be inserted in te table reco*cler(8.

     begin

    insert into reco*cler( 

    0alues;sysdate toDcar;sysdateGmissG

  • 8/16/2019 PLSQL CourseWare.doc

    123/135

    System Consultant

     

    dbmsDout!ut6!utDline;G-*ter ro le0elG

  • 8/16/2019 PLSQL CourseWare.doc

    124/135

    System Consultant

     

    End

    4< ene0er a record is deleted *rom em! table ten te count o* records

    remaining sould be re*resed in te a log table countDem!

    create table countDem! ;noDo*Drecords number

  • 8/16/2019 PLSQL CourseWare.doc

    125/135

    System Consultant

     

    Combinin 'L e,ents in one Trier

    $$Combinin all 'L in one !ein bloc& 

    $$Any 'L s#oul% be trace% in t#e table eepTrace

    create table Oee!Trace

    ;username 0arcar2;3)

  • 8/16/2019 PLSQL CourseWare.doc

    126/135

    System Consultant

     

    Callin a proce%ure insi%e a trier  

    create table Em!Summary

    ;TotalDSalary number

  • 8/16/2019 PLSQL CourseWare.doc

    127/135

    System Consultant

     

    create or re!lace trigger trig11

     a*ter delete on tem!1

     *or eac ro

     begin

      insert into tem!1 ;em!noename< 0alues;$&G!rG

  • 8/16/2019 PLSQL CourseWare.doc

    128/135

    System Consultant

     

    On 6p%ate Casca%e

    Similar to on %elete casca%e built in for primary an% forein

    &ey interity.

    create table st

    ;roll number

     name 0arcar2;4)

  • 8/16/2019 PLSQL CourseWare.doc

    129/135

    System Consultant

     

    7nstea% Of Triers

    Pro0ides a trans!arent ay o* modi*ying 0ies tat cannot be

    modi*ied directly troug /,SERT P9-TE or 9ELETE statements

     because underlying tables contain Xoins /t is called /,STE-9 '% because 'racle *ires te trigger instead o*

    te triggering statement;s<

    sers can be trans!arent to te trigger because tey rite normal

    9L statements against te 0ie and te /,STE-9 '% trigger is

    used to ta(e care o* te modi*ications

    /t can be !laced on 'bXect +ies to insert u!date or delete data in te

    underlying relational tables

    CRE-TE TR/ER em!Dinsert

    /,STE-9 '% /,SERT ', em!D0ie

    BE/,

    statements

    E,9

  • 8/16/2019 PLSQL CourseWare.doc

    130/135

    System Consultant

     

    insert into r 

    0alues;1#)

  • 8/16/2019 PLSQL CourseWare.doc

    131/135

    System Consultant

     

    =D E(ample of 7nstea% of 7nsert

    Create or re!lace trigger tig14

      /nstead '* /,SERT on SR 

      %or Eac Ro

      Begin

      .8/nserting te ne record into bot te tables s and r68.

    /nsert into s

      0alues;ne6rollno ne6name

  • 8/16/2019 PLSQL CourseWare.doc

    132/135

    System Consultant

     

    ''L E+ENT TR7GGERS Can be create% by '!AD

  • 8/16/2019 PLSQL CourseWare.doc

    133/135

    System Consultant

     

    create or re!lace trigger PutD9ro!D'bXs

    After 'ROP ON Scott.Sc#ema

    Begin

      /nsert into Scottdro!

      +alues;ora%ictobUname SysdateD

    Ten

      raiseDa!!licationDerror;72))"$GCannot dro! column 2G

  • 8/16/2019 PLSQL CourseWare.doc

    134/135

    System Consultant

     

    Assinments

     Note 9 All the programs are based on the demonstration tables emp and dept. Beforee$ecuting the 1ueries please ensure that the standard records default" are present.

    1< /* te 4t record in te em! table o* te Xob -,-ERU ten dis!lay te entire

    record ;eac 0alue se!arated by an y!en

  • 8/16/2019 PLSQL CourseWare.doc

    135/135

    System Consultant

     

    12< sing ile loo! tecniue dis!lay all te multi!les o* $ beteen 31 and 4&6

    13< Create a table /ns!ectionD9etails tat as one column Readings o* numeric ty!e6

    sing !l.sl bloc( add numbers ic as te di**erence o* )616 Te numbers sould be

     beteen )61 and "6&6

    14< 9is!lay te names o* te em!loyees o are earning salary less tan te a0erage

    salary o* teir on Xobs6

    15< 9is!lay te di**erence o* salary beteen te oldest and te latest em!loyee6

    1"< Create a !rocedure tat ill ta(e de!artment name as a !arameter6 Te !roceduresould delete te record o* te em!loyees *rom te em! table only *or te de!artment

    name !assed6

    1$< Create a *unction ic ill so 2)M o* te raised salary *or eac em!loyee6

    1&< Create a !rocedure ic ill so te total igest loest and a0erage o* tesalary *or te Xob6 ;Zob ty!e is te !arameter to be !assed6<

    1#< Create a trigger ic ill not allo records to be entered beteen 1 and 2 !m onee(days6

    2)< Create one trigger ic ill allo insert u!date and delete *or a 0ie ic is

     based on an inner Xoin beteen tables em! and de!t6

    21< Create a trigger ic ill not allo records getting inserted in table T1U i* te

    b * d i bl i di