Вы находитесь на странице: 1из 14

SQL PROCEDURES

PL/SQL subprograms are named PL/SQL blocks that can be invoked with a set of parameters. PL/SQL provides two kinds of subprograms:

Functions: these subprograms return a single value, mainly used to compute and return a value. Procedures: these subprograms do not return a value directly, mainly used to perform an action. Parts of a PL/SQL Subprogram ach PL/SQL subprogram has a name, and may have a parameter list. Like anonymous PL/SQL blocks and, the named blocks a subprograms will also have following three parts: S.N. Parts Description

Dec!arati"e Part "t is an optional part. #owever, the declarative part for a subprogram does not start with the $ %L&' keyword. "t contains declarations of types, cursors, constants, variables, e(ceptions, and nested subprograms. )hese items are local to the subprogram and cease to e(ist when the subprogram completes e(ecution. E#ecutab!e Part )his is a mandatory part and contains statements that perform the designated action. E#ception$%and!ing )his is again an optional part. "t contains the code that handles run,time errors.

* +

&. Creating a Procedure


& procedure is created with the %' &) -' ' PL&% P'-% $.' statement. )he simplified synta( for the %' &) -' ' PL&% P'-% $.' statement is as follows: %' &) /-' ' PL&% 0 P'-% $.' procedure1name /2parameter1name /"3 4 -.) 4 "3 -.)0 type /, ...050 6"S 4 &S7 8 9"3 : procedure1body ; 3$ procedure1name< =here,

!. procedure-name specifies the name of the procedure. *. /-' ' PL&% 0 option allows modifying an e(isting procedure. +. )he optional parameter list contains name, mode and types of the parameters. "3 represents that value will be passed from outside and -.) represents that this parameter will be used to return a value outside of the procedure. >. procedure-body contains the e(ecutable part. ?. )he &S keyword is used instead of the "S keyword for creating a standalone procedure.

'. E#ecuting a Standa!one Procedure


& standalone procedure can be called in two ways:

.sing the @ %.) keyword %alling the name of the procedure from a PL/SQL block )he above procedure named AgreetingsA can be called with the keyword as: @ %.) greetings< )he above call would display: #ello =orld PL/SQL procedure successfully completed. )he procedure can also be called from another PL/SQL block: 8 9"3 greetings< 3$< / @ %.)

@&BPL ,

Parameter Bodes in PL/SQL Subprograms S.N. Parameter (ode Description )N &n "3 parameter lets you pass a value to the subprogram. )t is a read$on!* parameter. "nside the subprogram, an "3 parameter acts like a constant. "t cannot be assigned a value. Cou can pass a constant, literal, initialiDed variable, or e(pression as an "3 parameter. Cou can also initialiDe it to a default value< however, in that case, it is omitted from the subprogram call. )t is t%e defau!t mode of parameter passing. Parameters are passed b* reference. OU+ &n -.) parameter returns a value to the calling program. "nside the subprogram, an -.) parameter acts like a variable. Cou can change its value and reference the value after assigning it. +%e actua! parameter must be "ariab!e and it is passed b* "a!ue. )N OU+ &n "3 -.) parameter passes an initial value to a subprogram and returns an updated value to the caller. "t can be assigned a value and its value can be read. )he actual parameter corresponding to an "3 -.) formal parameter must be a variable, not a constant or an e(pression. Eormal parameter must be assigned a value. ,ctua! parameter is passed b* "a!ue.

@&BPL :

)his program finds the minimum of two values, here procedure takes two numbers using "3 mode and returns their minimum using -.) parameters. $ %L&' a number< b number< c number< P'-% $.' findBin2( "3 number, y "3 number, D -.) number5 "S 8 9"3 "E ( : y )# 3 D:F (< LS D:F y< 3$ "E< 3$< 8 9"3 a:F *+< b:F >?< findBin2a, b, c5< dbms1output.put1line2A Binimum of 2*+, >?5 : A 44 c5< 3$< /

