basics pl sql2

Upload: faizankareem

Post on 03-Jun-2018

226 views

Category:

Documents


0 download

TRANSCRIPT

  • 8/13/2019 Basics Pl Sql2

    1/75

    CURSORS

    Cursoris a pointer to memory location which is called as context areawhich containsthe information necessary for processing, including the number of rows processed by

    the statement, a pointer to the parsed representation of the statement, and the active

    setwhich is the set of rows returned by the query.

    Cursor contains two parts

    Header Body

    Header includes cursor name, any parameters and the type of data being loaded.Body includes the select statement.

    !"

    Cursor c#dno in number$ return dept%rowtype is select &from dept'

    (n the abo)e

    Header* cursor c#dno in number$ return dept%rowtype

    Body* select &from dept

    CURSOR +-S

    (mplicit #S/$ !plicit -arameteri0ed cursors R1 cursors

    CURSOR S+23S

    Open 1etch Close

    CURSOR 2++R(BU+S

    %found %notfound %rowcount %isopen

  • 8/13/2019 Basics Pl Sql2

    2/75

    %bul45rowcount %bul45e!ceptions

    CURSOR 6C/R2+(O7

    Synta!"

    Cursor 8cursor_name9 isselect statement'

    !"

    Cursor c is select &from dept'

    CURSOR /OO-S

    Simple loop :hile loop 1or loop

    S(;-/ /OO-

    Synta!"

    /oop

    1etch 8cursor_name9 into 8record_variable9'

    !it when 8cursor_name9 % notfound'

    8statements9'

    nd loop'

    !"

    6C/2R

    cursor c is select & from student'

    )5stud student%rowtype'

    B3(7

    open c'

    loop

    fetch c into )5stud'

    e!it when c%notfound'

    dbms5output.put5line#> )5stud.name$'

    end loop'

    close c'

  • 8/13/2019 Basics Pl Sql2

    3/75

    76'

    Output"

    7ame = sa4eth

    7ame = srinu

    7ame = satish

    7ame = sudha

    :H(/ /OO-

    Synta!"

    :hile8cursor_name9 % found loop 1etch 8cursor_name9 into 8record_variable9'

    8statements9'

    nd loop'

    !"

    6C/2R

    cursor c is select & from student'

    )5stud student%rowtype'

    B3(7

    open c'

    fetch c into )5stud'

    while c%found loop

    fetch c into )5stud'

    dbms5output.put5line#> )5stud.name$'

    end loop'

    close c'

    76'

    Output"

    7ame = sa4eth

    7ame = srinu

    7ame = satish

    7ame = sudha

  • 8/13/2019 Basics Pl Sql2

    4/75

    1OR /OO-

    Synta!"

    for8record_variable9 in8cursor_name9 loop

    8statements9'

    nd loop'

    !"

    6C/2R

    cursor c is select & from student'

    B3(7

    for )5stud in c loop

    dbms5output.put5line#> )5stud.name$'

    end loop'

    76'

    Output"

    7ame = sa4eth

    7ame = srinu

    7ame = satish

    7ame = sudha

    -2R2;+2R(?6 CURSORS

    +his was used when you are going to use the cursor in more than one place with different)alues for the same where clause.

    Cursor parameters must be inmode. Cursor parameters may ha)e default )alues. +he scope of cursor parameter is within the select statement.

    !"

    6C/2R

    cursor c#dno in number$ is select & from dept where deptno = dno'

    )5dept dept%rowtype'

    B3(7

  • 8/13/2019 Basics Pl Sql2

    5/75

    open c#@A$'

    loop

    fetch c into )5dept'

    e!it when c%notfound'

    dbms5output.put5line#> )5dept.dname >> < /oc = < >> )5dept.loc$'

    end loop'

    close c'

    76'

    Output"

    6name = RS2RCH/oc = 62//2S

    -2C236 CURSORS :(+H H26R (7 S-C 276 BO6 (7 -2C23 BO6

    cursors declared in pac4ages will not close automatically. (n pac4aged cursors you can modify the select statement without ma4ing any changes to

    the cursor header in the pac4age specification.

    -ac4aged cursors with must be defined in the pac4age body itself, and then use it asglobal for the pac4age.

    ou can not define the pac4aged cursor in any subprograms. Cursor declaration in pac4age with out body needs the return clause.

    !"

    CR2+ OR R-/2C -2C23 -3 (S

    cursor c return dept%rowtype is select & from dept'

    procedure proc is

    76 -3'

    CR2+ OR R-/2C -2C23 BO6 -3 (S

    cursor c return dept%rowtype is select & from dept'

    -ROC6UR -ROC (S

    B3(7

    for ) in c loop

    dbms5output.put5line#> ).deptno >> < 6name = < >> ).dname >> > ).loc$'

    end loop'

    76 -ROC'

  • 8/13/2019 Basics Pl Sql2

    6/75

    76 -3'

    Output"

    S/9e!ec p4g.proc

    6eptno = A 6name = 2CCOU7+(73/oc = 7: OR

    6eptno = @A 6name = RS2RCH/oc = 62//2S 6eptno = DA 6name = S2/S/oc = CH(C23O

    6eptno = EA 6name = O-R2+(O7S/oc = BOS+O7

    CR2+ OR R-/2C -2C23 BO6 -3 (S

    cursor c return dept%rowtype is select & from dept where deptno 9 @A'

    -ROC6UR -ROC (S

    B3(7

    for ) in c loop

    dbms5output.put5line#> ).deptno >> < 6name = < >> ).dname >> > ).loc$' end loop'

    76 -ROC'

    76 -3'

    Output"

    S/9e!ec p4g.proc

    6eptno = DA 6name = S2/S/oc = CH(C23O

    6eptno = EA 6name = O-R2+(O7S/oc = BOS+O7

    R1 CURSORS 276 CURSOR F2R(2B/S

    +his is unconstrained cursor which will return different types depends upon the userinput.

    Ref cursors can not be closed implicitly. Ref cursor with return type is calledstrong cursor. Ref cursor with out return type is called weak cursor. ou can declare ref cursor type in pac4age spec as well as body. ou can declare ref cursor types in local subprograms or anonymous bloc4s. Cursor )ariables can be assigned from one to another. ou can declare a cursor )ariable in one scope and assign another cursor )ariable with

    different scope, then you can use the cursor )ariable e)en though the assigned cursor

    )ariable goes out of scope.

    Cursor )ariables can be passed as a parameters to the subprograms.

  • 8/13/2019 Basics Pl Sql2

    7/75

    Cursor )ariables modes are in or out or in out. Cursor )ariables can not be declared in pac4age spec and pac4age body #e!cluding

    subprograms$.

    ou can not user remote procedure calls to pass cursor )ariables from one ser)er toanother.

    Cursor )ariables can not use for update clause. ou can not assign nulls to cursor )ariables. ou can not compare cursor )ariables for equality, inequality and nullity.

    !"

    CR2+ OR R-/2C -ROC6UR R15CURSOR#+2B/572; (7 F2RCH2R$ (S

    type t is ref cursor'

    c t'

    )5dept dept%rowtype'

    type r is record#ename emp.ename%type,Gob emp.Gob%type,sal emp.sal%type$'

    )5emp r'

    )5stud student.name%type'

    B3(7

    if table5name = )5dept.deptno >> < 6name = < >>

    )5dept.dname >> < /oc = < >> )5dept.loc$'

    elsif table5name = )5emp.ename >> < ob = < >> )5emp.Gob >> > )5emp.sal$'

  • 8/13/2019 Basics Pl Sql2

    8/75

    elsif table5name = )5stud$'

    end if'

    end loop'

    close c'

    76'

    Output"

    S/9e!ec ref5cursor#

  • 8/13/2019 Basics Pl Sql2

    9/75

    7ame = sa4eth

    7ame = srinu

    7ame = satish

    7ame = sudha

    CURSOR N-RSS(O7S

    ou can use cursor e!pressions in e!plicit cursors. ou can use cursor e!pressions in dynamic S/. ou can use cursor e!pressions in R1 cursor declarations and )ariables. ou can not use cursor e!pressions in implicit cursors. Oracle opens the nested cursor defined by a cursor e!pression implicitly as soon as it

    fetches the data containing the cursor e!pression from the parent or outer cursor.

    7ested cursor closes if you close e!plicitly. 7ested cursor closes whene)er the outer or parent cursor is e!ecuted again or closed or

    canceled.

    7ested cursor closes whene)er an e!ception is raised while fetching data from a parentcursor.

    Cursor e!pressions can not be used when declaring a )iew. Cursor e!pressions can be used as an argument to table function. ou can not perform bind and e!ecute operations on cursor e!pressions when using the

    cursor e!pressions in dynamic S/.

    US(73 7S+6 CURSORS OR CURSOR N-RSS(O7S

    !"

    6C/2R

    cursor c is select ename,cursor#select dname from dept d where e.empno = d.deptno$

    from emp e'

    type t is ref cursor'

    c t'

  • 8/13/2019 Basics Pl Sql2

    10/75

    c@ t'

    ) emp.ename%type'

    )@ dept.dname%type'

    B3(7

    open c'loop

    fetch c into )'

    e!it when c%notfound'

    fetch c@ into )@'

    e!it when c@%notfound'

    dbms5output.put5line#> ) >> < 6name = < >> )@$'

    end loop'

    end loop'

    close c'

    76'

    CURSOR C/2USS

    Return 1or update :here current of Bul4 collect

    R+UR7

    Cursor c return dept%rowtype is select &from dept'

    Or

    Cursor c is select &from dept'

    Cursor c return c%rowtype is select &from dept'

    Or

    +ype t is record#deptno dept.deptno%type, dname dept.dname%type$'

    Cursor c return t is select deptno, dname from dept'

    1OR U-62+ 276 :HR CURR7+ O1

  • 8/13/2019 Basics Pl Sql2

    11/75

    7ormally, a select operation will not ta4e any loc4s on the rows being accessed. +his will

    allow other sessions connected to the database to change the data being selected. +he

    result set is still consistent. 2t open time, when the acti)e set is determined, oracle

    ta4es a snapshot of the table. 2ny changes that ha)e been committed prior to this point

    are reflected in the acti)e set. 2ny changes made after this point, e)en if they are

    committed, are not reflected unless the cursor is reopened, which will e)aluate the

    acti)e set again.

    Howe)er, if the 1OR U-62+caluse is pesent, e!clusi)e row loc4s are ta4en on the rows in

    the acti)e set before the open returns. +hese loc4s pre)ent other sessions from

    changing the rows in the acti)e set until the transaction is committed or rolled bac4. (f

    another session already has loc4s on the rows in the acti)e set, then S/C+ 1OR U-62+

    operation will wait for these loc4s to be released by the other session. +here is no timePout for this waiting period. +he S/C+1OR U-62+will hang until the other session

    releases the loc4. +o handle this situation, the 7O:2(+clause is a)ailable.

    Synta!"

    Select from for update of column5name Qwait n'

    (f the cursor is declared with the 1OR U-62+clause, the :HR CURR7+ O1clause can be

    used in an update or delete statement.

    Synta!"

    :here current of cursor'

    !"

    6C/2R

    cursor c is select & from dept for update of dname'

    B3(7

    for ) in c loop

    update dept set dname =

  • 8/13/2019 Basics Pl Sql2

    12/75

    +his is used for array fetches :ith this you can retrie)e multiple rows of data with a single roundtrip. +his reduces the number of conte!t switches between the plsql and sql engines. Reduces the o)erhead of retrie)ing data. ou can use bul4 collect in both dynamic and static sql. ou can use bul4 collect in select, fetch into and returning into clauses. S/ engine automatically initiali0es and e!tends the collections you reference in the bul4

    collect clause.

    Bul4 collect operation empties the collection referenced in the into clause beforee!ecuting the query.

    ou can use the limit clause of bul4 collect to restrict the no of rows retrie)ed.

    ou can fetch into multible collections with one column each. Using the returning clause we can return data to the another collection.

    BU/ CO//C+ (7 1+CH

    !"

    6C/2R

    +ype t is table of dept%rowtype'

    nt t'

    Cursor c is select &from dept'

    B3(7

    Open c'

    1etch c bul4 collect into nt'

    Close c'

    1or i in nt.first..nt.last loop

    dbms5output.put5line#> nt#i$.dname >> < /oc = < >> nt#i$.loc$'

    end loop'

    76'

    Output"

    6name = 2CCOU7+(73/oc = 7: OR

    6name = RS2RCH/oc = 62//2S

    6name = S2/S/oc = CH(C23O

  • 8/13/2019 Basics Pl Sql2

    13/75

    6name = O-R2+(O7S/oc = BOS+O7

    BU/ CO//C+ (7 S/C+

    !"

    6C/2R

    +ype t is table of dept%rowtype'

    7t t'

    B3(7

    Select & bul4 collect into nt from dept'

    for i in nt.first..nt.last loop

    dbms5output.put5line#> nt#i$.dname >> < /oc = < >> nt#i$.loc$'

    end loop'

    76'

    Output"

    6name = 2CCOU7+(73/oc = 7: OR

    6name = RS2RCH/oc = 62//2S

    6name = S2/S/oc = CH(C23O

    6name = O-R2+(O7S/oc = BOS+O7

    /(;(+ (7 BU/ CO//C+

    !"

    6C/2R

    +ype t is table of dept%rowtype'

    nt t'

    Cursor c is select &from dept'

    B3(7

    Open c'

    1etch c bul4 collect into nt'

    Close c'

    1or i in nt.first..nt.last loop

    dbms5output.put5line#> nt#i$.dname >> < /oc = < >> nt#i$.loc$'

    end loop'

    76'

  • 8/13/2019 Basics Pl Sql2

    14/75

    Output"

    6name = 2CCOU7+(73/oc = 7: OR

    6name = RS2RCH/oc = 62//2S

    ;U/+(-/ 1+CHS (7 (7+O C/2US

    !"

    6C/2R

    +ype t is table of dept.dname%type'

    nt t'

    +ype t is table of dept.loc%type'

    nt t' Cursor c is select dname,loc from dept'

    B3(7

    Open c'

    1etch c bul4 collect into nt,nt'

    Close c'

    1or i in nt.first..nt.last loop

    dbms5output.put5line#> nt#i$$'

    end loop'

    1or i in nt.first..nt.last loop

    dbms5output.put5line#> nt#i$$'

    end loop'

    76'

    Output"

    6name = 2CCOU7+(73

    6name = RS2RCH

    6name = S2/S6name = O-R2+(O7S

    /oc = 7: OR

    /oc = 62//2S

    /oc = CH(C23O

    /oc = BOS+O7

  • 8/13/2019 Basics Pl Sql2

    15/75

    !@"

    6C/2R

    type t is table of dept.dname%type'

    type t is table of dept.loc%type'

    nt t'

    nt t'

    B3(7

    Select dname,loc bul4 collect into nt,nt from dept'

    for i in nt.first..nt.last loop

    dbms5output.put5line#> nt#i$$'

    end loop'

    for i in nt.first..nt.last loop

    dbms5output.put5line#> nt#i$$'

    end loop'

    76'

    Output"

    6name = 2CCOU7+(73

    6name = RS2RCH

    6name = S2/S

    6name = O-R2+(O7S

    /oc = 7: OR

    /oc = 62//2S

    /oc = CH(C23O

    /oc = BOS+O7

    R+UR7(73 C/2US (7 BU/ CO//C+

    declare

    type t is table of number#@$'

    nt t "= t#,@,D,E$'

    type t is table of )archar#@$'

    nt t'

    type t@ is table of student%rowtype'

    nt@ t@'

  • 8/13/2019 Basics Pl Sql2

    16/75

    begin

    select name bul4 collect into nt from student'

    forall ) in nt.first..nt.last

    update student set no = nt#)$ where name = nt#)$ returning no,name,mar4s bul4

    collect into nt@'

    for ) in [email protected]@.last loop

    dbms5output.put5line#> nt@#)$$'

    end loop'

    end'

    -O(7+S +O R;;BR

    Cursor name can be up to DA characters in length. Cursors declared in anonymous bloc4s or subprograms closes automatically when that

    bloc4 terminates e!ecution.

    %bul45rowcount and %bul45e!ceptions can be used only with forall construct. Cursor declarations may ha)e e!pressions with column aliases. +hese e!pressions are called )irtual columns or calculated columns.

    S/ (7 -/S/

    +he only statements allowed directly in plsql are 6;/ and +C/.

    B(76(73

    Binding a )ariable is the process of identifying the storage location associated with an

    identifier in the program.

    +ypes of binding

    arly binding /ate binding

    Binding during the compiled phase is early binding. Binding during the runtime phase is late binding. (n early binding compile phase will ta4e longer because of binding wor4 but the e!ecution

    is faster.

    (n late binding it will shorten the compile phase but lengthens the e!ecution time. -lsql by default uses early binding.

  • 8/13/2019 Basics Pl Sql2

    17/75

    Binding also in)ol)es chec4ing the database for permissions to access the obGectReferenced.

    672;(C S/

    (f you use 66/ in plsql it )alidates the permissions and e!istence if requires during

    compile time which ma4es in)alid.

    :e can a)oid this by using 6ynamic S/.

    6ynamic S/ allows you to create a S/ statement dynamically at runtime.

    +wo techniques are a)ailable for 6ynamic S/.

    7ati)e 6ynamic S/ 6B;S5S/ pac4age

    US(73 72+(F 672;(C S/

    Using e!ecute immediate

    Begin

    !ecute immediate Tcreate table student#no number#@$,name )archar#A$$'

    or

    !ecute immediate #Tcreate table student#no number#@$,name )archar#A$$$'

    nd'

    Using e!ecute immediate with plsql )ariables

    declare

    ) )archar#AA$'

    begin

    ) "=

  • 8/13/2019 Basics Pl Sql2

    18/75

    !ecuting queries with open for and using clause

    create or replace procedure p#smar4s in number$ is

    s )archar#AA$ "=

  • 8/13/2019 Basics Pl Sql2

    19/75

    nd'

    Fariable 7ames

    6eclare

    ;ar4s number#D$ "= AA'

    Begin

    6elete student where mar4s = mar4s' PP this will delete all the rows in the student table

    nd'

    +his can be a)oided by using the labeled bloc4s.

    88my5bloc499

    6eclare

    ;ar4s number#D$ "= AA'Begin

    6elete student where mar4s = my5bloc4.mar4s' PP delete rows which has a mar4s of

    AA

    nd'

    3etting data into plsql )ariables

    6eclare

    F number'

    F@ )archar#@$'

    Begin

    Select no,name into ),)@ from student where mar4s = AA'

    nd'

    6;/ and Records

    create or replace procedure p#srow in student%rowtype$ is

    begin

    insert into student )alues srow'

    end p'

    declare

    s student%rowtype'

    begin

  • 8/13/2019 Basics Pl Sql2

    20/75

    s.no "= '

    s.name "=

  • 8/13/2019 Basics Pl Sql2

    21/75

    dbms5output.put5line#> sreturn.no$'

    dbms5output.put5line#> sreturn.name$'

    dbms5output.put5line#> sreturn.mar4s$'

    end'

    1orall with nonPsequential arrays

    declare

    type t is table of student.no%type inde! by binary5integer'

    ibt t'

    begin

    ibt#$ "= '

    ibt#A$ "= @'

    forall i in ibt.first..ibt.lastupdate student set mar4s = LAA where no = ibt#i$'

    end'

    +he abo)e program will gi)e error li4e Telement at inde! Q@ does not e!ists.

    Usage of indices of to a)oid the abo)e error

    declare

    type t is table of student.no%type inde! by binary5integer'

    ibt t'

    type t is table of boolean inde! by binary5integer'

    ibt t'

    begin

    ibt#$ "= '

    ibt#A$ "= @'

    ibt#AA$ "= D'

    ibt#$ "= true'

    ibt#A$ "= true'

    ibt#AA$ "= true'

    forall i in indices of ibt

    update student set mar4s = LAA where no = ibt#i$'

    end'

  • 8/13/2019 Basics Pl Sql2

    22/75

    declare

    type t is table of student.no%type inde! by binary5integer'

    ibt t'

    type t is table of pls5integer inde! by binary5integer'

    ibt t'

    begin

    ibt#$ "= '

    ibt#A$ "= @'

    ibt#AA$ "= D'

    ibt#$ "= '

    ibt#K$ "= A'

    ibt#I$ "= AA'forall i in )alues of ibt

    update student set mar4s = KJM where no = ibt#i$'

    end'

    Bul4 Binds

    -assing the entire plsql table to the S/ engine in one step is 4nown as bul4 bind. Bul4 binds are done using the forall statement. (f there is an error processing one of the rows in bul4 6;/ operation, only that row is

    rolled bac4.

    Returning clause

    +his will be used only with 6;/ statements to return data into plsql )ariables. +his will be useful in situations li4e , when performing insert or update or delete if you

    want to 4now the data of the table which has been effected by the 6;/.

    :ith out going for another S/C+ using R+UR7(73 clause we will get the datawhich will a)oid a call to R6B;S 4erne

    RROR H276/(73

    -/S/ implements error handling with e!ceptions and e!ception handlers. !ceptions

    can be associated with oracle errors or with your own userPdefined errors. By using

  • 8/13/2019 Basics Pl Sql2

    23/75

    e!ceptions and e!ception handlers, you can ma4e your -/S/ programs robust and

    able to deal with both une!pected and e!pected errors during e!ecution.

    RROR +-S

    CompilePtime errors Runtime errors

    rrors that occur during the compilation phase are detected by the -/S/ engine and

    reported bac4 to the user, we ha)e to correct them.

    Runtime errors are detected by the -/S/ runtime engine which can programmatically

    raise and caught by e!ception handlers.

    !ceptions are designed for runPtime error handling, rather than compilePtime error

    handling.

    H276/(73 NC-+(O7S

    :hen e!ception is raised, control passes to the e!ception section of the bloc4. +he

    e!ception section consists of handlers for some or all of the e!ceptions. 2n e!ception

    handler contains the code that is e!ecuted when the error associated with the e!ception

    occurs, and the e!ception is raised.

    Synta!"

    NC-+(O7

    :hen e!ception5name then

    Sequence5of5statements'

    :hen e!ception5name then

    Sequence5of5statements'

    :hen others thenSequence5of5statements'

    76'

    NC-+(O7 +-S

  • 8/13/2019 Basics Pl Sql2

    24/75

    -redefined e!ceptions UserPdefined e!ceptions

    -R61(76 NC-+(O7S

    Oracle has predefined se)eral e!ceptions that corresponds to the most common oracle

    errors. /i4e the predefined types, the identifiers of these e!ceptions are defined in the

    S+2762R6pac4age. Because of this, they are already a)ailable to the program, it is not

    necessary to declare them in the declarati)e secion.

    !"

    6C/2R

    a number'

    b )archar#@$'

    )5mar4s number'

    cursor c is select & from student'

    type t is )array#D$ of )archar#@$'

    )a t "= t#

  • 8/13/2019 Basics Pl Sql2

    25/75

    B3(7

    close c'

    open c'

    close c'

    close c' NC-+(O7

    when in)alid5cursor then

    dbms5output.put5line#

  • 8/13/2019 Basics Pl Sql2

    26/75

    )a#E$ "=

  • 8/13/2019 Basics Pl Sql2

    27/75

    B3(7

    c "= KA'

    NC-+(O7

    when 0ero5di)ide then

    dbms5output.put5line#

  • 8/13/2019 Basics Pl Sql2

    28/75

    S/CO6returns the current error code, and S/RR;returns the current error message

    te!t'

    1or userPdefined e!ception S/CO6returns and S/RR;returns VuserPdeifned

    e!ceptionW.

    S/RR; wiil ta4e only negati)e )alue e!cept AA. (f any positi)e )alue other than AA

    returns nonPoracle e!ception.

    !"

    6C/2R

    e e!ception'

    )5dname )archar#A$'

    B3(7

    PP USRP61(76 NC-+(O7

    B3(7

    raise e'

    NC-+(O7

    when e then

    dbms5output.put5line#S/CO6>> < < >> S/RR;$'

    76'

    PP -R61(76 NC-+(O7

    B3(7

    select dname into )5dname from dept where deptno = KA' NC-+(O7

    when no5data5found then

    dbms5output.put5line#S/CO6>> < < >> S/RR;$'

    76'

    76'

    Output"

    UserP6efined !ception

    AA OR2PAEAD" no data found

    !@"

    B3(7

    dbms5output.put5line#S/RR;#AA$$'

    dbms5output.put5line#S/RR;#A$$'

  • 8/13/2019 Basics Pl Sql2

    29/75

    dbms5output.put5line#S/RR;#$$'

    dbms5output.put5line#S/RR;#PAA$$'

    dbms5output.put5line#S/RR;#PKAA$$'

    dbms5output.put5line#S/RR;#@AA$$'

    dbms5output.put5line#S/RR;#PLAA$$'76'

    Output"

    OR2PAEAD" no data found

    OR2PAAAA" normal, successful completion

    UserP6efined !ception

    OR2PAAAA" no data found

    OR2PAAKAA" ;essage KAA not found' product=R6B;S' facility=OR2

    P@AA" nonPOR2C/ e!ception

    OR2PAALAA" in)alid S/ statement

    6B;S5U+(/(+.1OR;2+5RROR5S+2C

    +he builtPin function, li4e S/RR;, returns the message associated with the current

    error.

    (t differs from S/RR;in two ways"

    (ts length is not restricted' it will return the full error message string.

    ou can not pass an error code number to this function' it cannot be used to return the

    message for a random error code.

    !"

    6C/2R

    ) number "=

  • 8/13/2019 Basics Pl Sql2

    30/75

  • 8/13/2019 Basics Pl Sql2

    31/75

    CR2+ OR R-/2C -ROC6UR -D (S

    B3(7

    dbms5output.put5line#

  • 8/13/2019 Basics Pl Sql2

    32/75

    Output"

    (n)alid Operation

    R2(S52--/(C2+(O75RROR

    ou can use this builtPin function to create your own error messages, which can be more

    descripti)e than named e!ceptions.

    Synta!"

    R2(S52--/(C2+(O75RROR#error_number, error_message,, Qkeep_errors_flag$'

    +he Boolean parameter keep_errors_flagis optional. (f it is +RU, the new error is added

    to the list of errors already raised. (f it is 12/S, which is default, the new error will

    replace the current list of errors.

    !"6C/2R

    c number'

    B3(7

    c "= KA'

    NC-+(O7

    when 0ero5di)ide then

    raise5application5error#P@A@@@,

  • 8/13/2019 Basics Pl Sql2

    33/75

    !ceptions raised in e!ecuatable section can be handled in current bloc4 or outer bloc4.

    !"

    6C/2R

    e e!ception'B3(7

    B3(7

    raise e'

    76'

    NC-+(O7

    when e then

    dbms5output.put5line#

  • 8/13/2019 Basics Pl Sql2

    34/75

    when others then

    dbms5output.put5line#

  • 8/13/2019 Basics Pl Sql2

    35/75

  • 8/13/2019 Basics Pl Sql2

    36/75

    e is raised

    1rom outer bloc4" e@ is raised

    !D"

    6C/2R

    e e!ception'

    B3(7

    raise e'

    NC-+(O7

    when e then

    dbms5output.put5line#

  • 8/13/2019 Basics Pl Sql2

    37/75

    /i4e pac4ages, triggers must be stored as standPalone obGects in the database and cannotbe local to a bloc4 or pac4age.

    2 trigger does not accept arguments.

    US O1 +R(33RS

    ;aintaining comple! integrity constraints not possible through declarati)e constraintsenable at table creation.

    2uditing information in a table by recording the changes made and who made them. 2utomatically signaling other programs that action needs to ta4e place when chages are

    made to a table.

    -erform )alidation on changes being made to tables. 2utomate maintenance of the database.

    +-S O1 +R(33RS

    6;/ +riggers (nstead of +riggers 66/ +riggers System +riggers Suspend +riggers

    C2+3OR(S

    +iming PP Before or 2fter

    /e)el PP Row or Statement

    Row le)el trigger fires once for each row affected by the triggering statement. Row le)el

    trigger is identified by the 1OR 2CH RO: clause.

    Statement le)el trigger fires once either before or after the statement.

    6;/ +R(33R S7+2N

    Create or replace trigger 8trigger_name9

    Before > after on insert or update or delete

    Q1or each row

  • 8/13/2019 Basics Pl Sql2

    38/75

    Begin

    PP trigger body

    nd 8trigger_name9'

    6;/ +R(33RS

    2 6;/ trigger is fired on an (7SR+, U-62+, or 6/+ operation on a database table.

    (t can be fired either before or after the statement e!ecutes, and can be fired once per

    affected row, or once per statement.

    +he combination of these factors determines the types of the triggers. +hese are a total

    of @ possible types #D statements & @ timing & @ le)els$.

    OR6R O1 6;/ +R(33R 1(R(73

    Before statement le)el Before row le)el 2fter row le)el 2fter statement le)el

    !"

    Suppose we ha)e a follwing table.

    S/9 select & from student'

    7O 72; ;2RS

    PPPPP PPPPPPP PPPPPPPPPP

    a AA

    @ b @AA

    D c DAA

    E d EAA

    2lso we ha)e triggering5firing5order table with firing5order as the field.

    CR2+ OR R-/2C +R(33R +R(33R

    before insert on student

    B3(7

  • 8/13/2019 Basics Pl Sql2

    39/75

    insert into trigger5firing5order )alues#

  • 8/13/2019 Basics Pl Sql2

    40/75

    PPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPP

    Before Statement /e)el

    Before Row /e)el

    2fter Row /e)el

    2fter Statement /e)el

    S/9 select & from student'

    7O 72; ;2RS

    PPPP PPPPPPPP PPPPPPPPPP

    a AA

    @ b @AA

    D c DAA

    E d EAA

    K e KAA

    CORR/2+(O7 (67+(1(RS (7 RO:P/F/ +R(33RS

    (nside the trigger, you can access the data in the row that is currently being processed.

    +his is accomplished through two correlation identifiers P "old and "new.

    2 correlation identifieris a special 4ind of -/S/ bind )ariable. +he colon in front ofeach indicates that they are bind )ariables, in the sense of host )ariables used in

    embedded -/S/, and indicates that they are not regular -/S/ )ariables. +he

    -/S/ compiler will treat them as records of type

    +riggering5table%RO:+-.

    2lthough syntactically they are treated as records, in reality they are not. "old and "new

    are also 4nown aspseudorecords, for this reason.

    +R(33R(73 S+2+;7+ "O/6 "7:

    PPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPP PPPPPPPPPPPPPPPPPPPPPPPPPPPP

    PPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPP

    (7SR+ all fields are 7U//. )alues that will be

    inserted

    :hen the statement is completed.

  • 8/13/2019 Basics Pl Sql2

    41/75

    U-62+ original )alues for new )alues that will be

    updated

    the row before the when the statement is completed.

    update.6/+ original )alues before all fields are 7U//.

    the row is deleted.

    !"

    Suppose we ha)e a table called mar4s with fields no, old5mar4s, new5mar4s.

    CR2+ OR R-/2C +R(33R O/657:

    before insert or update or delete on student

    for each row

    B3(7

    insert into mar4s )alues#"old.no,"old.mar4s,"new.mar4s$'

    76 O/657:'

    Output"

    S/9 select & from student'

    7O 72; ;2RS

    PPPPP PPPPPPP PPPPPPPPPP

    a AA

    @ b @AA

    D c DAA

    E d EAA

    K e KAA

    S/9 select & from mar4s'

    no rows selected

    S/9 insert into student )alues#J,

  • 8/13/2019 Basics Pl Sql2

    42/75

    row created.

    S/9 select & from student'

    7O 72; ;2RS PPPP PPPPPPPP PPPPPPPPPP

    a AA

    @ b @AA

    D c DAA

    E d EAA

    K e KAA

    J f JAA

    S/9 select & from mar4s'

    7O O/65;2RS 7:5;2RS

    PPPP PPPPPPPPPPPPPPP PPPPPPPPPPPPPPP

    JAA

    S/9 update student set mar4s=KKK where no=K'

    row updated.

    S/9 select & from student'

    7O 72; ;2RS

    PPPPP PPPPPPP PPPPPPPPPP

    a AA

    @ b @AA

    D c DAA

    E d EAA

    K e KKK

    J f JAA

    S/9 select & from mar4s'

  • 8/13/2019 Basics Pl Sql2

    43/75

    7O O/65;2RS 7:5;2RS

    PPPPPP PPPPPPPPPPPPPPPP PPPPPPPPPPPPPPP

    JAA

    K KAA KKK

    S/9 delete student where no = @'

    row deleted.

    S/9 select & from student'

    7O 72; ;2RS

    PPPP PPPPPPPP PPPPPPPPPP

    a AA

    D c DAA

    E d EAA

    K e KKK

    J f JAA

    S/9 select & from mar4s'

    7O O/65;2RS 7:5;2RS

    PPPPP PPPPPPPPPPPPPP PPPPPPPPPPPPPPPP JAA

    K KAA KKK

    @ @AA

    R1R7C(73 C/2US

    (f desired, you can use the R1R7C(73 clause to specify a different name for "old

    ane "new. +his clause is found after the triggering e)ent, before the :H7 clause.

    Synta!"

    R1R7C(73 Qold as old5name Qnew as new5name

    !"

    CR2+ OR R-/2C +R(33R R1R7C5+R(33R

  • 8/13/2019 Basics Pl Sql2

    44/75

    before insert or update or delete on student

    referencing old as old5student new as new5student

    for each row

    B3(7

    insert into mar4s

    )alues#"old5student.no,"old5student.mar4s,"new5student.mar4s$'

    76 R1R7C5+R(33R'

    :H7 C/2US

    :H7 clause is )alid for rowPle)el triggers only. (f present, the trigger body will be

    e!ecuted only for those rows that meet the condition specified by the :H7 clause.

    Synta!"

    :H7 trigger_condition'

    :here trigger_conditionis a Boolean e!pression. (t will be e)aluated for each row. +he

    :newand :oldrecords can be referenced inside trigger_conditionas well, but li4e

    R1R7C(73, the colon is not used there. +he colon is only )alid in the trigger body.

    !"

    CR2+ OR R-/2C +R(33R :H75+R(33R before insert or update or delete on student

    referencing old as old5student new as new5student

    for each row

    when #new5student.mar4s 9 KAA$

    B3(7

    insert into mar4s

    )alues#"old5student.no,"old5student.mar4s,"new5student.mar4s$'

    76 :H75+R(33R'

    +R(33R -R6(C2+S

    +here are three Boolean functions that you can use to determine what the operation is.

    +he predicates are

  • 8/13/2019 Basics Pl Sql2

    45/75

    (7SR+(73 U-62+(73

    6/+(73

    !"

    CR2+ OR R-/2C +R(33R -R6(C2+5+R(33R

    before insert or update or delete on student

    B3(7

    if inserting then

    insert into predicates )alues#

  • 8/13/2019 Basics Pl Sql2

    46/75

    ;S3

    PPPPPPPPPPPPPPP

    6

    (

    S/9 update student set mar4s = MMM where no=M'

    row updated.

    S/9 select & from predicates'

    ;S3

    PPPPPPPPPPPPPPP

    6

    (

    U

    (7S+26PO1 +R(33RS

    (nsteadPof triggers fire instead of a 6;/ operation. 2lso, insteadPof triggers can bedefined only on )iews. (nsteadPof triggers are used in two cases"

    +o allow a )iew that would otherwise not be modifiable to be modified. +o modify the columns of a nested table column in a )iew.

    SS+; +R(33RS

    System triggers will fire whene)er databasePwide e)ent occurs. +he following are the

    database e)ent triggers. +o create system trigger you need 26;(7(S+R 62+2B2S

    +R(33R pri)ilege.

    S+2R+U- SHU+6O:7

  • 8/13/2019 Basics Pl Sql2

    47/75

    /O3O7 /O3O11 SRFRRROR

    Synta!"

    Create or replace trigger 8trigger_name9

    YBefore > afterZ Y6atabase e)entZ on Ydatabase > schemaZ

    Q:hen #$

    Q6eclare

    PP declaration section

    Begin

    PP trigger body

    Q!ception

    PP e!ception section

    nd 8trigger_name9'

    !"

    S/9 create table user5logs#u5name )archar#A$,log5time timestamp$'

    CR2+ OR R-/2C +R(33R 21+R5/O3O7

    after logon on database

    B3(7

    insert into user5logs )alues#user,current5timestamp$'

    76 21+R5/O3O7'

    Output"

    S/9 select & from user5logs'

    no rows selected

    S/9 conn sa4ethsa4eth

    S/9 select & from user5logs'

  • 8/13/2019 Basics Pl Sql2

    48/75

  • 8/13/2019 Basics Pl Sql2

    49/75

    Output"

    S/9 create table ss #no$$'

    create table ss #no$$ &

    RROR at line "

    OR2PAAL@@" missing or in)alid option

    S/9 select & from my5errors'

    RROR5;S3

    PPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPP

    OR2PAAL@@" missing or in)alid option

    S/9 insert into student )alues#,@,D$'

    insert into student )alues#,@,D$

    &

    RROR at line "

    OR2PAALE@" table or )iew does not e!ist

    S/9 select & from my5errors'

    RROR5;S3

    PPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPP

    OR2PAAL@@" missing or in)alid option

    OR2PAALE@" table or )iew does not e!ist

    SRFR5RROR 2++R(BU+ 1U7C+(O7

    (t ta4es a single number type of argument and returns the error at the position on the

    error stac4 indicated by the argument. +he position is the top of the stac4.

    !"

    CR2+ OR R-/2C +R(33R SRFR5RROR5+R(33R

    after ser)ererror on database

  • 8/13/2019 Basics Pl Sql2

    50/75

    B3(7

    insert into my5errors )alues#ser)er5error#$$'

    76 SRFR5RROR5+R(33R'

    SUS-76 +R(33RS

    +his will fire whene)er a statement is suspended. +his might occur as the result of a

    space issue such as e!ceeding an allocated tablepace quota. +his functionality can be

    used to address the problem and allow the operatin to continue.

    Synta!"

    Create or replace trigger 8trigger_name9

    after suspend on Ydatabase > schemaZ

    Q:hen #$

    Q6eclare

    PP declaration section

    Begin

    PP trigger body

    Q!ception

    PP e!ception section nd 8trigger_name9'

    !"

    S/9 create tablespace my5space datafile

  • 8/13/2019 Basics Pl Sql2

    51/75

    (nsert more rows in student table then , you will get

    7o room to insert in your tablespace

    -ROC6URS

    2 procedure is a module that performs one or more actions.

    Synta!"-rocedure Qschema.nameQ#parameter1Q,parameter2$

    Qauthid definer > current5user is

    PP Qdeclarations Begin

    PP e!ecutable statements

    Q!ceptionPP e!ception handlers

    nd Qname'

    (n the abo)e authidclause defines whether the procedure will e!ecute under the

    authority of the definer of the procedure or under the authority of the current user.

    1U7C+(O7S

    2 function is a module that returns a )alue.

    Synta!"

    1unction Qschema.nameQ#parameter1Q,parameter2$Return return5datatype

    Qauthid definer > current5userQdeterministic

    Qparallel5enable isPP Qdeclarations

    Begin

    PP e!ecutable statements Q!ception

    PP e!ception handlers

    nd Qname'(n the abo)e authidclause defines whether the procedure will e!ecute under the

    authority of the definer of the procedure or under the authority of the current user.

  • 8/13/2019 Basics Pl Sql2

    52/75

    Deterministicclause defines, an optimi0ation hint that lets the system use a sa)ed copyof the functions return result, if a)ailable. +he quety optimi0er can choose whether to

    use the sa)ed copy or rePcall the function.

    Parallel_enableclause defines, an optimi0ation hint that enables the function to bee!ecuted in parallel when called from within S/C+statement.

    -2R2;+R ;O6S

    (n #6efault$ Out (n out

    (7

    (n parameter will act aspl/sl constant.

    OU+

    Out parameter will act as unintiali!edvariable. ou cannot pro)ide a default )alue to an outparameter. 2ny assignments made to outparameter are rolled bac4 when an e!ception is raised in

    the program.

    2n actual parameter corresponding to an outformal parameter must be a )ariable.

    (7 OU+

    (n out parameter will act as initiali!edvariable. 2n actual parameter corresponding to an in outformal parameter must be a )ariable.

    612U/+ -2R2;+RS

    6efault -arameters will not allow in the beginningand middle."utand#n "utparameters can not ha)e default )alues.

    !"

    procedure p#a in number default K, b in number default J, c in number default M$ * )alidprocedure p#a in number, b in number default J, c in number default M$ * )alild

    procedure p#a in number, b in number, c in number default M$ * )alild

    procedure p#a in number, b in number default J, c in number$ * in)alildprocedure p#a in number default K, b in number default J, c in number$ * in)alild

    procedure p#a in number default K, b in number, c in number$ * in)alild

    7O+2+(O7S

  • 8/13/2019 Basics Pl Sql2

    53/75

    7otations are of two types.

    -ositional notation 7ame notation

    :e can combine positional and name notation but positional notation can not be

    followed by the name notation.

    !" Suppose we ha)e a procedure proc#a number,b number,c number$ and we ha)e one

    anonymous bloc4 which contains ),)@, and )D'

    S/9e!ec proc #),)@,)D$ PP -ositional notation S/9e!ec proc #a=9),b=9)@,c=9)D$ PP 7amed notation

    1OR;2/ 276 2C+U2/ -2R2;+RS

    -arametes which are in calling subprogram are actual parameters. -arametes which are in called subprogram are formal parameters. (f any subprogram was called, once the call was completed then the )alues of formal

    parameters are copied to the actual parameters.

    !"

    CR2+ OR R-/2C -ROC6UR S2;-/#a in number,b out number,c in outnumber$ is

    B3(7

    dbms5output.put5line# a >>< b = < >> b >> < c = < >> c$'76 S2;-/'

    6C/2R

    ) number "= E' )@ number "= K'

    )D number "= J'B3(7

    dbms5output.put5line# ) >> < )@ = < >> )@ >> < )D = < >> )D$'76'

    Output"

    Before call) = E )@ = K )D = J

    2fter calla = E b = c = J

    2fter assignment

  • 8/13/2019 Basics Pl Sql2

    54/75

    a = E b = A c = @A2fter completion of call

    ) = E )@ = A )D = @A!@"

    CR2+ OR R-/2C 1U7#a in number,b out number,c in out number$ returnnumber (S

    B3(7 dbms5output.put5line# #a&n)l#b,$&c$$'

    b "= K' c "= M'

    dbms5output.put5line# ) >> < )@ = < >> )@ >> < )D = < >> )D$' ) "= fun#),)@,)D$'

    dbms5output.put5line# )$'76'

    Output"

    Before call) = )@ = @ )D = D2fter call

    a = b = c = DBefore assignement Result = D

    2fter assignment

    a = b = K c = M2fter call completed

    ) = )@ = K )D = MResult = DK

    RS+R(C+(O7S O7 1OR;2/ -2R2;+RS

    By declaring with specified si0e in actual parameters. By declaring formal parameters with %type specifier.

    US(73 7OCO-

    $ocop%is a hint, not a command. +his means that the compiler might silently decide thatit cant fulfill your request for a nocop%parameter.

    +he copying from formal to actual can be restricted by issuing nocop%qualifier.

  • 8/13/2019 Basics Pl Sql2

    55/75

    +o pass the out and in out parameters by reference use nocopy qualifier.

    !"

    CR2+ OR R-/2C -ROC6UR -ROC#a in out nocopy number$ (S B3(7

    PPPP 76 -ROC'

    C2// 276 NC

    Call is a S/statement, which can be used to e!ecute subprograms li4e e!ec.

    Synta!"

    Callsubprogram_name#Qargument_list$ Qinto host_variable'

    +he parantheses are always required, e)en if the subprogram ta4es no arguments. :e can not use call with outand in outparameters. Call is a S/statement, it is not )alid inside a -/S/bloc4' +he (7+Oclause is used for the output )ariables of functions only. :e can not use Te!ec with outor in outparameters. !ec is not )alid inside a -/S/bloc4'

    !"CR2+ OR R-/2C -ROC (SB3(7

    dbms5output.put5line# a >> < b = < >> b$'76 -ROC'

    Output"S/9call proc#K,J$'

    a = K b = J

    !D"CR2+ OR R-/2C 1U7C+(O7 1U7 R+UR7 F2RCH2R (SB3(7

    return

  • 8/13/2019 Basics Pl Sql2

    56/75

    hello world

    C2// B R1R7C 276 C2// B F2/U

    (n parameters by default call b% referencewhere as out and in out call b% value. :hen parameter passed by reference, a pointer to the actual parameter is passed to the

    corresponding formal parameter. :hen parameter passed by )alue it copies the )alue of the actual parameter to the formal

    parameter.

    Call by reference is faster than the call by )alue because it a)oids the copying.

    SUB-RO3R2;S OFR/O26(73

    -ossible with different number of parameters. -ossible with different types of data. -ossible with same type with obGects. Can not be possible with different types of modes. :e can o)erload local subprograms also.

    !"S/9create or replace type t as obGect#a number$'

    S/9create or replace type t as obGect#a number$'

    6C/2R

    i t "= t#K$'

    G t@ "= t@#K$' -ROC6UR -#m t$ (S

    B3(7

    dbms5output.put5line#> m.a$' 76 -' -ROC6UR -#n t@$ (S

    B3(7 dbms5output.put5line#> n.b$' 76 -' -ROC6UR -RO6UC+#a number,b number$ (S B3(7

    dbms5output.put5line#> a & b$' 76 -RO6UC+' -ROC6UR -RO6UC+#a number,b number,c number$ (S B3(7

    dbms5output.put5line#> a & b & c$' 76 -RO6UC+'B3(7

    p#i$'

    p#G$'

    product#E,K$' product#E,K,J$'76'

    Output"a = K

    b = K-roduct of a,b = @A

    -roduct of a,b = @A

  • 8/13/2019 Basics Pl Sql2

    57/75

    B71(+S O1 OFR/O26(73

    Supporting many data combinations 1itting the program to the user.

    RS+R(C+(O7S O7 OFR/O26(73

    O)erloaded programs with parameter lists that differ only by name must be called usingnamed notation.

    +he parameter list of o)erloaded programs must differ by more than parameter mode. 2ll of the o)erloaded programs must be defined within the same -/S/scope or bloc4. O)erloaded functions must differ by more than their return type.

    (;-OR+27+ -O(7+S 2BOU+ SUB-RO3R2;S

    :hen a stored subprogram is created, it is stored in the data dictionar%. +he subprogram is stored in compile form which is 4nown asp&codein addition to the

    source te!t.

    +he pPcode has all of the references in the subprogram e)aluated, and the source code istranslated into a form that is easily readable by -/S/engine.

    :hen the subprogram is called, the pPcode is read from the dis4, if necessary, ande!ecuted.

    Once it reads from the dis4, the pPcode is stored in the shared pool portion of the systemglobal area #S32$,where it can be accessed by multiple users as needed.

    /i4e all of the contents of the shared pool, pPcode is aged out of the shared poolaccording to a least recently used #/RU$algorithm.

    Subprograms can be local. /ocal subprograms must be declared in the declarati)e section of -/S/bloc4 and called

    from the e!ecutable section. Subprograms can not ha)e the declarati)e section separately. Stored subprograms can ha)e local subprograms' /ocal subprograms also can ha)e local subprograms. (f the subprogram contains a )ariable with the same name as the column name of the

    table then use the dot method to differentiate #subprogram_name.sal$.

    Subprograms can be in)alidated.

    -ROC6URS F 1U7C+(O7S

    -rocedures may return through out and in out parameters where as function must return. -rocedures can not ha)e return clause where as functions must. :e can use call statement directly for e!ecuting procedure where as we need to declare a

    )ariable in case of functions.

    1unctions can use in select statements where as procedures can not. 1unctions can call from reports en)ironment where as procedures can not. :e can use e!ec for e!ecuting procedures where as functions can not. 1unction can be used in dbms5output where as procedure can not. -rocedure call is a standalone e!ecutable statement where as function call is a part of an

    e!ecutable statement.

  • 8/13/2019 Basics Pl Sql2

    58/75

    S+OR6 F /OC2/ SUB-RO3R2;S

    +he stored subprogram is stored in compiled pPcode in the database, when the procedureis called it does not ha)e to be compiled. +he local subprogram is compiled as part of its containing bloc4. (f the containing

    bloc4 is anonymous and is run multiple times, the subprogram has to be compiled

    each time.

    Stored subprograms can be called from any bloc4 submitted by a user who has e!ecutepri)ileges on the subprogram.

    /ocal subprograms can be called only from the bloc4 containing the subprogram.

    By 4eeping the stored subprogram code separate from the calling bloc4, the calling bloc4is shorter and easier to understand.

    +he local subprogram and the calling bloc4 are one and the same, which can lead topart confusion. (f a change to the calling bloc4 is made, the subprogram will be

    recompiled as of the recompilation of the containing bloc4.

    +he compiled pPcode can be pinned in the shared pool using the 6B;S5SH2R65-OO/-ac4age. +his can impro)e performance.

    /ocal subprograms cannot be pinned in the shared pool by themsel)es. Stand alone stored subprograms can not be o)erloaded, but pac4aged subprograms can

    be o)erloaded within the same pac4age.

    /ocal subprograms can be o)erloaded within the same bloc4.

    !"CR2+ OR R-/2C -ROC6UR - (SB3(7

    dbms5output.put5line#

  • 8/13/2019 Basics Pl Sql2

    59/75

    2 stored subprogram is mar4ed as in)alid in the data dictionary if it has compile errors. 2 stored subprogram can also become in)alid if a 66/ operation is performed on one of

    its dependent obGects.

    (f a subprogram is in)alidated, the -/S/engine will automatically attempt to recompilein the ne!t time it is called.

    (f we ha)e two procedures li4e - and -@ in which - depends on -@. (f we compile -@then - is in)alidated.

    SUB-RO3R2;S 6-767C(S (7 R;O+ 62+2B2SS

    :e will call remote subprogram using connect string li4e -\OR2C/' (f we ha)e two procedures li4e - and -@ in which - depends on -@ but -@ was in

    remote database. (f we compile -@ it will not in)alidate - immediately because thedata dictionary does not trac4 remote dependencies.

    (nstead the )alidity of remote obGects is chec4ed at runtime. :hen - is called, theremote data dictionary is queried to determine the status of -@.

    - and -@ are compared to see it - needs to be recompiled, there are two differentmethods of comparision

    +imestamp ;odel Signature ;odel

    +(;S+2;- ;O6/

    s the default model used by oracle.

    this model, the timestamps of the last modifications of the two obGects arecompared.

    ast_ddl_timefield of user_ob'ectscontains the timestamp.

    e base obGect has a newer timestamp than the dependent obGect, the

    dependent obGect will be recompiled.

    (SSUS :(+H +H(S ;O6/

    (f the obGects are in different time 0ones, the comparison is in)alid. :hen - is in a client side -/S/engine such as oracle forms, in this case it may not

    possible to recompile -, because the source for it may not be included with the forms.

    S(372+UR ;O6/

    :hen a procedure is created, a signature is stored in the data dictionary in addition to thepPcode.

    +he signature encodes the types and order of the parametes. :hen - is compiled the first time, the signature of -@ is included. +hus, - only needs to

    recompiled when the signature of -@ changes. (n order to use the signature model, the parameter R;O+56-767C(S5;O6must be set

    to S(372+UR. +his is a parameter in the database initiali0ation file.

    +HR :2S O1 S++(73 +H(S ;O6

    2dd the line R;O+56-767C(S5;O6=S(372+UR to the database initiali0ation file. +hene!t time the database is started, the mode will be set to S(372+URfor all sessions.

    2lter system set remote5dependencies5mode = signature'

  • 8/13/2019 Basics Pl Sql2

    60/75

    +his will affect the entire database #all sessions$ from the time the statement is issued. ou must ha)e the 2/+RSS+;pri)ilege to issue this command.

    2lter session set remote5dependencies5mode = signature' +his will only affect your session

    (SSUS :(+H +H(S ;O6/

    Signatures dont get modified if the default )alues of formal parameters arechanged.

    Suppose -@ has a default )alue for one of its parameters, and - is using thisdefault )alue. (f the default in the specification for -@ is changed, - will not be

    recompiled by default. +he old )alue for the default parameter will still be used

    until- is manually recompiled.

    (f - is calling a pac4aged procedure -@, and a new o)erloaded )ersion of -@ is added tothe remote pac4age, the signature is not changed. - will still use the old )ersion#notthe new o)erloaded one$ until - is recompiled manually.

    1OR:2R6 6C/R2+(O7

    Before going to use the procedure in any other subprogram or other bloc4 , you must

    declare the prototype of the procedure in declarati)e section.

    !" 6C/2R -ROC6UR - (S B3(7

    dbms5output.put5line#

  • 8/13/2019 Basics Pl Sql2

    61/75

    !@"6C/2R

    -ROC6UR -@' PP forward declaration -ROC6UR -D'

    -ROC6UR - (S B3(7

    dbms5output.put5line#

  • 8/13/2019 Basics Pl Sql2

    62/75

    S/9!ec user2.p

    (f suppose userB also ha)ing student@ table then which table will populate whether

    user2s or userBs.

    +he answer is user2s student@ table only because by default the procedure will e!ecute

    under the pri)lige set of its owner.+he abo)e procedure is 4nown as definers procedure.

    HO: +O -O-U/2+ USR Bs +2B/

    Oracle introduces#nvoker(s and Definer(s rights) By default it will use the definers rights. 2n in)o4ers rights routine can be created by using 2U+H(6clause to populate the

    userBs table.

    (t is )alid for standPalone subprograms, pac4age specifications, and obGect typespecifications only.

    user2 created the following procedure

    CR2+ OR R-/2C -ROC6UR -2U+H(6 CURR7+5USR (S

    cursor is select &from student'B3(7

    for ) in c loop insert into student@ )alues#).no,).name,).mar4s$'

    end loop'76 -'

    +hen grant e!ecute pri)ilege on p to userB.

    !ecuting the procedure by userB, which populates userBs table.

    +he abo)e procedure is called in)o4ers procedure.(nstead of current5user of authid clause, if you use definer then it will be called definer

    procedure.

    S+OR6 SUB-RO3R2;S 276 RO/S

    we ha)e two users sa4eth and sudha in which sa4eth has student table and sudha doesnot.

    Sudha is going to create a procedure based on student table owned by sa4eth. Beforedoing this sa4eth must grant the permissions on this table to sudha.

    S/9conn sa4ethsa4ethS/9grant all on student to sudha'

    then sudha can create procedure

    S/9conn sudhasudha

    CR2+ OR R-/2C -ROC6UR - (S

    cursor c is select &from sa4eth.student'B3(7

    for ) in c loop

  • 8/13/2019 Basics Pl Sql2

    63/75

    dbms5output.put5line#T7o = T >> ).no$' end loop'76 -'

    here procedure will be created.

    (f the same pri)ilege was granted through a role it wont create the procedure.!amine the following code

    S/9conn sa4ethsa4eth

    S/9create role sa4eth5role'

    S/9grant all on student to sa4eth5role'

    S/9grant sa4eth5role to sudha'then conn sudhasudha

    CR2+ OR R-/2C -ROC6UR - (S

    cursor c is select &from sa4eth.student'B3(7

    for ) in c loop dbms5output.put5line#T7o = T >> ).no$'

    end loop'76 -'

    +he abo)e code will raise error instead of creating procedure .

    +his is because of early binding which -/S/uses by default in which references are

    e)aluated in compile time but when you are using a role this will affect immediately.

    (SSUS :(+H (7FORS R(3H+S

    (n an in)o4ers rights routine, e!ternal references in S/statements will be resol)edusing the callers pri)ilege set.

    But references in -/S/statements are still resol)ed under the owners pri)ilege set.+R(33RS, F(:S 276 (7FORS R(3H+S

    2 database trigger will always be e!ecuted with definers rights and will e!ecute underthe pri)ilege set of the schema that owns the triggering table.

    +his is also true for -/S/function that is called from a )iew. (n this case, the functionwill e!ecute under the pri)ilege set of the )iews owner.

    -2C23S

    2packageis a container for related obGects. (t has specification and body. ach of themis stored separately in data dictionary.

    -2C23 S7+2N

    Create or replace pac4age 8package_name9 is

    PP pac4age specification includes subprograms signatures, cursors and global orpublic )ariables.

  • 8/13/2019 Basics Pl Sql2

    64/75

    nd 8package_name9'

    Create or replace pac4age body 8package_name9 is

    PP pac4age body includes body for all the subprograms declared in the spec, pri)ate

    Fariables and cursors. Begin

    PP initiali0ation section !ception

    PP !ception handling seciton nd 8package_name9'

    (;-OR+27+ -O(73S 2BOU+ -2C23S

    +he first time a pac4aged subprogram is called or any reference to a pac4aged )ariable ortype is made, the pac4age is instantiated.

    ach session will ha)e its own copy of pac4aged )ariables, ensuring that two sessionse!ecuting subprograms in the same pac4age use different memory locations.

    (n many cases initiali0ation needs to be run the first time the pac4age is instantiatedwithin a session. +his can be done by adding initiali0ation section to the pac4age bodyafter all the obGects.

    -ac4ages are stored in the data dictionary and can not be local. -ac4aged subprograms has an ad)antage o)er stand alone subprogram. :hen e)er any reference to pac4age, the whole pac4age pPcode was stored in shared

    pool of S32.

    -ac4age may ha)e local subprograms. ou can include authid clause inside the pac4age spec not in the body. +he e!ecution section of a pac4age is 4now as initiali0ation section. ou can ha)e an e!ception section at the bottom of a pac4age body. -ac4ages subprograms are not in)alidated.

    CO;-(/(73 -2C23S

    S/92lter pac4age -3 compile' S/92lter pac4age -3 compile specification' S/92lter pac4age -3 compile body'

    -2C23 6-767C(S

    +he pac4age body depends on the some obGects and the pac4age header. +he pac4age header does not depend on the pac4age body, which is an ad)antage of

    pac4ages.

    :e can change the pac4age body with out changing the header.

    -2C23 RU7+(; S+2+

    -ac4age runtime state is differ for the following pac4ages.

    Serially reusable pac4ages 7on serially reusable pac4ages

    SR(2// RUS2B/ -2C23S

  • 8/13/2019 Basics Pl Sql2

    65/75

    +o force the oracle to use serially reusable )ersion then include -R23;2 SR(2//5RUS2B/in both pac4age spec and body, !amine the following pac4age.

    CR2+ OR R-/2C -2C23 -3 (S

    pragma serially5reusable'procedure emp5proc'

    76 -3'

    CR2+ OR R-/2C -2C23 BO6 -3 (S

    pragma serially5reusable'cursor c is select ename from emp'

    -ROC6UR ;-5-ROC (S

    )5ename emp.ename%type'

    )5flag boolean "= true')5numrows number "= A'

    B3(7

    if not c%isopen then

    open c'

    end if'while )5flag loop

    fetch c into )5ename'

    )5numrows "= )5numrows ] ' if )5numrows = K then

    )5flag "= false' end if'

    dbms5output.put5line#> )5ename$' end loop'76 ;-5-ROC'76 -3'

    S/9e!ec p4g.emp5proc

    name = S;(+Hname = 2//7name = :2R6name = O7S

    name = ;2R+(7

    S/9e!ec p4g.emp5proc

    name = S;(+Hname = 2//7name = :2R6name = O7S

    name = ;2R+(7

    +he abo)e pac4age displays the same output for each e!ecution e)en though the cursor isnot closed.

    Because the serially reusable )ersion resets the state of the cursor each time it wascalled.

    7O7 SR(2// RUS2B/ -2C23S

  • 8/13/2019 Basics Pl Sql2

    66/75

    +his is the default )ersion used by the oracle, e!amine the following pac4age.

    CR2+ OR R-/2C -2C23 -3 (S

    procedure emp5proc'76 -3'

    CR2+ OR R-/2C -2C23 BO6 -3 (Scursor c is select ename from emp'

    -ROC6UR ;-5-ROC (S

    )5ename emp.ename%type'

    )5flag boolean "= true')5numrows number "= A'

    B3(7

    if not c%isopen then

    open c' end if'

    while )5flag loop fetch c into )5ename'

    )5numrows "= )5numrows ] '

    if )5numrows = K then )5flag "= false' end if'

    dbms5output.put5line#> )5ename$' end loop'76 ;-5-ROC'76 -3'

    S/9e!ec p4g.emp5proc

    name = S;(+Hname = 2//7

    name = :2R6name = O7S

    name = ;2R+(7

    S/9e!ec p4g.emp5proc

    name = B/2name = C/2R

    name = SCO++name = (73

    name = +UR7R

    +he abo)e pac4age displays the different output for each e!ecution e)en though thecursor is not closed.

    Because the nonPserially reusable )ersion remains the state of the cursor o)er databasecalls.6-767C(S O1 -2C23 RU7+(; S+2+

    6ependencies can e!ists between pac4age state and anonymous bloc4s.!amine the following program

    Create this pac4age in first sessionCR2+ OR R-/2C -2C23 -3 (S

  • 8/13/2019 Basics Pl Sql2

    67/75

    ) number "= K'procedure p'

    76 -3'

    CR2+ OR R-/2C -2C23 BO6 -3 (S-ROC6UR - (SB3(7

    dbms5output.put5line#> )$') "= A'dbms5output.put5line#> )$'76 -'76 -3'

    Connect to second session, run the following code.

    B3(7

    p4g.p'76'

    +he abo)e code wil wor4.

    3o bac4 to first session and recreate the pac4age using create.

    +hen connect to second session and run the following code again.

    B3(7

    p4g.p' 76'

    +his abo)e code will not wor4 because of the following.

    +he anonymous bloc4 depends on p4g. +his is compile time dependency. +here is also a runtime dependency on the pac4aged )ariables, since each session has its

    own copy of pac4aged )ariables. +hus when p4g is recompiled the runtime dependency is followed, which in)alidates the

    bloc4 and raises the oracle error.

    Runtime dependencies e!ist only on pac4age state. +his includes )ariables and cursorsdeclared in a pac4age.

    (f the pac4age had no global )ariables, the second e!ecution of the anonymous bloc4would ha)e succeeded.

    -UR(+ /F/S

    (n general, calls to subprograms are procedural, they cannot be called from S/

    statements. Howe)er, if a standPalone or pac4aged function meets certain restrictions, it

    can be called during e!ecution of a S/ statement.

    UserPdefined functions are called the same way as builtPin functions but it must meet

    different restrictions. +hese restrictions are defined in terms of purity le)els.

    +here are four types of purity le)els.

    :76S PP :rites 7o 6atabase State

    R76S PP Reads 7o 6atabase State

    :7-S PP :rites 7o -ac4age State

  • 8/13/2019 Basics Pl Sql2

    68/75

  • 8/13/2019 Basics Pl Sql2

    69/75

    return

  • 8/13/2019 Basics Pl Sql2

    70/75

  • 8/13/2019 Basics Pl Sql2

    71/75

    +he 6B;S5SH2R65-OO/pac4age allows you to pin obGects in the shared pool. :hen anobGect is pinned, it will ne)er be aged out until you request it, no matter how full the

    pool gets or how often the obGect is accessed. +his can impro)e performance, as it ta4es

    time to reload a pac4age from dis4.

    6B;S5SH2R65-OO/has four procedures

    - U7- S(?S 2BOR+65RUS+5+HRSHO/6

    -

    +he 6B;S5SH2R65-OO/.-procedure is used to pin obGects in the pool.

    Synta!"

    -ROC6UR -#ob'ect_name)archar@,flag char default T-$'

    Here the flag represents different types of flag )alues for different types of obGects.

    - PP -ac4age, function or procedure PP Sequence

    R PP +riggerC PP S/ Cursor

    + PP ObGect typeS PP a)a source

    C PP a)a class

    R PP a)a resource6 PP a)a shared data

    U7-

    U7-is the only way to remo)e a 4ept obGect from the shared pool, without restartingthe database. ept obGects are ne)er aged out automatically.

    Synta!"

    -ROC6UR U7-#ob'ect_name)archar@, flagchar default T-$'

    S(?S

    S(?Swill echo the contents of the shared pool to the screen.

    Synta!"-ROC6UR S(?S#minsi!enumber$'

    ObGects with greater than the minsi!ewill be returned. S(?Suses 6B;S5OU+-U+to returnthe data.

    2BOR+65RUS+5+HRSHO/6

  • 8/13/2019 Basics Pl Sql2

    72/75

    :hen the database determines that there is not enough memory in the shared pool tosatisfy a gi)en request, it will begin aging obGects out until there is enough memory. (t

    enough obGects are aged out, this can ha)e a performance impact on other databasesessions. +he 2BOR+65RUS+5+HRSHO/6 can be used to remedy this.

    Synta!"

    -ROC6UR 2BOR+65RUS+5+HRSHO/6#threshold_si!enumber$'

    Once this procedure is called, oracle will not start aging obGects from the pool unless atleast threshold_si!ebytes is needed.

    62+2 ;O6/ 1OR SUB-RO3R2;S 276 -2C23S

    USR5OBC+S USR5SOURC USR5RRORS 6B25OBC+S 6B25SOURC 6B25RRORS 2//5OBC+S 2//5SOURC 2//5RRORS

    2U+O7O;OUS +R27S2C+(O7

    -rior to OracleIi, there was no way in which some S/ operations within a transaction

    could be committed independent of the rest of the operations. Oracle allows this,howe)er, through autonomous transactions. 2n autonomous transactionis a

    transaction that is started within the conte!t of another transaction, 4nown as parent

    transaction, but is independent of it. +he autonomous transaction can be committed orrolled bac4 regardless ot the state of the parent transaction.

    !"

    CR2+ OR R-/2C +R(33R 2U+O7O;OUS5+R27S2C+(O75+R(33R

    after insert on student6C/2R

    pragma autonomous5transaction'B3(7

    update student set mar4s = KKK'

    commit'76 2U+O7O;OUS5+R27S2C+(O75+R(33R'

    Output"

    S/9select & from student'

    7O 72 ;2RS

    PPPPP PPPPP PP PPPPPPPPPP a

    @ b @@@

  • 8/13/2019 Basics Pl Sql2

    73/75

  • 8/13/2019 Basics Pl Sql2

    74/75

    B3(7

    select count#&$ into ct from student where no = "old.no'76 ;U+2+(735+R(33R'

    Output"

    S/9delete student where no = 'delete student where no =

    &RROR at line "

    OR2PAEAL" table SCO++.S+U67+ is mutating, triggerfunction may not see itOR2PAJK@" at XSCO++.+X, line E

    OR2PAEAII" error during e!ecution of trigger

  • 8/13/2019 Basics Pl Sql2

    75/75