You are on page 1of 17

PL/SQL PL/SQL stands for Procedural Language/SQL.PL/SQL extends SQL by adding control Structures found in other procedural language.

PL/SQL combines the flexibility of SQL with Powerful feature of 3 rd generation Language. The procedural construct and database access Are present in PL/SQL.PL/SQL can be used in both in database in racle Ser!er and in "lient side application de!elopment tools. Advantages of PL/SQL Support for SQL# support for ob$ect%oriented programming## better performance# portability# higher producti!ity# &ntegration with racle a' Supports the declaration and manipulation of ob$ect types and collections. b' Allows the calling of external functions and procedures. c' "ontains new libraries of built in pac(ages. d' with PL/SQL # an multiple s)l statements can be processed in a single command line statement. PL/SQL Datatypes Scalar Types *&+A,-.&+T/0/, #1/"#1/"&2AL#1 3*L/ ##P,/"&S& +#4L AT#&+T#&+T/0/,#+AT3,AL# +AT3,AL+#+32*/,# +32/,&"# PLS.&+T/0/,#P S&T&5/#P S&T&5/+#,/AL#S&0+T-P/# S2ALL&+T#"6A,#"6A,A"T/,#L +0#L +0 ,A7#+"6A,#+5A,"6A,8#,A7#, 7&1#ST,&+0# 5A,"6A,#5A,"6A,8# "omposite Types TA*L/# 5A,,A-# ,/" ,1 L * Types *4&L/# *L *# "L *# +"L * ,eference Types ,/4 "3,S , * L/A+# 1AT/

1*2S. 3TP3T.P3T.L&+/9 &t is a pre%defined pac(age that prints the message inside the parenthesis ANONYMOUS PL/SQL BLOCK. The text of an Oracle Forms trigger is an anonymous PL/SQL block. It consists of three sections: !eclaration of "ariables# constants# cursors an! exce$tions %hich is o$tional. section of executable statements. section of exce$tion han!lers# %hich is o$tional. ATTRIBUTES Allow us to refer to data types and ob$ects from the database.PL/SQL !ariables and "onstants can ha!e attributes. The main ad!antage of using Attributes is e!en if you "hange the data definition# you don:t need to change in the application. %TYPE &t is used when declaring !ariables that refer to the database columns. 3sing ;T-P/ to declare !ariable has two ad!antages. 4irst# you need not (now the exact datatype of !ariable. Second# if the database definition of !ariable changes# the datatype of !ariable changes accordingly at run time. 1

%ROWTYPE The ;, 7T-P/ attribute pro!ides a record type that represents a row in a table <or !iew=. The record can store an entire row of data selected from the table or fetched from a cursor or strongly typed cursor !ariable. EXCEPTION An /xception is raised when an error occurs. &n case of an error then normal execution stops and the control is immediately transferred to the exception handling part of the PL/SQL *loc(. /xceptions are designed for runtime handling# rather than compile time handling. /xceptions impro!e readability by letting you isolate error%handling routines. 7hen an error occurs# an exception is raised. That is# normal execution stops and control transfers to the exception%handling part of your PL/SQL bloc( or subprogram. &nternal exceptions are raised implicitly <automatically= by the runtime system. 3ser%defined exceptions must be raised explicitly by ,A&S/ statements# which can also raise predefined exceptions. To handle raised exceptions# you write separate routines called exception handlers. After an exception handler runs# the current bloc( stops executing and the enclosing bloc( resumes with the next statement. &f there is no enclosing bloc(# control returns to the host en!ironment. Ex ept!on Types 1. Predefined Exceptions An internal exception is raised implicitly whene!er your PL/SQL program !iolates an racle rule or exceeds a system%dependent limit. /!ery racle error has a number# but exceptions must be handled by name. So# PL/SQL predefines some common racle errors as exceptions. 4or example# PL/SQL raises the predefined exception + .1ATA.4 3+1 if a S/L/"T &+T statement returns no rows. 2. User Defined exceptions 3ser > defined exception must be defined and explicitly raised by the user EXCEPTION_INIT A named exception can be associated with a particular oracle error. This can be used to trap the error specifically. PRA"#A EXCEPTION$INIT<exception name# racle.error.number=?

The pragma /@"/PT& +.&+&T associates an exception name with an racle# error number. That allows you to refer to any internal exception by name and to write a specific handler RAISE_APP ICATION_ERROR The procedure raise.application.error lets you issue user%defined error messages from stored subprograms. That way# you can report errors to your application and a!oid returning unhandled exceptions. To call raise.application.error# you use the syntax raise.application.error<error.number# messageA# BT,3/ C 4ALS/D'=? where error.number is a negati!e integer in the range %8EEEE .. %8EFFF and message is a character string up to 8EGH bytes long.

Usin! S" CODE #nd S" ERR$ 4or internal exceptions# SQL" 1/ returns the number of the racle error. The number that SQL" 1/ returns is negati!e unless the racle error is no data found# in which case SQL" 1/ returns IJEE. SQL/,,2 returns the corresponding error message. The message begins with the racle error code. Un%#nd&ed Exceptions PL/SQL returns an unhandled exception error to the host en!ironment# which determines the outcome. '%en Ot%ers &t is used when all exception are to be trapped. CURSORS racle allocates an area of memory (nown as context area for the processing of SQL statements. The pointer that points to the context area is a cursor. #e%!ts J' Allowing to position at specific rows of the result set. 8' ,eturning one row or bloc( of rows from the current position in the result set. 3' Supporting data modification to the rows at the current position in the result set. TYPES &' STATIC CURSOR SQL statement is determined at design time. A( EXP ICIT CURSOR 2ultiple row S/L/"T statement is called as an explicit cursor. To execute a multi%row )uery# racle opens an unnamed wor( area that stores processing information. To access the information# you can use an explicit cursor# which names the wor( area. 3sage % &f the S/L/"T statement returns more that one row then explicit cursor should be used. Steps 1eclare a cursor pen a cursor 4etch data from the cursor "lose the cursor

/@PL&"&T "3,S , ATT,&*3T/S ;4 3+1 <,eturns true if the cursor has a !alue= ;+ T4 3+1 <,eturns true if the cursor does not contain any !alue= ;, 7" 3+T <,eturns the number of rows selected by the cursor= ;&S P/+ <,eturns the cursor is opened or not= CURSOR )OR OOP The "3,S , 4 , L P lets you implicitly P/+ a cursor# 4/T"6 each row returned by the )uery associated with the cursor and "L S/ the cursor when all rows ha!e been processed. S-+TA@ 4 , K,/" ,1 +A2/L &+ K"3,S , +A2/L L P STAT/2/+TS /+1 L P? To refer an element of the record use Krecord name. Column nameL 4

P#r#*eteri+ed C,rsor A cursor can ta(e parameters# which can appear in the associated )uery where!er constants can appear. The formal parameters of a cursor must be &+ parameters. Therefore# they cannot return !alues to actual parameters. Also# you cannot impose the constraint + T +3LL on a cursor parameter. The !alues of cursor parameters are used by the associated )uery when the cursor is opened. - .I$P ICIT CURSOR An &2PL&"&T cursor is associated with any SQL 12L statement that does not ha!e a explicit cursor associated with it. This includes: All All All All &+S/,T statements 3P1AT/ statements 1/L/T/ statements S/L/"T .. &+T statements

&2PL&"&T "3,S M SQL;4 M SQL;+ M SQL;,

, ATT,&*3T/S 3+1 <,eturns true if the 12L operation is !alid= T4 3+1 <,eturns true if the 12L operation is in!alid= 7" 3+T <,eturns the no. of rows affected by the 12L operation=

(' D)NA#IC CURSOR 1ynamic "ursor can be used along with 1*2S.SQL pac(age .A SQL statement is dynamic# if it is constructed at run time and then executed. *' RE+ CURSOR 1eclaring a cursor !ariable creates a pointer# not an item. &n PL/SQL# a pointer has datatype ,/4 @# where ,/4 is short for ,/4/,/+"/ and @ stands for a class of ob$ects. Therefore# a cursor !ariable has datatype ,/4 "3,S ,. To execute a multi%row )uery# racle opens an unnamed wor( area that stores processing information. To access the information# you can use an explicit cursor# which names the wor( area. r# you can use a cursor !ariable# which points to the wor( area. 2ainly# you use cursor !ariables to pass )uery result sets between PL/SQL stored subprograms and !arious clients. +either PL/SQL nor any of its clients owns a result set? they simply share a pointer to the )uery wor( area in which the result set is stored. 4or example# an "& client# racle 4orms application# and racle Ser!er can all refer to the same wor( area. a' Stron! C,rsor % 7hose return type specified. b' 'ee. C,rsor % 7hose return type not specified. Dref &t is the Ndeference operator.Li(e 5AL3/#it return the !alue of an ob$ect#3nli(e !alue. 1refNs input is a ,/4 to an column in a table and you want reteri!e the target instead of the pointer#you 1,/4.

ORACLE ,I Advan ed Exp-! !t C.%so% Con epts 1. )OR UPDATE 'AIT C&#,se Loc( the rows before the update or delete. 3se explicit loc(ing to deny access for the duration of a transaction.

Syntax "ursor eipcJ is select O from emp for update A of column.reference ' A + 7A&T ' "olumn ,eference + 7A&T &t is column in the table against which the )uery is performed A A list of column may also be used ' ,eturns an racle /rror if the rows are loc(ed by another session.

P The S/L/"T... 4 , 3P1AT/ statement has been modified to allow the user to specify how long the command should wait if the rows being selected are loc(ed. P &f + 7A&T is specified# then an error is returned immediately if the loc( cannot be obtained. Exa/p-e of Us!ng +OR UPDATE 0AIT C-a.se J. S/L/"T O 4, 2 /2PL -//S 76/,/ 1/PA,T2/+T.&1 Q JE 4 , 3P1AT/ 7A&T 8E? 8. 1/"LA,/ "3,S , /2P."3,S , &S S/L/"T /2P+ # /+A2/# 1+A2/ 4, 2 /2P#1/PT 76/,/ /2P.1/PT+ Q1/PT.1/PT+ A+1 /2P.1/PT+ + QHE 4 , 3P1AT/ 4 SALA,- + 7A&T?

A Retrieve the Employees who work in department 80 and update their Salary ] 2. T%e '/ERE CURRENT O) C&#,se 3se cursors to update or delete the cursor row. &nclude the 4 , 3P1AT/ clause in the cursor )uery to loc( the row first. 3se the 76/,/ "3,,/+T 4 clause to refer the current row from an explicit cursor.

Syntax 76/,/ "3,,/+T 4 K cursor.name L "ursor.+ame %&t is the name of a declared cursor. A The cursor ha!e been declared with the 4 , 3P1AT/ clause' Exa/p-e of Us!ng +OR 01ERE CURRENT O+ C-a.se J. 1/"LA,/ "3,S , /2P."3,S , &S S/L/"T /2P+ # /+A2/# 1+A2/ 4, 2 /./2P#1.1/PT 76/,/ /2P.1/PT+ Q1/PT.1/PT+ A+1 /2P.1/PT+ + QHE 4 , 3P1AT/ 4 SALA,- + 7A&T? */0&+ 4 , & &+ /2P."3,S ,? L P &4 &.SALKREEE T6/+ 3P1AT/ /2P S/T SALA,-Q&.SALOJ.JE 76/,/ "3,,/+T /+1 L /+1? 6 /+1 &4? P? 4 /2P."3,S ,?

AThe E ample loops throu!h ea"h employee in department 80 # and "he"ks whether the salary is less than $000%&' salary is less than # the salary is raised (y )0%% The where "urrent o' "lause in the *P+,TE statement re'ers to the "urrently 'et"hed re"ords% ] 0. CURSORS 'IT/ SU- "UERIES Sub )ueries are often used in the 76/,/ clause of select statement. &t can be used to 4, 2 clause# creating a temporary data source for the )uery. DECLARE bonus REAL; BEGIN FOR emp_rec IN (SELECT empno, sal, comm FRO emp! LOO" bonus #$ (emp_rec%sal & '%'(! ) (emp_rec%comm & '%*(!; INSERT INTO bonuses +AL,ES (emp_rec%empno, bonus!; END LOO"; CO IT;

