Procedures and Cursors

Embed Size (px)

Citation preview

  • 8/13/2019 Procedures and Cursors

    1/24

    PL/SQL programmingProcedures and Cursors

    Lecture 4 [Part 2]

  • 8/13/2019 Procedures and Cursors

    2/24

    SQL refresher Basic commands

    SELECT, !SE"T, #ELETE, $P#%TE

    %&'a(s remem)er to state the ta)&e*s+ (ou

    are se&ecting data from

    oin ta)&es )( primar( and foreign -e(s

    .i&ter data using 0E"E c&ause

    SELECT 111 ."3 111 [0E"E 111]

  • 8/13/2019 Procedures and Cursors

    3/24

    SQL scripts Set of commands to run in seuence1 Stored as a te5t fi&e *e1g1 using !otepad+ on a dis-

    and not in the data dictionar(1 t is accessed )( fi&e

    name

    E5ecuted using 6 or Start1

    Script called:Create_lecturer_copy.sql

    Executed by:

    SQL> @create_lecturer_copy.sql

  • 8/13/2019 Procedures and Cursors

    4/24

    The SQL Procedure B&oc- of SQL statements stored in the #ata dictionar(

    and ca&&ed )( app&ications

    Satisfies freuent&(7used or critica& app&ication &ogic hen ca&&ed a&& code 'ithin the procedure is e5ecuted

    *un&i-e pac-ages+ %ction ta-es p&ace on ser8er not c&ient #oes not return 8a&ue to ca&&ing program !ot a8ai&a)&e in rac&e 9 or o&der %ids securit( as #B% ma( grant access to procedures not

    ta)&es, therefore some users cannot access ta)&es e5ceptthrough a procedure

  • 8/13/2019 Procedures and Cursors

    5/24

    Bui&ding a procedure: contents;1 Create or rep&ace command

    21 )

  • 8/13/2019 Procedures and Cursors

    6/24

    ;1 Create or rep&ace

    command21 )

  • 8/13/2019 Procedures and Cursors

    7/24

    Compi&ing and e5ecuting

    procedures Li-e an( program the code needs to )e compi&ed1

    6inf&ation@rise compi&es the procedure in a fi&e 'ith this name ma-es it a8ai&a)&e to the data)ase

    E5ecute inf&ation@rise e5ecutes the procedure1

    "emem)er to compi&e a procedure again once ithas )een amended1

    .or ease of use, it is )est to 'rite procedures in

    notepadand then run them, this means that the(

    can )e easi&( edited and (ou ha8e a )ac-up cop(

  • 8/13/2019 Procedures and Cursors

    8/24

    E5amp&eCREATE OR REPLACE PROCEDUREvalidate_customer (v_cust VARCHAR)

    AS

    v_count NUMBER;

    BEGIN

    SELEC C!UN(") INTOv_count

    #R!M CUS!MER

    $HERE CUS_C!%E & v_cust;

    IF v_count > 0 THEN

    %BMS_!U'U'U_LNE(*customer valid+);

    ELSE

    %BMS_!U'U'U_LNE(*customer not reco,nised+);

    END IF;

    END;

    %n( 8aria)&espassed into

    procedure

    Loca& 8aria)&es

    used )( procedure

    SQL

  • 8/13/2019 Procedures and Cursors

    9/24

    Cursors in SQL Ena)&es users to &oop round a se&ection of

    data1

    Stores data se&ect from a uer( in a temp

    area for use 'hen opened1

    $se comp&e5 actions 'hich 'ou&d not )e

    feasi)&e in standard SQL se&ection ueries

  • 8/13/2019 Procedures and Cursors

    10/24

    % #E3A #ata has )een se&ected from the emp&o(ee ta)&e1

    This data needs to )e amended in the fo&&o'ing

    'a(: Each mem)er of staff is to )e increased one grade1

    Each mem)er of staff is to ha8e a > pa( rise1

    f the pa( rise does not ta-e them to the min for theirne' grade the( are to )e increased to the min for thatgrade

    f the pa( rise mo8es them a)o8e the ma5 for a gradethe( are to )e increased to the ma5 on&(1

  • 8/13/2019 Procedures and Cursors

    11/24

    S(nta5 for Cursors #ec&ared as a 8aria)&e in the same 'a( as

    standard 8aria)&es

    dentified as cursor t(pe

    SQL inc&uded

    E1g1Cursor cur_emp is

    Select emp_id, surname name, grade,

    salary

    From employee

    Where regrade is true;

  • 8/13/2019 Procedures and Cursors

    12/24

    Cursors % cursor is a temp store of data1

    The data is popu&ated 'hen the cursor is opened1

    nce opened the data must )e mo8ed from the

    temp area to a &oca& 8aria)&e to )e used )( the

    program1 These 8aria)&es must )e popu&ated in the

    same order that the data is he&d in the cursor1 The data is &ooped round ti&& an e5it c&ause is

    reached1

  • 8/13/2019 Procedures and Cursors

    13/24

    Actie setActie set

    Current ro!Current ro!Cursor

    "#$% S&'() C*+-

    "$$ /01+S &A1A2+""33 SC0(( A1A*4S(

    "3"$ A5A&S C*+-

    "%67 F05 A1A*4S(

    Cursor unctionsCursor unctions

  • 8/13/2019 Procedures and Cursors

    14/24

    Controllin! CursorControllin! Cursor

    Create aCreate anamednamed

    S8* areaS8* area

    5+C*A+5+C*A+5+C*A+5+C*A+

    'denti9y'denti9ythe actiethe actie

    setset

    0:+10:+10:+10:+1

    *oad the*oad thecurrentcurrent

    ro! intoro! into

    arialesariales

    F+(C)F+(C)F+(C)F+(C)

    (est 9or(est 9ore

  • 8/13/2019 Procedures and Cursors

    15/24

    Controllin! Cursor*Controllin! Cursor*0pen the cursor.0pen the cursor.

    CursorCursor

    :ointer:ointer

    Fetch a ro! 9rom the cursor.Fetch a ro! 9rom the cursor.

    CursorCursor

    :ointer:ointer

    Continue until empty.Continue until empty.

    CursorCursor

    :ointer:ointer

    Close the cursor.Close the cursor.

    CursorCursor

  • 8/13/2019 Procedures and Cursors

    16/24

    Cursor +ttributesCursor +ttributes

    Attriute (ype 5escription

    >'S0:+1 ?oolean +aluates to (+ i9 the cursor

    is open

    >10(F015 ?oolean +aluates to (+ i9 the most

    recent 9etch does not return a ro!

    >F015 ?oolean +aluates to (+ i9 the most

    recent 9etch returns a ro!;complement o9 >10(F015

    >0WC01( 1umer +aluates to the total numer o9

    ro!s returned so 9ar

    )tain status information a)out a cursor1

  • 8/13/2019 Procedures and Cursors

    17/24

    Create or replace procedure proc_test as

    v_empid number;

    Cursor cur_sample is

    Select empid from employee

    where grade > 4;

    Begin

    open cur_sample;

    loop

    fetch cur_sample into v_empid;

    exit when cur_samplenotfound;

    update employeeset salary ! salary " #$$

    where empid ! v_empid;

    end loop;

    %nd;

    &pen cursor for use'

    (oops round each value

    returned by the cursor

    )lace the value from thecursor into the variable

    v_empid

    Stop when

    no morerecords

    are found

    *#4+,

    -**4#

    ##./,

    -*#*4

    ./#4,

    0ata

    returnedby cursor

    ,eclare

    Cursor

  • 8/13/2019 Procedures and Cursors

    18/24

    !otepad fi&e ca&&ed:

    Create_procedures.sql

    ;+ pen SQLDP&us and &ogon

    2+ %t the prompt enter:

    -create_procedures

    ou 'i&& get a prompt 'hich shou&d sa( Fprocedure createdG

    =+ To run the procedure enter:

    Execute proc_test

    4+ f (ou chec- (our data (ou shou&d no' find that the procedure has run successfu&&(

  • 8/13/2019 Procedures and Cursors

    19/24

    $se of conditions f statements can )e used

    1f 2condition> 3hen

    ''

    %nd if; E5amp&e

    "emem)er to end the if statement and use of indented code'i&& ma-e it easier to de)ugA

    . . .

    IF v_enae ! "#ILLER" THEN

    v_$o% &! "SALES#AN";

    v_'e(tno &! )*; v_ne+_co &! ,a- 0./0;

    END IF;

    . . .

    . . .

    IF v_enae ! "#ILLER" THEN

    v_$o% &! "SALES#AN";

    v_'e(tno &! )*; v_ne+_co &! ,a- 0./0;

    END IF;

    . . .

  • 8/13/2019 Procedures and Cursors

    20/24

    The HSPE! %ttri)ute .etch ro's on&( 'hen the cursor is open1

    $se the HSPE! cursor attri)ute )efore

    performing a fetch to test 'hether the cursor isopen1

    E5amp&e

    IF NOT cu_,a(-e1ISOPEN THEN

    OPEN cu_,a(-e;

    END IF;

    LOOP

    FETCH cu_,a(-e...

    IF NOT cu_,a(-e1ISOPEN THEN

    OPEN cu_,a(-e;

    END IF;

    LOOP

    FETCH cu_,a(-e...

  • 8/13/2019 Procedures and Cursors

    21/24

    DECLARECURSOR e(_cu,o IS

    SELECT e(no2 enae FRO# e(;

    e(_eco' e(_cu,o1RO3T4PE;BEGIN OPEN e(_cu,o; LOOP FETCH e(_cu,o INTO e(_eco'; ...

    DECLARECURSOR e(_cu,o IS

    SELECT e(no2 enae FRO# e(;

    e(_eco' e(_cu,o1RO3T4PE;BEGIN OPEN e(_cu,o; LOOP FETCH e(_cu,o INTO e(_eco'; ...

    Cursors and "ecordsCursors and "ecords

    Process the ro's of the acti8e setcon8enient&( )( fetching 8a&ues into a

    PL/SQL "EC"#1

    E5amp&e

  • 8/13/2019 Procedures and Cursors

    22/24

    Cursor ." LoopsCursor ." Loops

    FOR record_nameIN cursor_nameLOOP

    statement1;

    statement2;

    . . .

    END LOOP;

    FOR record_nameIN cursor_nameLOOP

    statement1;

    statement2;

    . . .

    END LOOP;

    S(nta5

    The cursor ." &oop is a shortcut to processcursors1

    mp&icit&( opens, fetches, and c&oses cursor1

    The record is imp&icit&( dec&ared1

  • 8/13/2019 Procedures and Cursors

    23/24

    Cursor ." Loops: %n E5amp&eCursor ." Loops: %n E5amp&e"etrie8e emp&o(ees one )( one unti& no more are"etrie8e emp&o(ees one )( one unti& no more are

    &eft1&eft1

    E5amp&eE5amp&e

    DECLARE CURSOR e(_cu,o IS SELECT enae2 'e(tno FRO# e(;BEGIN

    FOR e(_eco' IN e(_cu,o LOOP 55 6(-6c6t o(en an' 6(-6c6t 7etc8 occu IF e(_eco'.'e(tno ! )0 THEN ... END LOOP; 55 6(-6c6t c-o,e occu,END;

    DECLARE CURSOR e(_cu,o IS SELECT enae2 'e(tno FRO# e(;BEGIN

    FOR e(_eco' IN e(_cu,o LOOP 55 6(-6c6t o(en an' 6(-6c6t 7etc8 occu IF e(_eco'.'e(tno ! )0 THEN ... END LOOP; 55 6(-6c6t c-o,e occu,END;

  • 8/13/2019 Procedures and Cursors

    24/24

    Seminar e5ercise The purpose of this e5ercise is to create a procedure 'hich, 'hen

    e8o-ed, 'i&& increase the sa&ar( of a grade )( > or ;

    depending on the &e8e& of the grade1 ou 'i&& need to popu&ate the

    ta)&e first 'ith a minimum of ; entries, the empgrade 8a&ue shou&d

    )e )et'een ; and >, and the idea is the higher the grade the higher the

    manager1 There is a script for this on the B&ac-Board1

    nce (ou ha8e done this (ou shou&d compi&e the code this 'i&& then

    indicate if the procedure has compi&ed or not1 f compi&ation is

    unsuccessfu& entering the command so/ errors 'i&& &ist an(

    pro)&ems 'ith the code1 To run the procedure (ou t(pe execute

    0procedure name>at the SQL prompt1