You are on page 1of 16

Chapter 19

PROCEDURES, FUNCTIONS AND PACKAGES


What is a stored procedure? Advantages of stored procedures Creating a stored procedure Creating a stored function Recompiling Types of parameters Parameter modes NCOPY compiler hints RAI !"APP#ICATION"!RROR procedure Pac$ages

What is a stored procedure?


As %e have seen in the introduction to P#& '# that there are t%o types of P#& '# (loc$s ) anonymous and stored procedures* A stored procedure is a P#& '# (loc$ that is stored in the data(ase %ith a name* It is invo$ed using the name* !ach procedure is meant for a specific purpose* A stored procedure is stored in the data(ase as an o(+ect* It is also called as data(ase procedure as it is stored in the data(ase* A procedure may ta$e one or more parameters* If a procedure ta$es parameters then these parameters are to (e supplied at the time of calling the procedure*

What is a function?
A function is similar to procedure, e-cept that it returns a value* The calling program should use the value returned (y the function*

Advantages of stored procedures


1

tored procedures and functions offer the follo%ing (enefits*

Reduced network traffic


tored procedures are stored in the data(ase on the server* In order to invo$e a stored procedure a client has to use only the name of the stored procedure* This results in reduced net%or$ traffic (ecause only the name is passed to server and not the entire P#& '# (loc$*

Better Performance
tored procedures improve performance (ecause the data(ase accessed (y stored procedures and stored procedures themselves are stored in the data(ase* .urthermore, (ecause a stored procedure/s compiled form is availa(le in the data(ase, no compilation step is re0uired to e-ecute the code* Apart from this, stored procedures ma$e use of shared memory* That means if a stored procedure is called (y user12, then it is (rought into server/s memory* As a result there is a chance of finding the stored procedure in memory, %hen user13 later %ants to use the same procedure* In this case stored procedure need not (e (rought into memory since it is already in the memory* This saves time and increases performance*

Easy

aintenance

If there is any change in the application, only the concerned stored procedures are to (e modified to incorporate the change* As all the clients access stored procedures, they automatically use the modified definition* You only have to change (usiness login once in the stored procedure* Therefore stored procedures improve the integrity and consistency of your applications*

!ecurity
tored procedures help enforcement of data security* You can allo% users to access only the stored procedures and not the ta(le that are manipulated (y stored procedures* Whenever a stored procedure runs, it runs %ith the privileges of the o%ner and not the user running it* 4ecause users only have the privilege to e-ecute the procedure and not the privileges to access the underlying ta(les, it increases security*

"wner rights
When a stored procedure is run under the privileges of the o%ner of the stored procedure, it is called as o%ner rights*

#nvoker rights
When a stored procedure is e-ecuted %ith the privileges of the invo$er and not under the privileges of the o%ner, it is called as invo$er rights*

We %ill discuss a(out the difference (et%een these t%o %ays of running a stored procedure in detailed later in this chapter*

Creating a stored procedures


A stored procedure is created using CR!AT! PROC!56R! command*

CREATE [OR REPLACE] PROCEDURE name [(parameter[,parameter, ...])] {IS |AS} [lo al !e larat"on#] $E%I& e'e (ta)le #tatement# [E*CEPTIO& e' ept"on +an!ler#] E&D [name],

OR REPLACE is used to create a procedure even a procedure %ith the same name is already e-isting* Oracle creates procedure even though the procedure is not valid (ut it displays the message saying that the procedure is created %ith errors* Then you have to rectify the errors and recreate the procedure* If OR R!P#AC! option is not given Oracle doesn/t allo% you to replace an e-isting stored procedure* o, it is (etter you use OR R!P#AC! option so that the e-isting invalid version of the procedure %ill (e replaced %ith the valid version*

!$"W ERR"R!
5uring the creation of the procedure if there are any errors Oracle displays the message saying procedure is created (ut %ith errors %ith the follo%ing message7 -arn"n./ Pro e!(re reate! 0"t+ omp"lat"on error#.

In order to displays errors in the most recent CR!AT! PROC!56R! statement, use 8OW !RROR command* The follo%ing stored procedure inserts a ne% record into PAY9!NT given roll num(er and amount* ta(le %ith the

reate or repla e pro e!(re ne0pa1ment(rollno n(m)er, amt n(m)er) "# )e."n "n#ert "nto pa1ment# 2al(e#(rollno, #1#!ate,amt), omm"t, en!, 3

Once a stored procedure is stored in the data(ase, it can (e invo$ed using !:!C6T! command (y using the name of the procedure*

E%EC&'E command
A procedure can (e e-ecuted using !:!C6T! command* To e-ecute a procedure either you must (e the o%ner of the procedure or you must have !:!C6T! privilege on the procedure* The follo%ing e-ample sho%s ho% to invo$e N!WPAY9!NT procedure* S4L5 e'e (te ne0pa1ment(67,8777), PL3S4L pro e!(re #( e##9(ll1 omplete!.

In the a(ove e-ample, N!WPAY9!NT is invo$ed (y passing 2; and 3;;;* It inserts a ne% ro% into PAY9!NT ta(le %ith values 2;, sysdate, and 3;;;*

Creating a stored function


A stored function is same as a procedure, e-cept that it returns a value* CR!AT! .6NCTION command is used to create a stored function*

CREATE [OR REPLACE] :U&CTIO& name [(parameter[,parameter, ...])] RETURN datatype {IS | AS} [lo al !e larat"on#] $E%I& e'e (ta)le #tatement# [E*CEPTIO& RETURN value;

e' ept"on +an!ler#] E&D [name],


OR REPLACE is used to create a function even though a function %ith the same name already e-ists RETURN datatype specifies the type of data to (e returned (y the function* RETURN statement in the e-ecuta(le part returns the value* The value must (e of the same type as the return type specified using R!T6RN option in the header* The follo%ing stored function ta$es roll num(er of the student and return the amount yet to (e paid (y the student* reate or repla e 9(n t"on ret(rn n(m)er .et!(eamt(prollno n(m)er)

"# 2;9ee n(m)er(<), 2;amtpa"! n(m)er(<), )e."n == .et total amo(nt pa"! )1 #t(!ent #ele t #(m(amo(nt) "nto 2;amtpa"! 9rom pa1ment# 0+ere rollno > prollno, == .et o(r#e 9ee o9 t+e o(r#e "nto 0+" + #t(!ent ?o"ne! #ele t 9ee "nto 2;9ee 9rom o(r#e# 0+ere o!e > ( #ele t o!e 9rom )at +e# 0+ere ) o!e "n ( #ele t ) o!e 9rom #t(!ent# 0+ere rollno > prollno) ), == ret(rn t+e !"99eren e ret(rn 2;9ee = 2;amtpa"!, en!, 3 The a(ove function can (e called from a P#& '# (loc$ as follo%s7 )e."n !)m#;o(tp(t.p(t;l"ne(.et!(eamt(67)), en!, 6ser1defined P#& '# functions can (e used in '# in the same manner as the standard functions such as RO6N5 and 64 TR** .or e-ample, the function <!T56!A9T can (e invo$ed from follo%s7 S4L5 #ele t rollno, getdueamt(rollno) 8 9rom #t(!ent#, ROLL&O %ETDUEA@T(ROLL&O) ========= ================= 6 7 8 7 A 7 B 7 < 7 C 7 D 7 E 7 F 6<77 67 8777 66 7 68 6<77 6A 7 !#!CT command as

(etting source code


It is possi(le to see the source code of stored procedures and function (y using 6 !R" O6RC! data dictionary vie%* The follo%ing procedure* !#!CT command %ill display the source code of N!WPAY9!NT stored

S4L5 #ele t te't 8 9rom (#er;#o(r e A 0+ere name > G&E-PAH@E&TG, TE*T ======================================================================== pro e!(re ne0pa1ment(rollno n(m)er, amt n(m)er) "# )e."n "n#ert "nto pa1ment# 2al(e#(rollno, #1#!ate,amt), omm"t, en!,

Privi)eges re*uired
To create a stored procedure, you must have CR!AT! PROC!56R! system privilege* You must also have re0uired o(+ect privileges on the o(+ects that are referred in the procedure in order to successfully compile the procedure* Note: The owner of the procedure CANNOT obtain required privileges on the stored procedure through ROLES.

Recompi)ing
tored procedures and functions are compiled at the time of creation and stored in the compiled form* If a procedure (ecomes invalid after%ards, it is to (e recompiled (efore it is e-ecuted* Oracle implicitly compiles the procedure %hen an invalid procedure is referred* 8o%ever, it is possi(le to e-plicitly recompile In order to recompile a stored procedure use A#T!R PROC!56R! and A#T!R .6NCTION to recompile a procedure and function respectively*

ALTER PROCEDURE pro e!(rename ALTER :U&CTIO& 9(n t"onname

CO@PILE, CO@PILE,

The follo%ing se0uence %ill illustrate the importance of recompilation*

Assume user

COTT has created N!WPAY9!NT procedure as follo%s

reate or repla e pro e!(re ne0pa1ment(rollno n(m)er, amt n(m)er) "# )e."n "n#ert "nto )ooI.pa1ment# 2al(e#(rollno, #1#!ate,amt), omm"t, en!, 3

ince

COTT doesn/t have IN !RT privilege on PAY9!NT

ta(le of 4OO=, the

procedure is created (ut mar$ed as invalid* You can see the status of the procedure using the follo%ing command* #ele t #tat(# 9rom (#er;o)?e t# 0+ere o)?e t;name > G&E-PAH@E&TG, STATUS ======= I&JALID

No%, user 4OO= has granted IN !RT privilege on PAY9!NT

ta(le to

COTT

as follo%s7 %RA&T I&SERT O& PAH@E&TS to SCOTT,

Then any su(se0uent reference to N!APAY9!NT procedure in

COTT %ill

implicitly recompile the procedure* 4ut in order to avoid e-tra time ta$en to recompile the procedure at runtime, it can (e recompiled using A#T!R PROC!56R! command as follo%s7

ALTER PROCEDURE ne0pa1ment CO@PILE, After recompilation, the procedure %ill have status >A#I5 as provide (y the

follo%ing 0uery* #ele t #tat(# 9rom (#er;o)?e t# 0+ere o)?e t;name > G&E-PAH@E&TG, STATUS ======= JALID

'ypes of Parameters
Parameters of a procedure are of t%o types*

.ormal parameters

Actual Parameters

+orma) Parameters
The parameters declared in the definition of procedure are called as formal parameters* They receive the values sent %hile calling the procedure* pro e!(re "n rea#e;9ee (p o!e 2ar +ar8, pamt n(m)er)

In the a(ove procedure, PCCO5!, PA9T parameters are called as formal parameters*

Actua) Parameters
The values given %ithin parentheses %hile calling the procedure are called as actual parameters. "n rea#e;9eepa"! ( 2; o!e, 8777),

v"ccode and 3;;; are actual parameters* These values are copied to the corresponding formal parameters 1 pccode and p a t*

Parameter

odes

Parameter mode is used to specify %hat can (e done %ith formal parameter* The follo%ing are the availa(le modes*

IN O6T IN O6T

#, mode
IN parameters lets you pass a value to the su(program (eing called* The value cannot (e changed inside the su(program* It is li$e a constant in the su(program* Therefore it cannot (e assigned a value* pro e!(re "n rea#e;9ee (p )e."n . . . en!, o!e "n 2ar +ar8, pamt n(m)er) "#

The actual parameter corresponding to IN parameter can (e a varia(le, constant, or e-pression* The default parameter mode is IN* In the a(ove e-ample though %e didn/t specify the parameter mode for PA9T is it ta$en as IN parameter*

"&'

ode
8

An O6T parameter lets the su(program pass a value to caller* Inside the su(program O6T parameter is an uninitiali?ed varia(le* u(program has to place a value in the O6T parameters, %hich %ill (e used (y caller program* Whatever changes are made to formal parameter, the changes %ill (e made availa(le to actual parameter* The actual parameter corresponding to O6T parameter must (e a varia(le*

#, "&'

ode

It is same as IN and O6T modes put together* It can get a value from the calling program and return value to calling program* The value of this type of parameter can (e used in the su(program and The actual parameter corresponding to IN O6T parameter must (e a varia(le* The follo%ing procedure ta$es course code and returns the dates on %hich the first and last (atches of that course have started* reate or repla e pro e!(re .et;!ate#( p o!e "n 2ar +ar8, 9"r#t;!ate o(t !ate, la#t;!ate o(t !ate) "# )e."n #ele t m"n(#t!ate) "nto 9rom )at +e# 0+ere o!e > p o!e, #ele t ma'(#t!ate) "nto 9rom )at +e# 0+ere o!e > p o!e, en!, Once the procedure is created, it can (e called as follo%s7 !e lare m"n;!ate !ate, ma';!ate !ate, )e."n .et;!ate#( KoraL, m"n;!ate, ma';!ate), !)m#;o(tp(t.p(t;l"ne( m"n;!ate || K/L || ma';!ate), en!, The output of the a(ove program %ill (e7 12-JAN-01:15-AUG-01 9"r#t;!ate

la#t;!ate

,"C"P- Compi)er $int


4y default, OUT and I& OUT parameters are passed (y value* That means, the value of an I& OUT actual parameter is copied into the corresponding formal parameter* Then, if the procedure e-its normally, the values assigned to OUT and I& OUT formal parameters are copied into the corresponding actual parameters* When the parameters hold large data structures such as records, and instances of o(+ect types @%hich %e %ill in later chaptersA, copying slo%s do%n e-ecution and uses up more memory* To prevent that, you can specify the &OCOPH hint, %hich allo%s the P#& '# to pass OUT and I& OUT parameters (y reference* PROCEDURE +an.e(p#t(!ent I& OUT &OCOPH #t(!ent;t1pe) IS ... T65!NT"TYP!* It is

In the a(ove e-ample parameter P T65!NT is of o(+ect type ) no% passed (y reference as %e used NOCOPY option %ith it*

#nvoker Rights vs. definer rights


4y default, %hen a user e-ecutes a procedure, the procedure is e-ecuted %ith the privileges of the o%ner* That means, the privileges of invo$ing user @invo$erA are not ta$en into account only the privileges of definer @o%nerA of the procedure %ill (e considered* If the procedure is to (e called (y user other than the o%ner then the use must (e granted !:!C6T! privilege on the procedure* When the procedure is e-ecuted using the privileges of definer then, it is called as definer rights* 5efiner rights is the default option* All o(+ect references in the procedure %ill (e referring to o(+ects of definer and not invo$er* #et us see an e-ample to understand this point further* Assume %e have procedure A559! A<! created (y user RI=ANT8 as follo%s7

reate or repla e pro e!(re a!!me##a.e(m#. 2ar +ar8) "# )e."n "n#ert "nto me##a.e# 2al(e# (m#., #1#!ate), omm"t, en!, Then user RI=ANT8 has granted !:!C6T! privilege to user PRAN!!T8 as follo%s7

.rant e'e (te on a!!me##a.e to praneet+,

10

No% user PRAN!!T8 can e-ecute the procedure as follo%s7 e'e (te Sr"Iant+.a!!me##a.e(G:"r#t me##a.eG), A<! ta(le of RI=ANT8 ) the

The message B.irst messageC is inserted into 9! definer of the procedure*

What if user PRAN!!T8 also has 9! A<! ta(le %ith the same structure as 9! A<! ta(le of RI=ANT8? The ans%er isD even no% the message goes to 9! A<! ta(le of RI=ANT8, since all references to o(+ects in the procedure are resolved to definer of the procedure*

#nvoke Rights
OracleEi has introduced invo$er rights* In case of invo$er rights, procedure is e-ecuted %ith the privileges of invo$er and not the definer of the procedure* If you %ant the procedure to (e e-ecuted %ith invo$er rights and not %ith definer right, then the procedure is to (e created %ith A6T8I5 C6RR!NT"6 !R option as follo%s* reate or repla e pro e!(re a!!me##a.e(m#. 2ar +ar8) a(t+"! (rrent;(#er a# "# )e."n "n#ert "nto me##a.e# 2al(e# (m#., #1#!ate), omm"t, en!, A6T8I5 C6RR!NT"6 !R option specifies that the procedure to (e e-ecuted under the privileges of invo$ing user* Also remem(er that all o(+ect references are resolved to invo$er and not the definer* 8o%ever, if any o(+ect is 0ualified %ith schema @usernameA then it %ill refer to o(+ect in that schema* In other %ords, all un0ualified o(+ect are ta$en from invo$er/s schema* No% if you e-ecute A559! A<! procedure from user PRAN!!T8, it %ill fail, as there is no 9! A<! ta(le in that schema* S4L5 e'e (te #r"Iant+.a!!me##a.e(GSe on! me##a.eG), $E%I& #r"Iant+.a!!me##a.e(G9"neG), E&D, M ERROR at l"ne 6/ ORA=77FB8/ ta)le or 2"e0 !oe# not e'"#t ORA=7C<68/ at NSRIOA&TP.ADD@ESSA%EN, l"ne B ORA=7C<68/ at l"ne 6 As you can understand, the a(ove message is complaining a(out missing 9! A<! ta(le* If you create 9! A<! ta(le in PRAN!!T8 schema, then the procedure %ill succeed and the message is inserted into 9! A<! ta(le of PRAN!!T8 account*

11

The advantage of invo$er rights is that it allo%s you to centrali?ed code %hereas the data is stored in individual schema* That means though users use the same common code the data is stored in o(+ects of their schema*

RA#!E/APP0#CA'#",/ERR"R Procedure
This procedure is used to create your o%n application error num(ers and messages* When you have to terminate a P#& '# program, you can display an error message and send error code to host environment using this procedure*

RAISE;APPLICATIO&;ERROR (errorn(m)er,

errorme##a.e),

errornumber errormessage

is a num(er in the range 13;;;2 and 13;FFF* is the message to (e displayed*

The follo%ing P#& '# (loc$ displays the error message along %ith error num(er @1 3;2;;A %hen NO"5ATA".O6N5 e-ception is raised* !e lare 2;9ee )e."n

o(r#e#.9eeQt1pe,

#ele t 9ee "nto 2;9ee 9rom o(r#e# 0+ere o!e > KoraL, == rema"n"n. #tatement# e' ept"on 0+en no;!ata;9o(n! t+en ra"#e;appl" at"on;error(=87677,KIn2al"! en!,

o(r#e

o!eL),

Packages
A pac$age is a collection of related procedures, functions, varia(les and data types* A pac$age typically contains t%o parts ) specification and (ody*

!pecification
Pac$age specification contains declarations for items, procedure and functions that are to (e made pu(lic* All pu(lic o(+ects of pac$age are visi(le outside the pac$age* In other %ords, pu(lic o(+ects are calla(le from outside of the pac$age* Private items of the pac$age can (e used only in the pac$age and not outside the pac$age*

12

The follo%ing is the synta- to create pac$age specification*

CREATE PACOA%E pa Ia.e;name AS 3M !e lare E&D, p()l" o)?e t# o9 pa Ia.e M3

Body
4ody of the pac$age defines all the o(+ects of the pac$age* It includes pu(lic o(+ects that are declared in pac$age specification and o(+ects that are to (e used only %ithin the pac$age ) private mem(ers*

CREATE PACOA%E $ODH pa Ia.e;name AS 3M !e9"ne o)?e t# o9 pa Ia.e M3 E&D,

procedures declared in the pac$age specification functions declared in the pac$age specification definition of cursors declared in the pac$age specification local procedures and functions, not declared in the pac$age specification local varia(les

Ca))ing a procedure of package


In order to access a pu(lic o(+ect of a pac$age use the follo%ing synta-7

pa Ia.e;name.o)?e t;name
pac$age"name is the name of the pac$age %hose o(+ect you %ant to access* ob!ect"na e is the name of a pu(lic o(+ect in the pac$age* #et us no% create a pac$age called CO6R !"P=< that contains t%o su(programs ) C8AN<!.!! and <!T4ATC8CO6R !* We have to first create pac$age specification and then (ody a follo%s7 reate or repla e pa Ia.e o(r#e;pI. a#

pro e!(re +an.e9ee (p o!e 2ar +ar8, ne09ee n(m)er), 9(n t"on .et)at + o(r#e(p) o!e 2ar +ar8) ret(rn 2ar +ar8,

13

en!, 3 The follo%ing CR!AT! PAC=A<! 4O5Y statement creates the (ody of the pac$age* reate or repla e pa Ia.e )o!1 o(r#e;pI. a#

pro e!(re +an.e9ee (p o!e 2ar +ar8, ne09ee n(m)er) "# )e."n (p!ate o(r#e# #et 9ee > ne09ee 0+ere o!e > p o!e, "9 #RlQ9o(n! t+en omm"t, el#e ra"#e;appl" at"on;error(=87767,GIn2al"! en! "9, en!,

o(r#e

o!eG),

9(n t"on .et)at + o(r#e(p) o!e 2ar +ar8) ret(rn 2ar +ar8 "# 2; o!e o(r#e#. o!eQt1pe, )e."n #ele t o!e "nto 2; o!e 9rom )at +e# 0+ere ) o!e > p) o!e, ret(rn 2; o!e,

e' ept"on 0+en no;!ata;9o(n! t+en ra"#e;appl" at"on;error( =87766,GIn2al"! )at + en!, en!, 3

o!eG),

In order to call procedure C8AN<!.!! of the pac$age, use the pac$age name follo%ed (y procedure name as follo%s7 E'e (te o(r#e;pI.. +an.e9ee(KoraL,<777),

#nitia)i1ing package
It is possi(le to e-ecute some code %hen a user refers the pac$age for the first time* Any code that you feel is to (e e-ecuted at the time of a user referring to the pac$age for the first time can (e put in initiali?ation part of the pac$age* The follo%ing is the structure of initiali?ation part* reate pa Ia.e )o!1 name a#

14

3M !e9"n"t"on o9 pa Ia.e )o!1 M3 begin /* code to be executed when pac age i! re"erred "or the "ir!t time */ end;

!ummary
tored procedure and functions are su( programs stored in data(ase* .unctions return a single value %hereas procedure doesn/t return any value* tored procedures have important advantages such as improving performance, ma$ing maintenance and security implementation easy* Oracle allo%s parameters of three types ) in, out, and in out* O6T and IN O6T parameters are used to return values (ac$ to calling program* They can (e passed (y either value @defaultA or (y reference using NOCOPY hint* Procedures are e-ecuted under privileges of o%ner of the procedure* 8o%ever, it is possi(le to e-ecute procedure %ith the privileges of invo$er using A6T8I5 C6RR!NT"6 !R option of CR!AT! PROC!56R! command* tandard procedure RAI !"APP#ICATION"!RROR is used to raise an application error %ith the given error num(er and message* Pac$age allo%s a group of related procedures and function to (e identified (y a single name* It is used to avoid name conflicts (et%een names of different procedures*

E2ercises
2* 3* G* H* I* J* """"" command is used to display errors that occurred during compilation of a stored procedure* """"""" vie% provides information a(out stored procedures* """""""option is used to specify that a parameter is (oth input and output parameter* What is the command used to compile a procedure e-plicitly? Create a procedure to insert a ne% ro% into payments %ith the given roll num(er* 5P is system date and A9O6NT is the amount to (e paid (y the student* Create a function to ta$e (atch code and return the num(er of students in the (atch*

15

K* E* F*

Create a function to return the first missing roll num(er* If no roll num(er is missing then return the highest roll num(er L 2* Create a function to ta$e faculty code and return the num(er of (atches the faculty can handle* Create a procedure to ta$e course code and return minimum and ma-imum duration of (atches of that course*

2;* Create a pac$age to contain the follo%ing procedures and functions* .unction 4ATC8 TAT6 ) ta$es (atch code and returns 1 if (atch is yet to start, C ) if (atch is completed, R ) if (atch is currently running* .unction 4ATC8A9O6NT ) return the total amount collected from the given (atch code*

16

You might also like