END;

PROCEDURES Procedure is a subprogram that contains set of SQL and PL/SQL statements. $erits ,eusability % Subprograms once executed can be used in any number of applications 2aintainability % Subprogram can simplify maintenance# subprogram will be affected only its definition changes P#r#*eter &+ % 3T % &+ 3T The &+ parameter is used to pass !alues to a subprogram when it is in!o(ed The 3T parameter is used to return !alues to the caller of a subprogram The &+ 3T parameter is used to pass initial !alues to the subprogram when in!o(ed and also it returns updated !alues to the caller.

Usin! t%e NOCOP1 Co*pi&er /int Suppose a subprogram declares an &+ parameter# an 3T parameter# and an &+ 3T parameter. 7hen you call the subprogram# the &+ parameter is passed by reference. That is# a pointer to the &+ actual parameter is passed to the corresponding formal parameter. So# both parameters reference the same memory location# which holds the !alue of the actual parameter. *y default# the 3T and &+ 3T parameters are passed by !alue. That is# the !alue of the &+ 3T actual parameter is copied into the corresponding formal parameter. Then# if the subprogram exits normally# the !alues assigned to the 3T and &+ 3T formal parameters are copied into the corresponding actual parameters. 7hen the parameters hold large data structures such as collections# records# and instances of ob$ect types# all this copying slows down execution and uses up memory. To pre!ent that# you can specify the + " P- hint# which allows the PL/SQL compiler to pass 3T and &+ 3T parameters by reference. &n the following example# you as( the compiler to pass &+ 3T parameter my.staff by reference instead of by !alue9 DECLARE T-"E S.a// IS +ARRA-(*''! OF Emplo0ee; "ROCED,RE reor1an23e (m0_s.a// IN O,T NOCO"- S.a//! IS %%% ,emember# + " P- is a hint# not a directi!e. So# the compiler might pass my.staff by !alue despite your re)uest. 3sually# howe!er# + " P- succeeds. So# it can benefit any PL/SQL application that passes around large data structures. &n the example below# 8REEE records are loaded into a local nested table# which is passed to two local procedures that do nothing but execute +3LL statements. 6owe!er# a call to one procedure ta(es 8J seconds because of all the copying. 7ith + " P-# a call to the other procedure ta(es much less than J second. S4L5 SET SER+ERO,T",T ON S4L5 GET .es.%s6l 7 DECLARE * T-"E EmpTabT0p IS TABLE OF emp8RO9T-"E; : emp_.ab EmpTabT0p #$ EmpTabT0p(N,LL!; ;; 2n2.2al23e < .7 N, BER((!; ( .* N, BER((!; = .: N, BER((!; > "ROCED,RE 1e._.2me (. O,T N, BER! IS ? BEGIN SELECT TO_C@AR(S-SDATE,ASSSSSA! INTO . FRO Bual; END; C "ROCED,RE Bo_no.D2n17 (.ab IN O,T EmpTabT0p! IS 7' BEGIN N,LL; END; 77 "ROCED,RE Bo_no.D2n1* (.ab IN O,T NOCO"- EmpTabT0p! IS 8