SQL +R)--ERS
)riggers are stored programs, which are automatically e(ecuted or fired when some events occur. )riggers are, in fact, written to be e(ecuted in response to any of the following events:

& database manipulation 2$BL5 statement 2$ L ) , "3S '), or .P$&) 5. & database definition 2$$L5 statement 2%' &) , &L) ', or $'-P5. & database operation 2S 'G ' ''-', L-9-3, L-9-EE, S)&').P, or S#.)$-=35. )riggers could be defined on the table, view, schema, or database with which the event is associated. .enefits of +riggers

)riggers can be written for the following purposes:


9enerating some derived column values automatically nforcing referential integrity vent logging and storing information on table access &uditing Synchronous replication of tables "mposing security authoriDations Preventing invalid transactions

&. Creating +riggers


)he synta( for creating a trigger is: %' &) /-' ' PL&% 0 )'"99 ' trigger1name 68 E-' 4 &E) ' 4 "3S) &$ -E 7 6"3S ') /-'0 4 .P$&) /-'0 4 $ L ) 7 /-E col1name0 -3 table1name /' E ' 3%"39 -L$ &S o 3 = &S n0 /E-' &%# '-=0 =# 3 2condition5

$ %L&' $eclaration,statements 8 9"3 (ecutable,statements @% P)"-3 (ception,handling,statements 3$< =here,


%' &) /-' ' PL&% 0 )'"99 ' trigger1name: %reates or replaces an e(isting trigger with the trigger_name. 68 E-' 4 &E) ' 4 "3S) &$ -E7 : )his specifies when the trigger would be e(ecuted. )he "3S) &$ -E clause is used for creating trigger on a view. 6"3S ') /-'0 4 .P$&) /-'0 4 $ L ) 7: )his specifies the $BL operation. /-E col1name0: )his specifies the column name that would be updated. /-3 table1name0: )his specifies the name of the table associated with the trigger. /' E ' 3%"39 -L$ &S o 3 = &S n0: )his allows you to refer new and old values for various $BL statements, like "3S '), .P$&) , and $ L ) . /E-' &%# '-=0: )his specifies a row level trigger, i.e., the trigger would be e(ecuted for each row being affected. -therwise the trigger will e(ecute Hust once when the SQL statement is e(ecuted, which is called a table level trigger. =# 3 2condition5: )his provides a condition for rows for which the trigger would fire. )his clause is valid only for row level triggers.

+,.LE ON /0)C0 +R)--ER CRE,+ED1

+riggering a +rigger

SQL CURSORS
-racle creates a memory area, known as conte(t area, for processing an SQL statement, which contains all information needed for processing the statement, for e(ample, number of rows processed, etc. & cursor is a pointer to this conte(t area. PL/SQL controls the conte(t area through a cursor. & cursor holds the rows 2one or more5 returned by a SQL statement. )he set of rows the cursor holds is referred to as the acti"e set. Cou can name a cursor so that it could be referred to in a program to fetch and process the rows returned by the SQL statement, one at a time. )here are two types of cursors:

"mplicit cursors (plicit cursors

)mp!icit Cursors
"mplicit cursors are automatically created by -racle whenever an SQL statement is e(ecuted, when there is no e(plicit cursor for the statement. Programmers cannot control the implicit cursors and the information in it. =henever a $BL statement 2"3S '), .P$&) and $ L ) 5 is issued, an implicit cursor is associated with this statement. Eor "3S ') operations, the cursor holds the data that needs to be inserted. Eor .P$&) and $ L ) operations, the cursor identifies the rows that would be affected. "n PL/SQL, you can refer to the most recent implicit cursor as the SQL cursor, which always has the attributes like IE-.3$, I"S-P 3, I3-)E-.3$, and I'-=%-.3). )he SQL cursor has additional attributes, I8.LJ1'-=%-.3) and I8.LJ1 @% P)"-3S, designed for use with the E-'&LL statement. )he following table provides the description of the most used attributes: ,ttribute IE-.3$ Description 'eturns )'. if an "3S '), .P$&) , or $ L ) statement affected one or more rows or a S L %) "3)- statement returned one or more rows. -therwise, it returns E&LS . )he logical opposite of IE-.3$. "t returns )'. if an "3S '), .P$&) , or $ L ) statement affected no rows, or a S L %) "3)- statement returned no rows. -therwise, it returns E&LS . &lways returns E&LS for implicit cursors, because -racle closes the SQL cursor automatically after e(ecuting its associated SQL statement.

I3-)E-.3$

