PL/SQL programming Procedures and Cursors Lecture 4 [Part 2]
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 ."23 111 [/0E"E 111]
SQL scripts
Set of commands to run in se4uence1 Stored as a te5t fi&e *e1g1 using !otepad+ on a disand 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
The SQL Procedure
B&oc- of SQL statements stored in the #ata dictionar( and ca&&ed )( app&ications Satisfies fre4uent&(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 2rac&e 9 or o&der %ids securit( as #B% ma( grant access to procedures not ta)&es, therefore some users cannot access ta)&es e5cept through a procedure
Bui&ding a procedure: contents
;1 21 =1 41 >1 91 ?1
Create or rep&ace command 2)<ect to )e created !ame of o)<ect %n( 8aria)&es accessed or imported Loca& 8aria)&es dec&ared Code End procedure dec&aration
;1
Create or rep&ace command 2)<ect to )e created !ame of o)<ect %n( 8aria)&es accessed or imported #ec&ared &oca& 8aria)&es Code End procedure dec&aration
21
This procedure is ca&&ed inf&ation@rise and uses a 8aria)&e accessed as inf@rate 'hich is a num)er, this is passed in 'hen the procedure is used1 t simp&( updates the sa&ar( )( the rate of inf&ation1
=1 41
Create or replace procedure inflation_rise (inf_rate in number) e!in update employee set salary " salary # (salary $ inf_rate % &'')( commit( End(
>1
91 ?1
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 it has )een amended1 .or ease of use, it is )est to 'rite procedures in notepad and then run them, this means that the( can )e easi&( edited and (ou ha8e a )ac-up cop(
E5amp&e
CREATE OR REPLACE PROCEDURE validate_customer (v_cust VARCHAR) AS v_count BEGIN SELEC C!UN (") NUMBER;
Loca& 8aria)&es used )( procedure SQL
INTO v_count
%n( 8aria)&es passed into procedure
#R!M CUS !MER $HERE CUS _C!%E & v_cust; IF v_count > 0 THEN
%BMS_!U 'U ('U _L)NE(*customer valid+); ELSE %BMS_!U 'U ('U _L)NE(*customer not reco,nised+); END IF; END;
Cursors in SQL
Ena)&es users to &oop round a se&ection of data1 Stores data se&ect from a 4uer( in a temp area for use 'hen opened1 $se comp&e5 actions 'hich 'ou&d not )e feasi)&e in standard SQL se&ection 4ueries
% #E32A
#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 B>CC pa( rise1 f the pa( rise does not ta-e them to the min for their ne' grade the( are to )e increased to the min for that grade f the pa( rise mo8es them a)o8e the ma5 for a grade the( are to )e increased to the ma5 on&(1
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 Cursor cur_emp is E1g1
Select emp_id, surname name, grade, salary From employee Where regrade is true;
Cursors
% cursor is a temp store of data1 The data is popu&ated 'hen the cursor is opened1 2nce 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
Cursor )unctions
Acti e set "#$% S&'() ".$$ /01+S Cursor ""33 SC0(( "3"$ A5A&S "%67 F0,5 C*+,&A1A2+, A1A*4S( C*+,A1A*4S( Current ro!
Controllin! Cursor
1o 4es 5+C*A,+ 5+C*A,+ 0:+1 0:+1 F+(C) F+(C) +&:(4= C*0S+ C*0S+
Create a
named S8* area
'denti9y
the acti e set
*oad the
current ro! into aria;les
(est 9or
e<isting ro!s
,elease
the acti e set
,eturn to
F+(C) i9 ro!s 9ound
Controllin! Cursor*
0pen the cursor.
Cursor
:ointer
Fetch a ro! 9rom the cursor. :ointer
Cursor
Continue until empty. :ointer
Cursor
Close the cursor.
Cursor
Cursor +ttributes
2)tain status information a)out a cursor1
Attri;ute >'S0:+1 >10(F0@15 >F0@15 (ype ?oolean ?oolean ?oolean 5escription + aluates to (,@+ i9 the cursor is open + aluates to (,@+ i9 the most recent 9etch does not return a ro! + aluates to (,@+ i9 the most recent 9etch returns a ro!; complement o9 >10(F0@15 + aluates to the total num;er o9 ro!s returned so 9ar
>,0WC0@1(
1um;er
*#4+,
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_sample notfound; update employee set salary ! salary " #$$ where empid ! v_empid; end loop; ,eclare Cursor 0ata returned by cursor
-**4# ##./, -*#*4 ./#4,
&pen cursor for use' (oops round each value returned by the cursor
Stop when no more records are found %nd;
)lace the value from the cursor into the variable v_empid
!otepad fi&e ca&&ed: Create_procedures.sql
;+ 2pen SQLDP&us and &ogon 2+ %t the prompt enter: -create_procedures Eou '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&&(
$se of conditions
f statements can )e used
1f 2condition> 3hen 4'' %nd if;
E5amp&e
. .. .. . IF IF v_ena v_ena e e v_$o% v_$o% &! &! v_'e(tno v_'e(tno v_ne+_co v_ne+_co END END IF; IF; . .. .. . ! ! "#ILLER" "#ILLER" THEN THEN "SALES#AN"; "SALES#AN"; &! &! )*; )*; &! &! ,a,a- . . 0./0; 0./0;
"emem)er to end the if statement and use of indented code 'i&& ma-e it easier to de)ugA
The H S2PE! %ttri)ute
.etch ro's on&( 'hen the cursor is open1 $se the H S2PE! cursor attri)ute )efore performing a fetch to test 'hether the cursor is open1 E5amp&e
IF IF NOT NOT cu0_,a cu0_,a (-e1ISOPEN (-e1ISOPEN THEN THEN OPEN OPEN cu0_,a cu0_,a (-e; (-e; END END IF; IF; LOOP LOOP FETCH FETCH cu0_,a cu0_,a (-e... (-e...
Process
the ro's of the acti8e set con8enient&( )( fetching 8a&ues into a PL/SQL "EC2"#1 E5amp&e
DECLARE DECLARE CURSOR CURSOR e e (_cu0,o0 (_cu0,o0 IS IS SELECT SELECT e e (no2 (no2 ena ena e e FRO# e FRO# e (; (; e e (_0eco0' (_0eco0' e e (_cu0,o01RO3T4PE; (_cu0,o01RO3T4PE; BEGIN BEGIN OPEN OPEN e e (_cu0,o0; (_cu0,o0; LOOP LOOP FETCH FETCH e e (_cu0,o0 (_cu0,o0 INTO INTO e e (_0eco0'; (_0eco0'; ... ...
Cursors and "ecords
Cursor .2" Loops
S(nta5
FOR FOR record_name record_name IN IN cursor_name cursor_name LOOP LOOP statement1 ; statement1 ; statement2 ; statement2 ; . .. .. . END END LOOP; LOOP;
The
cursor .2" &oop is a shortcut to process cursors1 mp&icit&( opens, fetches, and c&oses cursor1 The record is imp&icit&( dec&ared1
Cursor .2" Loops: %n E5amp&e
"etrie8e emp&o(ees one )( one unti& no more are &eft1 E5amp&e
DECLARE DECLARE CURSOR CURSOR e e (_cu0,o0 (_cu0,o0 IS IS SELECT ena e2 'e(tno SELECT ena e2 'e(tno FRO# e FRO# e (; (; BEGIN BEGIN FOR FOR e e (_0eco0' (_0eco0' IN IN e e (_cu0,o0 (_cu0,o0 LOOP LOOP 55 55 6 6 (-6c6t (-6c6t o(en o(en an' an' 6 6 (-6c6t (-6c6t 7etc8 7etc8 occu0 occu0 IF IF e e (_0eco0'.'e(tno (_0eco0'.'e(tno ! ! )0 )0 THEN THEN ... ... END END LOOP; LOOP; 55 55 6 6 (-6c6t (-6c6t c-o,e c-o,e occu0, occu0, END; END;
Seminar e5ercise
The purpose of this e5ercise is to create a procedure 'hich, 'hen e8o-ed, 'i&& increase the sa&ar( of a grade )( B>CC or B;CCC depending on the &e8e& of the grade1 Eou 'i&& need to popu&ate the ta)&e first 'ith a minimum of ;C 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 2nce (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 s.o/ errors 'i&& &ist an( pro)&ems 'ith the code1 To run the procedure (ou t(pe execute 0procedure name> at the SQL prompt1