7*

N,LL; END; 7: BEGIN 7< SELECT & INTO emp_.ab(7! FRO emp 9@ERE empno $ >>??; 7( emp_.ab%EETEND(*<CCC, 7!; ;; cop0 elemen. 7 2n.o *%%*(''' 7= 1e._.2me(.7!; 7> Bo_no.D2n17(emp_.ab!; ;; pass IN O,T parame.er 7? 1e._.2me(.*!; 7C Bo_no.D2n1*(emp_.ab!; ;; pass IN O,T NOCO"- parame.er *' 1e._.2me(.:!; *7 DB S_O,T",T%",T_LINE(ACall Dura.2on (secs!A!; ** DB S_O,T",T%",T_LINE(A;;;;;;;;;;;;;;;;;;;;A!; *: DB S_O,T",T%",T_LINE(AFus. IN O,T# A GG TO_C@AR(.* ; .7!!; *< DB S_O,T",T%",T_LINE(A92.D NOCO"-# A GG TO_C@AR(.: ; .*!!; *(& END; S4L5 H Call Dura.2on (secs! ;;;;;;;;;;;;;;;;;;;; Fus. IN O,T# *7 92.D NOCO"-# ' A,tono*o,s Tr#ns#ctions A transaction is a series of SQL statements that does a logical unit of wor(. ften# one transaction starts another. &n some applications# a transaction must operate outside the scope of the transaction that started it. This can happen# for example# when a transaction calls out to a data cartridge. An autonomous transa"tion is an independent transaction started by another transaction# the main transa"tion. Autonomous transactions let you suspend the main transaction# do SQL operations# commit or roll bac( those operations# then resume the main transaction. Advantages of Autonomous Transactions nce started# an autonomous transaction is fully independent. &t shares no loc(s# resources# or commit%dependencies with the main transaction. So# you can log e!ents# increment retry counters# and so on# e!en if the main transaction rolls bac(. 2ore important# autonomous transactions help you build modular# reusable software components. 4or example# stored procedures can start and finish autonomous transactions on their own. A calling application need not (now about a procedure:s autonomous operations# and the procedure need not (now about the application:s transaction context. That ma(es autonomous transactions less /rror%prone than regular transactions and easier to use. 4urthermore# autonomous transactions ha!e all the functionality of regular transactions. They allow parallel )ueries# distributed processing# and all the transaction control statements including S/T T,A+SA"T& +. VIEW SOURCE CODE FOR PROCEDURES SELECT TEET FRO ,SER_SO,RCE 9@ERE NA E$IJ"7I AND T-"E$A"ROCED,REA

BEGIN

+UNCTIONS 9

4unction is a subprogram that computes and returns a single !alue. A function is a subprogram that computes a !alue. 4unctions and procedures are structured ali(e# except that functions ha!e a ,/T3,+ clause. F,NCTION NA E K("ARA ETERK, "ARA ETER, %%%L!L RET,RN DATAT-"E IS KLOCAL DECLARATIONSL BEGIN EEEC,TABLE STATE ENTS KEECE"TION EECE"TION @ANDLERSL A function has two parts9 the specification and the body. The function specification begins with the (eyword 43+"T& + and ends with the ,/T3,+ clause# which specifies the datatype of the result !alue. Parameter declarations are optional. 4unctions that ta(e no parameters are written without parentheses. The function body begins with the (eyword &S and ends with the (eyword /+1 followed by an optional function name. Usin! t%e RETURN St#te*ent The ,/T3,+ statement immediately completes the execution of a subprogram and returns control to the caller. /xecution then resumes with the statement following the subprogram call. <1o not confuse the ,/T3,+ statement with the ,/T3,+ clause in a function spec# which specifies the datatype of the return !alue.= A subprogram can contain se!eral ,/T3,+ statements# none of which need be the last lexical statement. /xecuting any of them completes the subprogram immediately. 6owe!er# to ha!e multiple exit points in a subprogram is a poor programming practice. &n procedures# a ,/T3,+ statement cannot contain an expression. The statement simply returns control to the caller before the normal end of the procedure is reached. 6owe!er# in functions# a ,/T3,+ statement must contain an expression# which is e!aluated when the ,/T3,+ statement is executed. The resulting !alue is assigned to the function identifier# which acts li(e a !ariable of the type specified in the ,/T3,+ clause. bser!e how the function balance returns the balance of a specified ban( account9 CO$PARIN2 PROCEDURES AND )UNCTIONS Procedure /xecute as a PL/SQL statement +o ,/T3,+ datatype "an return none# one or many !alues "an not use in SQL Statement -enefits of Stored Proced,res #nd ),nctions In a!!ition to mo!ulari&ing a$$lication !e"elo$ment# store! $roce!ures an! functions ha"e the follo%ing benefits: !"#ro$ed #er%or"&nce "oi! re$arsing for multi$le users by ex$loiting the share! SQL area "oi! PL/SQL $arsing at run'time by $arsing at com$ile time (e!uce the number of calls to the !atabase an! !ecrease net%ork traffic by bun!ling comman!s !"#ro$ed "&inten&nce. )o!ify routines online %ithout interfering %ith other users )o!ify one routine to affect multi$le a$$lications )o!ify one routine to eliminate !u$licate testing !"#ro$ed d&t& securit' &nd inte(rit' 10 Function &n!o(e as part of an expression 2ust contain a ,/T3,+ datatype 2ust return a single !alue "an 3se in SQL Statements

*ontrol in!irect access to !atabase ob+ects from non $ri"ilege! users %ith security $ri"ileges ,nsure that relate! actions are $erforme! together# or not at all# by funneling acti"ity for relate! tables through a single $ath

L!ST ALL P)OC*+U)*S AN+ FUNCT!ONS

SELECT OBFECT_NA E, OBFECT_T-"E FRO ,SER_OBFECTS (A"ROCED,REA, AF,NCTIONA! ORDER B- OBFECT_NA E


L!ST T,* CO+* OF P)OC*+U)*S AN+ FUNCT!ONS

9@ERE

OBFECT_T-"E

IN

SELECT TEET
PAC2A"E

FRO

,SER_SO,RCE

9@ERE NA E $ A4,ER-_E "A

ORDER B- LINE;

A pac(age is a schema ob$ect that groups logically related PL/SQL types# items# and subprograms. Pac(ages usually ha!e two parts# a specification and a body# $erits Si"#li%' securit' Li"it reco"#il&tion Per%or"&nce !n%or"&tion ,idin( ,idin( P#rts of P#c.#!e
A.PACKAGE SPECIFICATION

-o nee! to issue .( -T for e"ery $roce!ure in a $ackage *hange the bo!y of the $roce!ure or function %ithout changing s$ecification First call to $ackage loa!s %hole $ackage into memory /ith $ackages# you can s$ecify %hich ty$es# items# an! sub$rograms are $ublic 0"isible an! accessible1 or $ri"ate 0hi!!en an! inaccessible1. Im$lementation !etails from users# you $rotect the integrity of the $ackage.

The pac(age specification contains public declarations. The scope of these declarations is local to your database schema and global to the pac(age. So# the declared items are accessible from your application and from anywhere in the pac(age.
B.PACKAGE BODY

The pac(age body implements the pac(age specification. That is# the pac(age body contains the definition of e!ery cursor and subprogram declared in the pac(age specification. Seep in mind that subprograms defined in a pac(age body are accessible outside the pac(age only if their specifications also appear in the pac(age specification. PACKAGE OVERLOADING PL/SQL allows two or more pac(aged subprograms to ha!e the same name. This option is useful when you want a subprogram to accept parameters that ha!e different datatypes. PRI3ATE 3ERSUS PU- IC ITE$S PR&-,TE The pac(age body can also contain pri!ate declarations# which define types and items necessary for the internal wor(ings of the pac(age. The scope of these declarations is local to the pac(age body. Therefore# the declared types and items are inaccessible except from within the pac(age body. 3nli(e a pac(age spec# the declarati!e part of a pac(age body can contain subprogram bodies. P*./&0 Such items are termed pu(li". 7hen you must maintain items throughout a session or across transactions# place them in the declarati!e part of the pac(age body.

11

Ad4#nt#!es of P#c.#!es Pac(ages offer se!eral ad!antages9 modularity# easier application design# information hiding# added functionality# and better performance. #od.-a%!ty Pac(ages let you encapsulate logically related types# items# and subprograms in a named PL/SQL module. /ach pac(age is easy to understand# and the interfaces between pac(ages are simple# clear# and well defined. This aids application de!elopment. Eas!e% App-! at!on Des!gn 7hen designing an application# all you need initially is the interface information in the pac(age specs. -ou can code and compile a spec without its body. Then# stored subprograms that reference the pac(age can be compiled as well. -ou need not define the pac(age bodies fully until you are ready to complete the application. Info%/at!on 1!d!ng 7ith pac(ages# you can specify which types# items# and subprograms are public <!isible and accessible= or pri!ate <hidden and inaccessible=. 4or example# if a pac(age contains four subprograms# three might be public and one pri!ate. The pac(age hides the implementation of the pri!ate subprogram so that only the pac(age <not your application= is affected if the implementation changes. This simplifies maintenance and enhancement. Also# by hiding implementation details from users# you protect the integrity of the pac(age. Added +.n t!ona-!ty Pac(aged public !ariables and cursors persist for the duration of a session. So# they can be shared by all subprograms that execute in the en!ironment. Also# they allow you to maintain data across transactions without ha!ing to store it in the database. Bette% Pe%fo%/an e 7hen you call a pac(aged subprogram for the first time# the whole pac(age is loaded into memory. So# later calls to related subprograms in the pac(age re)uire no dis( &/ . Also# pac(ages stop cascading dependencies and thereby a!oid unnecessary recompiling. 4or example# if you change the implementation of a pac(aged function# racle need not recompile the calling subprograms because they do not depend on the pac(age body.

ORAC E SUPP IED PAC5A2ES P Pro!ided with the racle Ser!er P /xtend the functionality of the database P Allow access to certain SQL features normally restricted for PL/SQL Use Seri#&&6 Re,s#7&e P#c.#!es To help you manage the use of memory# PL/SQL pro!ides the pragma S/,&ALL-. ,/3SA*L/# which lets you mar( some pac(ages as serially reusa(le% -ou can so mar( a pac(age if its state is needed only for the duration of one call to the ser!er <for example# an "& call to the ser!er or a ser!er%to%ser!er ,P"=. The global memory for such pac(ages is pooled in the System 0lobal Area <S0A=# not allocated to indi!idual users in the 3ser 0lobal Area <30A=. That way# the pac(age wor( area can be reused. 7hen the call to the ser!er ends# the memory is returned to the pool. /ach time the pac(age is reused# its public !ariables are initialiTed to their default !alues or to +3LL. The maximum number of wor( areas needed for a pac(age is the number of concurrent users of that pac(age# which is usually much smaller than the number of logged%on users. The increased use of S0A memory is more than offset by the decreased use of 30A memory. Also# racle ages%out wor( areas not in use if it needs to reclaim S0A memory. 4or bodiless pac(ages# you code the pragma in the pac(age spec using the following syntax9 12

"RAG A SERIALL-_RE,SABLE; 4or pac(ages with a body# you must code the pragma in the spec and body. -ou cannot code the pragma only in the body. The following example shows how a public !ariable in a serially reusable pac(age beha!es across call boundaries9 CREATE "ACMAGE pN17 IS "RAG A SERIALL-_RE,SABLE; num N, BER #$ '; "ROCED,RE 2n2._pN1_s.a.e(n N, BER!; "ROCED,RE pr2n._pN1_s.a.e; END pN17;

DATABASE TRI""ERS 13

Trigger !efines an action the !atabase shoul! take %hen some !atabase relate! e"ent occurs. Triggers may be use! to su$$lement !eclarati"e referential integrity# to enforce com$lex business rules. !atabase trigger is a store! sub$rogram associate! %ith a table. 2ou can ha"e Oracle automatically fire the trigger before or after an I-S,(T# 3P4 T,# or 4,L,T, statement affects the table. Triggers are execute! %hen a s$ecific !ata mani$ulation comman! are $erforme! on s$ecific tables ROW LEVEL TRIGGERS (o% Le"el triggers execute once for each ro% in a transaction. (o% le"el triggers are create using FO( , *5 (O/ clause in the create trigger comman!. STATEMENT LEVEL TRIGGERS Statement Le"el triggers execute once for each transaction. For exam$le if you insert 677 ro%s in a single transaction then statement le"el trigger %ill be execute! once. BEFORE and AFTER Triggers Since triggers occur because of e"ents# they may be set to occur imme!iately before or after those e"ents. The follo%ing table sho%s the number of triggers that you can ha"e for a table. The number of triggers you can ha"e a for a table is 68 triggers. The follo%ing table sho%s the number of triggers that you can ha"e for a table. The number of triggers you can ha"e a for a table is 68 triggers. ROW LEVEL TRIGGER BEFORE INSERT UPDATE DELETE INSTEAD OF INSTEAD OF ROW STATEMENT LEVEL TRIGGER INSERT UPDATE DELETE

AFTER

INSERT UPDATE DELETE

INSERT UPDATE DELETE

AD3ANTA2ES O) TRI22ERS Fe&ture Security Auditing Data integrity Referential integrity Table replication *nh&nce"ent The Oracle Ser"er allo%s table access to users or roles. Triggers allo% table access accor!ing to !ata "alues. The Oracle Ser"er tracks !ata o$erations on tables. Triggers track "alues for !ata o$erations on tables. The Oracle Ser"er enforces integrity constraints. Triggers im$lement com$lex integrity rules. The Oracle Ser"er enforces stan!ar! referential integrity rules. Triggers im$lement nonstan!ar! functionality. The Oracle Ser"er co$ies tables asynchronously into sna$shots. Triggers co$y tables 14

Synchronously into re$licas. Derived data Event logging Syntax: CREATE OR RE"LACE TRIGGER OTRIGGER NA E5 K BEFORE G AFTER G INSTEAD OF L (INSERT OR ,"DATE OR DELETE! ON OTABLE NA E5 EAC@ RO9 BEGIN END; Example 1: CREATE OR RE"LACE TRIGGER DETAIL FOR EAC@ RO9 BEGIN IF LTRI (RTRI (TO_C@AR(S-SDATE,IDA-I!!!$IFRIDA-I T@EN IF INSERTING T@EN RAISE_A""LICATION_ERROR(;*'''7,IINSERT IS NOT "OSSIBLEI!; ELSIF ,"DATING T@EN RAISE_A""LICATION_ERROR(;*'''7,I,"DATE IS NOT "OSSIBLEI!; ELSIF DELETING T@EN RAISE_A""LICATION_ERROR(;*'''7,IDELETE IS NOT "OSSIBLEI!; END IF; END IF; END; Example 2: CREATE OR RE"LACE TRIGGER ITE DECLARE ITE ID N, BER; 4T- N, BER; BEGIN SELECT ITE ID INTO ITE ID FRO STOCM 9@ERE ITE ID $ #NE9%ITE ID; ,"DATE STOCM SET 4T-$4T-)#NE9%4T- 9@ERE ITE ID$#NE9%ITE ID; EECE"TION 9@EN NO_DATA_FO,ND T@EN INSERT INTO STOCM +AL,ES (#NE9%ITE ID, #NE9%4T-!; END; FOR EAC@ RO9 -_TRIG AFTER INSERT ON -_TRIG BEFORE INSERT OR ,"DATE OR DELETE ON REFERENCING OLD AS OLD G NE9 AS NE9 FOR The Oracle Ser"er com$utes !eri"e! !ata "alues manually. Triggers com$ute !eri"e! !ata "alues automatically. The Oracle Ser"er logs e"ents ex$licitly. Triggers log e"ents trans$arently.

15

Example 3: CREATE OR RE"LACE TRIGGER E " FOR EAC@ RO9 BEGIN INSERT INTO E "_BACM +AL,ES (#OLD%E "NO, #OLD%ENA E, #OLD%SAL, #OLD%DE"TNO!; END; Example 4: CREATE OR RE"LACE TRIGGER TR'* BEFORE INSERT OR ,"DATE OR DELETE ON E "7'' DECLARE D7 +ARC@AR(:!; BEGIN D7#$TO_C@AR(S-SDATE,ID-I!; IF D7 IN(IT,EI,I ONI! T@EN RAISE_A""LICATION_ERROR(;*''*(,ITR- ON ANOT@ER DA-I!; END IF; -_TRIG AFTER DELETE ON

END;

Example 5: CREATE OR RE"LACE TRIGGER TR'7 AFTER DELETE ON DE"T*'' FOR EAC@ RO9 BEGIN INSERT INTO DE"T7 +AL,ES (#OLD%DE"TNO,#OLD%DNA E,#OLD%LOC!; END; H S@O9 ERR Example 6: CREATE OR RE"LACE TRIGGER TR': AFTER ,"DATE ON E " FOR EAC@ RO9 BEGIN ,"DATE E "7'' SET SAL$#OLD%SAL&* 9@ERE E "NO$#OLD%E "NO; END; H S@O9 ERR Example 7: CREATE OR RE"LACE TRIGGER TR'( AFTER ,"DATE ON E "7'' DECLARE ,7 +ARC@AR*(('!; BEGIN SELECT ,SER INTO ,7 FRO D,AL; INSERT INTO ,SER7 +AL,ES(,7,S-SDATE,I,"DATEI!; END; H S@O9 ERR Example 8: CREATE OR RE"LACE TRIGGER TR'= AFTER DELETE ON DECLARE ,7 +ARC@AR*(('!; BEGIN SELECT ,SER INTO ,7 FRO D,AL; INSERT INTO ,SER7 +AL,ES(,7,S-SDATE,IDELETEI!; END; H S@O9 ERR E "7''

16

S1STE$ TRI22ER LOGON and LOGOFF Trigger Example 2ou can create this trigger to monitor ho% often you log on an! off# or you may %ant to %rite a re$ort on ho% long you are logge! on for. If you %ere a 49 %anting to !o this# you %oul! re$lace S*5,) %ith 4 T 9 S,.

7%

CREATE OR RE"LACE TRIGGER LOGON_TRIG AFTER lo1on ON SC@E A BEGIN INSERT INTO lo1_.r21_.able ( (user_2B, lo1_Ba.e, ac.2on! +AL,ES (user, s0sBa.e, ALo112n1 onA!; END; CREATE OR RE"LACE TRIGGER LOGOFF_TRIG BEFORE lo1o// ON SC@E A BEGIN INSERT INTO lo1_.r21_.able (user_2B, lo1_Ba.e, ac.2on! +AL,ES (user, s0sBa.e, ALo112n1 o//A!; END;
STATE$ENT

*%

CA

This allo%s you to call a store! $roce!ure# rather than co!ing the PL/SQL bo!y in the trigger itself.

CREATE KOR RE"LACEL TRIGGER .r211er_name .2m2n1 ePen.7 KOR ePen.* OR ePen.:L ON .able_name KREFERENCING OLD AS olB G NE9 AS neQL KFOR EAC@ RO9L K9@EN conB2.2onL CALL proceBure_name CREATE TRIGGER TEST: BEFORE INSERT ON E " CALL LOG_EEEC,TION
INSTEAD O) TRI22ERS &+ST/A1 4 triggers to tell ,A"L/ what to do instead of performing the actions that executed the trigger. An &+ST/A1 4 trigger can be used for a !iew. These triggers can be used to o!ercome the restrictions placed by oracle on any !iew which is non updateable. *-&"#le: CREATE OR RE"LACE +IE9 E "_DE"T AS SELECT A%DE"TNO,B%E "NO FRO 9@ERE A%DE"TNO$B%DE"TNO CREATE OR RE"LACE TRIGGER TRIG7 INSTEAD OF INSERT ON E "_DE"T REFERENCING NE9 AS N FOR EAC@ RO9 BEGIN INSERT INTO DE"T +AL,ES(#N%DE"TNO,IDNA EI!; INSERT INTO E " +AL,ES(#N%E "NO,IENA EI,#N%DE"TNO!; END; DE"T A,E " B

17

You might also like