I"S-P 3

I'-=%-.3)

'eturns the number of rows affected by an "3S '), .P$&) , or $ L ) statement, or returned by a S L %) "3)- statement.

&ny SQL cursor attribute will be accessed as s2!3attribute4name as shown below in the e(ample.

Example:
We will be using the CUSTOMERS table we had created and used in the previous chapters. Select * from customers; +----+----------+-----+-----------+----------+ | ID | NAME | AGE | ADDRESS | SALARY | +----+----------+-----+-----------+----------+ | 1 | Ramesh | 3 | Ahme!a"a! | ###$## | | | %h&la' | ( | Delh& | 1(##$## | | 3 | )aush&) | 3 | %ota | ###$## | | * | +ha&tal& | ( | Mum"a& | ,(##$## | | ( | -ar!&) | . | /ho0al | 1(##$## | | , | %omal | | M2 | *(##$## | +----+----------+-----+-----------+----------+ The following program would update the table and increase salary of each customer by 500 and use the SQL%ROWCOUNT attribute to determine the number of rows affected: DE+LARE total3ro4s 'um"er5 6; /EGIN 72DA8E customers SE8 salar9 : salar9 + (##; I; s<l='otfou'! 8-EN !"ms3out0ut$0ut3l&'e5>'o customers selecte!>6; ELSI; s<l=fou'! 8-EN total3ro4s ?: s<l=ro4cou't; !"ms3out0ut$0ut3l&'e5 total3ro4s || > customers selecte! >6; END I;; END; @ When the above code is executed at SQL prompt, it produces the following result: , customers selecte! 2L@SAL 0roce!ure successfull9 com0lete!$ If you check the records in customers table, you will find that the rows have been updated:

Select * from customers; +----+----------+-----+-----------+----------+ | ID | NAME | AGE | ADDRESS | SALARY | +----+----------+-----+-----------+----------+ | 1 | Ramesh | 3 | Ahme!a"a! | (##$## | | | %h&la' | ( | Delh& | ###$## | | 3 | )aush&) | 3 | %ota | (##$## | | * | +ha&tal& | ( | Mum"a& | .###$## | | ( | -ar!&) | . | /ho0al | B###$## | | , | %omal | | M2 | (###$## | +----+----------+-----+-----------+----------+

E#p!icit Cursors
(plicit cursors are programmer defined cursors for gaining more control over the conte#t area. &n e(plicit cursor should be defined in the declaration section of the PL/SQL 8lock. "t is created on a S L %) Statement which returns more than one row. )he synta( for creating an e(plicit cursor is : %.'S-' cursor1name "S select1statement< =orking with an e(plicit cursor involves four steps:

$eclaring the cursor for initialiDing in the memory -pening the cursor for allocating memory Eetching the cursor for retrieving data %losing the cursor to release allocated memory

Dec!aring t%e Cursor


$eclaring the cursor defines the cursor with a name and the associated S L %) statement. Eor e(ample: %.'S-' c1customers "S S L %) id, name, address E'-B customers<

Opening t%e Cursor


-pening the cursor allocates memory for the cursor and makes it ready for fetching the rows returned by the SQL statement into it. Eor e(ample, we will open above,defined cursor as follows: -P 3 c1customers<

Fetc%ing t%e Cursor


Eetching the cursor involves accessing one row at a time. Eor e(ample we will fetch rows from the above,opened cursor as follows: E )%# c1customers "3)- c1id, c1name, c1addr<

C!osing t%e Cursor


%losing the cursor means releasing the allocated memory. Eor e(ample, we will close above,opened cursor as follows: %L-S c1customers< (ample: Eollowing is a complete e(ample to illustrate the concepts of e(plicit cursors: $ %L&' c1id customers.idItype< c1name customers.nameItype< c1addr customers.addressItype< %.'S-' c1customers is

S L %) id, name, address E'-B customers< 8 9"3 -P 3 c1customers< L--P E )%# c1customers into c1id, c1name, c1addr< dbms1output.put1line2c1id 44 A A 44 c1name 44 A A 44 c1addr5< @") =# 3 c1customersInotfound< 3$ L--P< %L-S c1customers< 3$< /