PLSQL
PLSQL
PLSQL
In these 2 lessons, you will understand and demonstrate knowledge in the following areas: Overview of PL/SQL Develo ing a PL/SQL !lo"k Intera"ting with the Ora"le data!ase #ontrolling PL/SQL ro"ess flow $% li"it "ursor handling $rror handling In Ora"le, there is a s e"ial language availa!le for develo ers to "ode stored ro"edures that seamlessly integrate with data!ase o!&e"t a""ess via the language of data!ase o!&e"ts, SQL' (owever, this language offers far more e%e"ution otential than sim le u dates, sele"ts, inserts, and deletes' )his language offers a ro"edural e%tension that allows for modularity, varia!le de"laration, loo s and other logi" "onstru"ts, and advan"ed error handling' )his language is known as PL/SQL' )he ne%t few sessions will resent an overview of PL/SQL synta%, "onstru"ts, and usage'
Overview of PL/SQL
In this se"tion, you will "over the following to i"s related to overview of PL/SQL: *sing PL/SQL to a""ess Ora"le +aria!le value assignment PL/SQL offers many advantages over other rogramming languages for handling the logi" and !usiness rule enfor"ement of data!ase a li"ations' It is a straightforward language with all the "ommon logi" "onstru"ts asso"iated with a rogramming language, lus many things other languages don,t have, su"h as ro!ust error handling and modulari-ation of "ode !lo"ks' )he PL/SQL "ode used to interfa"e with the data!ase is also stored dire"tly on the Ora"le data!ase, and is the only rogramming language that interfa"es with the Ora"le data!ase natively and within the data!ase environment' )his overview will "over the details of !enefits asso"iated with using PL/SQL in the Ora"le data!ase and the !asi" "onstru"ts of the PL/SQL language'
.any a li"ations that use "lient/server ar"hite"ture have one thing in "ommon/a diffi"ulty maintaining the !usiness rules for an a li"ation' 0hen !usiness rules are de"entrali-ed throughout the a li"ation, the develo ers must make "hanges throughout the a li"ation and im lement system testing that will determine whether the "hanges are suffi"ient' (owever, in tight s"heduling situations, the first de loyment item to get left off is almost invaria!ly testing' One logi"al design "hange that should !e im lemented in this s"enario is the "entrali-ation of logi" in the a li"ation to allow for easier management of "hange' In systems that use the Ora"le data!ase, a 1middle layer1 of a li"ation logi" "an !e designed with PL/SQL' )he !enefits are as follows: PL/SQL is managed "entrally within the Ora"le data!ase' )he D23 manages sour"e "ode and e%e"ution rivileges with the same synta% used to manage other data!ase o!&e"ts' PL/SQL "ommuni"ates natively with other Ora"le data!ase o!&e"ts' PL/SQL is easy to read and has many features for "ode modularity and error handling' )he features of PL/SQL that manage "entrali-ed "ode management make PL/SQL the logi"al "hoi"e for a data!ase4"entri" "lient/server a li"ation that uses stored ro"edures for !usiness logi" and allows the "lient a li"ation develo er to fo"us mainly on the user interfa"e' Storing a li"ation logi" "entrally means only having to "om ile a "hange on"e, and then it is immediately a""essi!le to all users of the a li"ation' 0ith !usiness logi" stored in the "lient a li"ation, the effort of distri!uting "ode in"ludes the re"om ilation of the "lient a li"ation 5 otentially on several different latforms6' )here is an additional distri!ution "ost to getting the new e%e"uta!le version of the "lient on every user,s deskto , as well as overhead for "ommuni"ation and su ort to make sure all users of the a li"ation are on the right version' De"entrali-ed "om uting has in"reased the "a a"ity of organi-ations to rovide easy4to4use and fast a li"ations to their "ustomers' 2ut some "entrali-ation im roves the &o! even further !y allowing the a li"ation develo ment sho the a!ility to eliminate distri!ution "hannels for !usiness logi" "hanges and fo"us the "lient4side develo ers, efforts on the "lient a li"ation' 7igure 849 shows an e%am le of the differen"e !etween "entrali-ed and de"entrali-ed !usiness logi" "ode management'
Self #$ercises
9' 0hat are some advantages of using PL/SQL to a""ess the data!ase: 2' 0here is PL/SQL "om iled and stored:
%odularit&
PL/SQL allows the develo er to "reate rogram modules to im rove software reusa!ility and to hide the "om le%ity of the e%e"ution of a s e"ifi" o eration !ehind a name' 7or e%am le, there may !e a "om le% ro"ess involved to an em loyee re"ord to a "or orate data!ase, whi"h re;uires re"ords to !e added to several different ta!les for several different a li"ations' Stored ro"edures may handle the addition of re"ords to ea"h of the systems, making it look to the user that the only ste re;uired is entering data on one s"reen' In reality, that s"reen,s worth of data entry may "all do-ens of se arate ro"edures, ea"h designed to handle one small "om onent of the overall ro"ess of adding the em loyee' )hese "om onents may even !e reused data entry "ode !lo"ks from the various ension, health "are, day "are, ayroll, and other (< a li"ations,
whi"h have sim ly !een re a"kaged around this new data entry s"reen' 7igure 842 shows how modularity "an !e im lemented in PL/SQL !lo"ks'
FUNCTION convert_money (amount IN NUMBER, from_currency IN VARCHAR2, to_currency IN VARCHAR2 ) IS /* denotes the beginning of the declaration sectionif no variables */ /* to declare, use the AS keyword instead of IS. */ My_new_amt number := 0; BEGIN /* begins the executable section of a code block. / IF (b>3) THEN DBMS_OUTPUT.PUT_LINE(Hello, World.); ELSE RAISE bad_data; END IF; EXCEPTIONS /*Begins the Exception Handler */ WHEN bad_data THEN DBMS._OUTPUT.PUT_LINE(Error condition); END; )he other "lass of PL/SQL !lo"ks is known as an unnamed or anonymous !lo"k' It is easier to identify the de"laration se"tion of an anonymous PL/SQL !lo"k !e"ause the de"laration se"tion is re"eded !y the declare keyword' It to "ontains a de"laration se"tion, an e%e"uta!le se"tion, and an e%"e tion handler' DECLARE /* begins the declaration section in an anonymous block */ My_convert_amt NUMBER; My_convert_currency VARCHAR2; My_old_currency VARCHAR2; BEGIN /* begins the executable section of a code block. / IF (b>3) THEN DBMS_OUTPUT.PUT_LINE(Hello, World.); ELSE RAISE bad_data; END IF; EXCEPTIONS /*Begins the Exception Handler */ WHEN bad_data THEN DBMS._OUTPUT.PUT_LINE(Error condition); END;
*IP: *-e call to .,%S/OU*PU* PU*/LI0# in one of t-e code !loc(s a!ove is used to write a line of out+ut to t-e SQL1Plus interface In order to view t-e line of out+ut +roduced) use t-e set serverout+ut on co""and
in"lude PL/SQL ta!les and re"ords' )hese 1 ro"edural1 "onstru"ts are the items in PL/SQL that allow it to !e !oth a rogramming language for su orting !usiness rules and a fun"tional language for roviding data'
Cursors
One of the real strengths of PL/SQL, however, is its a!ility to handle "ursors' 3 "ursor is a handle to an address in memory that stores the results of an e%e"uted SQL statement' )hey are e%tremely useful for erforming o erations on ea"h row returned from a select statement' )herefore, the PL/SQL rogrammer often finds herself using the loo ing ro"edural "onstru"ts of PL/SQL in "on&un"tion with "ursor mani ulation o erations'
#rror 3andling
$rrors are "alled e%"e tions in PL/SQL, and they are "he"ked im li"itly anywhere in the "ode !lo"k' If at any time an error o""urs in the "ode !lo"k, the e%"e tion "orres onding to that error "an !e raised' 3t that oint, e%e"ution in the e%e"uta!le "ode !lo"k sto s and "ontrol is transferred to the e%"e tion handler' )here are many different ty es of e%"e tions in Ora"le, some of whi"h are user defined' Others are defined !y the Ora"le PL/SQL engine'
Self #$ercises
9' 0hat is PL/SQL: =ame some !enefits to a""essing the Ora"le data!ase with PL/SQL' 2' 0hat are the three arts of a PL/SQL "ode !lo"k: =ame four different ty es of "ode !lo"ks in Ora"le' 0hat are some rogram "onstru"ts availa!le in PL/SQL: >' 0hat is the differen"e !etween a named and an anonymous "ode !lo"k:
.ata!ase .atat&+es
)here are several dataty es that "an !e used in PL/SQL that "orres ond to the dataty es used on the data!ase' )hese ty es are as follows: 0U%,#5 *sed to store any num!er' C3A56size7) 4A5C3A5'6size7 *sed to store al hanumeri" te%t strings' )he #(3< dataty e ads the value stored to the full length of the varia!le with !lanks' .A*# *sed to store dates' LO08 Stores large !lo"ks of te%t, u to 2 giga!ytes in length' LO08 5A9 Stores large !lo"ks of data stored in !inary format' 5A9 Stores smaller !lo"ks of data stored in !inary format' %LSLA,#L *sed in )rusted Ora"le' 5O9I. *sed to store the s e"ial format of <O0IDs on the data!ase'
0ondata!ase .atat&+es
)here are also several other PL/SQL dataty es that are not designed for use in storing data to a ta!le: .#C) .#CI%AL) 5#AL) .OU,L#/P5#CISIO0 )hese numeri" dataty es are a su!set of the =*.2$< dataty e that is used for "olumn de"laration in the Ora"le data!ase' I0*#8#5) I0*) S%ALLI0*) 0A*U5AL) POSI*I4#) 0U%#5IC )hese numeri" dataty es are a su!set of the =*.2$< dataty e that is used for "olumn de"laration in the Ora"le data!ase' ,I0A5:/I0*#8#5 )his dataty e is "onsidered se arately from the others, !e"ause it is stored in !inary format' 3 varia!le in 2I=3<?@I=)$A$< format "annot !e stored in the data!ase without "onversion first' C3A5AC*#5 3nother name for the #(3< dataty e' 4A5C3A5 3nother name for the +3<#(3<2 dataty e' ,OOL#A0 Stores a )<*$/73LS$ value' *A,L#/5#CO5. )a!les "an !e used to store the e;uivalent of an array, while re"ords store varia!les with "om osite dataty es'
;*:P#
In general, the varia!les that deal with ta!le "olumns should have the same dataty e as the "olumn itself' <ather than look it u , the develo er "an use PL/SQL,s s e"ial synta"ti" feature that allows the develo er sim ly to identify the ta!le "olumn to whi"h this varia!le,s dataty e should "orres ond' )his synta% uses a s e"ial keyword known as ;t&+e' 0hen using the ;t&+e "olumn, all the develo er needs to know is the name of the "olumn and the ta!le to whi"h the varia!le will "orres ond' 3dditionally, a varia!le "an !e de"lared with an initiali-ation value !y setting it e;ual to the value in the de"laration se"tion' =oti"e the "hara"ters used to set the varia!le to a value: DECLARE My_employee_id employee.empid%TYPE; BEGIN DECLARE My_salary employee.salary%TYPE := 0; My_lastname employee.lastname%TYPE:= SMITH; BEGIN
;5O9*:P#
)here is another varia!le de"laration method that uses the same referen"e rin"i le des"ri!ed in the te%t a!ove' It is "alled ;rowt&+e, and it ermits the develo er to "reate a "om osite dataty e in whi"h all the "olumns of a row in the ta!le referen"ed are lum ed together into a re"ord' 7or e%am le, if the $.PLO?$$ ta!le "ontains four "olumns/$.PID, L3S)=3.$, 7I<S)=3.$, and S3L3<?/and the develo er wants to mani ulate the values in ea"h "olumn of a row using only one referen"ed varia!le, the varia!le "an !e de"lared with the ;rowt&+e keyword' #om are the use of ;rowt&+e to manual re"ord de"laration: DECLARE My_employee employee%ROWTYPE; BEGIN or manually: DECLARE TYPE t_employee IS RECORD ( My_empid employee.empid%TYPE, My_lastname employee.lastname%TYPE, My_firstname employee.firstname%TYPE, My_salary employee.salary%TYPE); My_employee t_employee; BEGIN
*IP: ,loc(s of PL/SQL code can !e nested) t-at is to sa& t-at a +rocedure can -ave su!+rocedures In w-ic- case) t-e sa"e +rinci+les of varia!le sco+e discussed in C-a+ter ' also a++l& to nested PL/SQL !loc(s
Constant .eclaration
It may !e useful for a develo er to de"lare "onstants in the de"laration se"tion of the PL/SQL !lo"ks develo ed as well' #onstants make a good su!stitute for the use of hard4"oded values, or 1magi" num!ers'1 3 magi" value in rogramming is a value that is re;uired to erform an o eration or "al"ulation !ut does not have any sort of meaning in the "ode !lo"k to hel others identify why the value is there' )ake, for e%am le, a fun"tion that "al"ulates the area of a "ir"le, whi"h is the num!er i times radius s;uared' )he num!er i is well known to most eo le, !ut imagine if it was not, how diffi"ult it would !e to understand the reason for having the num!er >'9B98C2D8E in the middle of the fun"tion' CREATE FUNCTION find_circle_area ( p_radius IN circle.radius%TYPE ) RETURN NUMBER IS My_area number := 0; Pi constant number := 3.14159265358; BEGIN My_area := (p_radius*p_radius)* Pi; Return my_area; END;
#$ercises
9' Identify some of the data!ase and nondata!ase dataty es in PL/SQL that "an !e used' 2' (ow "an the develo er de"lare PL/SQL varia!les without e% li"itly identifying the dataty e: >' (ow does the develo er de"lare a varia!le with an initiali-ed value: B' (ow does the develo er de"lare a "onstant: 0hy might the develo er use a "onstant:
#$ercises
9' 0here "an a varia!le !e assigned a value: 2' 0hat is the assignment o erator: (ow does it differ from the e;uality o erator:
SELECT * INTO my_employee FROM employee WHERE empid = 49594; UPDATE employee SET salary = my_employee.my_salary + 10000 WHERE empid = my_employee.my_empid; INSERT INTO employee (empid, lastname, firstname, salary) VALUES (emp_sequence.nextval, my_lastname, my_firstname, my_salary); My_empid := 59495; DELETE FROM employee WHERE empid = my_empid; END;
Self #$ercises
9' 0hat s e"ial "hara"ters are re;uired for using data mani ulation statements in PL/SQL: 2' $% lain how Ora"le assigns values to elements in a re"ord'
!y ;notfound' ;iso+en Identifies whether the "ursor referred to is o ened and ready for use' <eturns a )<*$ or 73LS$ value' In order to understand fully the use of "ursor attri!utes, a dis"ussion of "ursor ro"essing is re;uired' 7or now, it is suffi"ient to know that "ursors are generally named something, and that the synta% for using the "ursor attri!utes identified a!ove is to identify the "ursor name, followed !y the attri!ute' )his synta% is similar to that used for the ;t&+e and ;rowt&+e varia!le de"laration attri!utes' 7or e%am le, the o en or "lose status of "ursor $.PLO?$$S "an !e referred to !y its "ursor attri!ute, with the user entering $.PLO?$$S ;iso+en, whi"h will return )<*$ if the "ursor is o en or 73LS$ if the "ursor is "losed' .ore details a!out using "ursor attri!utes and general "ursor ro"essing a ears later in the "ha ter'
#$ercises
9' 0hat value "an im li"it "ursor attri!utes serve in PL/SQL "ode: 2' 0hat are some of the im li"it "ursor attri!utes a develo er "an use in PL/SQL:
are several different fun"tions that allow the user to start, end, and moderate the transa"tion ro"essing within PL/SQL !lo"ks'
#$ercises
9' 0hat transa"tion ro"essing features are availa!le in PL/SQL: 2' 0hat is D2.S@)<3=S3#)IO=:
"ommemorate the Jewish 7east of Lights around the same time as #hristmas6 usually "ontains eight or nine "andles, !ut never ten' )herefore, the statement is 73LS$' In the third e%am le, B definitely does not e;ual 9I, so the statement is 73LS$' )he final e%am le illustrates an interesting rin"i le a!out "om arison o erationsK sometimes today is )uesday, !ut sometimes it is not' )he validity of the statement, then, de ends on the day on whi"h the "om arison is made' #onditional statement ro"essing me"hanisms allow the develo er to stru"ture "ode su"h that "ertain statements may or may not e%e"ute !ased on the validity of a "om arison o eration' )he general synta% for "onditional statements is 1if the "om arison is )<*$, t-en do the following'1 PL/SQL also offers an o tional add4on, "alled else, whi"h says essentially, 1otherwise, do whatever the else "lause says'1 DECLARE My_hypotenuse NUMBER := 0; BEGIN IF TO_DATE(sysdate, DAY) = TUESDAY THEN Execute find_hypotenuse(56,45,my_hypotenuse); ELSE My_hypotenuse := derive_hypotenuse(56,45); END IF; END; =ote that single4row o erations are allowed in "om arison statements, so long as they resolve to a dataty e that "an !e "om ared ro erly' If, for e%am le, one side of the "om arison o eration resolves to a num!er and the other side is a te%t string, then that will !e a ro!lem' 3dditionally, note that the else statement "an "ontain another if statement, allowing for nested if statements that amount to a case o eration' DECLARE My_hypotenuse NUMBER; BEGIN IF TO_DATE(sysdate, DAY) = TUESDAY THEN Execute find_hypotenuse(56,45,my_hypotenuse); ELSIF TO_DATE(sysdate, DAY) = THURSDAY THEN My_hypotenuse := derive_hypotenuse(56,45); ELSE My_hypotenuse := 0; END IF; END; On"e again, if the first "ondition is )<*$, the first !lo"k of PL/SQL will e%e"ute' If the se"ond "ondition is )<*$, then the se"ond !lo"k of PL/SQL "ode will e%e"ute' If neither of the re"eding "ode !lo"ks is )<*$, then the third PL/SQL !lo"k will e%e"ute' )o end an if statement, there must !e the end if keywords' Otherwise, the "ode after the "onditional e% ression will !e treated as art of the else "lause, whi"h will "ause the PL/SQL "om iler to error out'
3ny "om arison o eration that "an !e used in a w-ere "lause is a SQL statement "an !e used as the "om arison o eration in an if2t-en statement'
Self #$ercises
9' 0hat statement allows the develo er to handle "onditional statement ro"essing: 2' 0hat is a "om arison o eration: 0hat is 2oolean logi":
Using Loo+s
3nother situation that arises in rogramming is the need to e%e"ute a set of statements re eatedly' )he re etitions "an !e "ontrolled in two ways: the first is to re eat the "ode for a s e"ified num!er of times, and the se"ond is to re eat the "ode until some "ondition is met, thus rendering a "om arison o eration to )<*$' )he ty es of loo s that are availa!le in PL/SQL are listed as follows' Loo+2e$it statements 9-ile2loo+ statements For2loo+ statements
LOOP2#=I* State"ents
)he loo+2e$it statement is the sim lest ty e of loo that "an !e written in PL/SQL' )he loo+ keyword denotes the !eginning of the "ode !lo"k that will !e re eated, and the end loo+ keywords denote the end of the "ode !lo"k that will !e re eated' )he e$it keyword s e"ified !y itself denotes that ro"ess should !reak out of the loo , while the e$it w-en keywords denote a "om arison o eration that will test whether the statement is finished e%e"uting' DECLARE My_leg NUMBER := 0; My_hypotenuse NUMBER := 0; BEGIN LOOP My_leg := my_leg + 1; Execute find_hypotenuse(my_leg,my_leg,my_hypotenuse); IF my_leg = 25 THEN EXIT; END IF; END LOOP; END; )he if2t-en statement is designed to determine if the "onditions within the loo are su"h that the loo should terminate' )he e$it statement instru"ts the PL/SQL e%e"ution me"hanism to leave the loo ' 3n alternative to setting u an
if2t-en statement to determine if the loo should end is to add a w-en "ondition to the e$it statement' )he w-en "ondition "ontains the "om arison o eration that the if2t-en statement would have handled' 3n e%am le of a sim le loo+ statement that uses an e$it w-en statement is listed in the following "ode !lo"k' =ote that the "ode is essentially a revision of the sim le loo+ !lo"k' DECLARE My_leg NUMBER := 0; My_hypotenuse NUMBER := 0; BEGIN LOOP My_leg := my_leg + 1; Execute find_hypotenuse(my_leg,my_leg,my_hypotenuse); EXIT WHEN my_leg = 25; END LOOP; END; )he w-en "lause is very useful for the develo er !e"ause it offers an elegant solution to defining when the loo will end, as o osed to hiding an e$it statement inside an if2t-en statement' (owever, there are other ossi!ilities for develo ing loo s to handle re etition in "oding'
93IL#2LOOP State"ents
)he ne%t ty e of loo that a ro%imates the usage of a loo+2e$it w-en statement is the w-ile loo+ statement' )he "ode in the revious !lo"k "an !e rewritten to in"lude the w-ile loo+' )he only differen"e !etween the w-ile loo+ statement and the loo+2e$it w-en statement is where PL/SQL evaluates the e$it "ondition' In a w-ile loo+ statement, the e%iting "ondition is evaluated at the !eginning of the statement, while in the loo+2e$it w-en statement, the e$it "ondition is evaluated wherever the e$it w-en statement is la"ed' In one sense, the loo+2e$it w-en statement offers more fle%i!ility than the w-ile loo+ statement does !e"ause loo+2e$it w-en allows the develo er to s e"ify the e$it "ondition wherever he wants' (owever, the fle%i!ility that the w-ile2loo+ statement may la"k is made u for !y its "om arative elegan"e, in that there is no need for an e$it statement' DECLARE My_leg NUMBER := 0; My_hypotenuse NUMBER := 0; BEGIN WHILE my_leg < 25 LOOP My_leg := my_leg + 1; Execute find_hypotenuse(my_leg,my_leg,my_hypotenuse); END LOOP; END;
FO52LOOP State"ents
)he final e%am le of loo ing "onstru"ts to !e resented is the for2loo+ statement' )his ty e of loo allows the develo er to s e"ify e%a"tly the num!er of times the "ode will e%e"ute !efore PL/SQL will !reak out of it' )o a""om lish this ro"ess, the for2loo+ statement s e"ifies a loo "ounter and a range through whi"h the "ounter will "ir"ulate' O tionally, the develo er "an "ir"ulate through the loo "ounter in reverse order, or in numeri" des"ending order' )he loo "ounter is then availa!le for use !y the statements in the for2 loo+ statement' DECLARE My_leg NUMBER := 0; My_hypotenuse NUMBER := 0; BEGIN FOR my_leg IN 1..25 LOOP Execute find_hypotenuse(my_leg,my_leg,my_hypotenuse); END LOOP; END; =oti"e that the use of a for2loo+ statement made this "ode !lo"k even more elegant' =o longer ne"essary is the statement that in"rements the .?@L$A varia!le, sin"e the for2loo+ statement handles the in"remental a"tivity automati"ally' )he develo er is left in this "ase with a !lo"k of "ode in the loo that handles no maintenan"e tasks' )here is another ty e of for2loo+ statement related to "ursor handling that offers the same elegan"e and utility as the for2loo+ statement detailed in the revious "ode !lo"k' Its usage, as well as the more general usage of "ursors will !e "overed in the ne%t se"tion of this "ha ter'
Self #$ercises
9' (ow is nested "onditional statement ro"essing handled: 2' 0hat are three different ty es of loo s: 0hat is an e$it w-en statement: 0hat is a loo "ounter, and for whi"h ty e of loo is it most "ommonly used: 0hi"h ty e of loo doesn,t re;uire an e% li"it e$it statement:
select statement, and they have other uses as well' )his dis"ussion will resent the uses for "ursors, along with the different ty es of "ursors availa!le in Ora"le' #reation of all ty es of "ursors will !e resented, along with a more detailed dis"ussion of "reating the s e"ial for loo for "ursor data handling that was mentioned at the end of the revious se"tion'
3n e% li"it "ursor is one that is named !y the develo er' )he "ursor is little more than a select statement that has a name' 3ny sort of select statement "an !e used in an e% li"it "ursor using the cursor cursor_name is synta%' 0hen a select statement is la"ed in an e% li"it "ursor, the develo er has more "om lete "ontrol over the statement,s e%e"ution' DECLARE CURSOR employee_cursor IS SELECT * FROM employee; END; BEGIN )here is really no su"h thing as determining 1the !est time1 to use an im li"it "ursor, !ut the develo er "an determine the !est time to use an e% li"it one' $very time a SQL o eration is re;uested, an im li"it "ursor is used' 0hen the develo er wants to erform some mani ulation on ea"h re"ord returned !y a select o eration, she will use an e% li"it "ursor' .ost serious ro"essing of data re"ords is done with e% li"it "ursorsK however, there are some o erations that work with im li"it "ursors as well' 7or e%am le, many of the "ursor attri!utes identified in an earlier se"tion of this "ha ter "an !e a lied to im li"it "ursors with useful results' )o refresh the dis"ussion, the list of "ursor attri!utes availa!le are ;notfound, ;found, ;rowcount, and ;iso+en' ;notfound identifies whether the fet"h e%e"uted on the "ursor did not return a row' )he return value is the o osite of that whi"h is returned !y ;found, whi"h identifies whether the fet"h e%e"uted on the "ursor returned a row' )hese two attri!utes return a )<*$ or 73LS$ value' ;rowcount identifies the num!er of rows that were ro"essed !y this "ursor and returns a numeri" value' ;iso+en identifies whether the "ursor referred to is o ened and ready for use, and returns a )<*$ or 73LS$ value'
*sing an im li"it "ursor in "on&un"tion with "ursor attri!utes may "onsist of e%e"uting some statement and then finding out if the results were su""essful' In the following e%am le, a user attem ts to u date an em loyee salary re"ord' If there are no em loyees in the $.PLO?$$ ta!le that "orres ond with the $.PID he would like to modify, then he wants the ro"ess to add an em loyee re"ord' DECLARE My_empid employee.empid%TYPE; My_salary employee.salary%TYPE; My_lastname employee.lastname%TYPE; BEGIN My_salary := 99000; My_empid := 59694; My_lastname := RIDDINGS; UPDATE employee SET salary = my_salary WHERE empid = my_empid; IF SQL%NOTFOUND THEN INSERT INTO EMPLOYEE (empid, lastname, salary) VALUES(my_empid, my_lastname, my_salary); END IF; END; )here are two im li"it "ursors in this e%am le' )he first is the u+date statement, and the se"ond is the insert statement' If the u+date statement rodu"es a "hange on no rows, the if s?l;notfound t-en statement will tra the error and for"e some o eration to ha en as a result of the "ondition' =ote that in the situation of an im li"it "ursor, there is no name to use to re"ede the "ursor attri!ute' In this situation, the develo er should s e"ify s?l ;notfound, or s?l;found, or use 1SQL1 followed !y the "ursor attri!ute' )hat 1SQL1 re resents the most re"ently4e%e"uted SQL statement rodu"ing an im li"it "ursor'
Self #$ercises
9' 0hat is an im li"it "ursor and what is the synta% for "reating one: 2' 0hat is an e% li"it "ursor: 0hy might a develo er use an e% li"it "ursor rather than an im li"it one: >' 0hat is the synta% for "reating an e% li"it "ursor:
statement' 3s stated, a "ursor is defined with the synta% cursor cursor_name is, whi"h is then followed !y a select statement' On"e defined, the "ursor allows the develo er to ste through the results of the ;uery in a num!er of different ways' DECLARE /* extract from a salary review program */ High_pctinc constant number := 1.20; Med_pctinc constant number := 1.10; Low_pctinc constant number := 1.05; My_salary number; My_empid number; CURSOR employee_crsr IS SELECT empid, salary FROM employee; BEGIN #onsider the definition of the $.PLO?$$@#<S<' )he two keywords used are cursor and is' =ote that the synta"ti" re;uirements of the select statement are fairly standard' )he de"laration of a "ursor does not a"tually rodu"e the "ursor, however' 3t this oint, the "ursor definition sim ly stands ready for a"tion' )he "ursor will not a"tually e%ist in memory until it is o ened and arsed !y the SQL e%e"ution me"hanism in Ora"le' Data will not o ulate the "ursor until the "ursor is e%e"uted' 3t the oint the SQL statement is e%e"uted, the "ode "an !egin fet"hing row values from it if the "ursor "ontains a select statement' 3ttention should turn now to the ro"ess of invoking the "ursor in memory' In this e%am le, the em loyees of the "om any will !e sele"ted into the "ursor for the ur ose of salary review' On"e sele"ted, the review will !e "ondu"ted as follows' $very em loyee of the "om any will o!tain a midlevel raise as defined !y the er"entage in"rease listed for mid_pctinc' )here are four e%"e tions: two em loyees will get a large raise as defined !y the er"entage in"rease listed for high_pctinc, while two other em loyees will get low erforman"e in"reases as defined !y low_pctinc' )he ro"ess flow will !e governed !y a "onditional statement, along with a loo ' DECLARE /* extract from a salary review program */ High_pctinc constant number := 1.20; Med_pctinc constant number := 1.10; Low_pctinc constant number := 1.05; My_salary number; My_empid number; CURSOR employee_crsr IS SELECT empid, salary FROM employee; BEGIN /* The following statement creates and executes the cursor in memory */ OPEN employee_crsr;
LOOP /* sets a loop that allows program to step through records of cursor */ FETCH employee_crsr INTO my_empid, my_salary; EXIT WHEN employee_crsr%NOTFOUND; /* stop looping when no records found */ IF my_empid = 59697 OR my_empid = 76095 THEN UPDATE employee SET salary = my_salary*high_pctinc WHERE empid = my_empid; ELSIF my_empid = 39294 OR my_Empid = 94329 THEN UPDATE employee SET salary = my_salary*low_pctinc WHERE empid = my_empid; ELSE UPDATE employee SET salary = my_salary*mid_pctinc WHERE empid = my_empid; END IF; END LOOP; END; )he main "ursor mani ulation o erations are the o+en, loo+2e$it w-en, fetc-, and cursor;notfound attri!ute statements' )he "ursor is first o ened with the o+en "ommand, whi"h im li"itly arses and e%e"utes the statement as well' )he loo is defined su"h that it should run until all re"ords from the "ursor are ro"essed' )he e$it "ondition uses the ;notfound attri!ute, re"eded !y the name of the e% li"it "ursor' Pay arti"ular attention to the fetc- statement' )his o eration "an only !e erformed on e% li"it "ursors that are select statements' 0hen a "all to fetc- is made, PL/SQL will o!tain the ne%t re"ord from the "ursor and o ulate the varia!les s e"ified with values o!tained from the "ursor' If the fetc- rodu"es no results, then the ;notfound attri!ute is set to )<*$' )he "ursor fetc- statement "an handle varia!les of two sorts' )he fetc- "ommand in the re"eding "ode !lo"k illustrates use of stand4alone varia!les for ea"h "olumn value stored in the "ursor' )he fetc- statement de ends on ositional s e"ifi"ation to o ulate the varia!les if this o tion is used' 3lternately, the use of a re"ord that "ontains the same attri!utes as those "olumns defined !y the "ursor is also handled !y fetc-' Positional s e"ifi"ation is used here as well, so it is re;uired for the order of the varia!les in the de"lared re"ord to mat"h the order of "olumns s e"ified in the "ursor de"laration' DECLARE /* extract from a salary review program */ High_pctinc constant number := 1.20; Med_pctinc constant number := 1.10; Low_pctinc constant number := 1.05; TYPE t_emp IS RECORD ( T_salary number, t_empid number); my_emprec t_emp; CURSOR employee_crsr IS
SELECT empid, salary FROM employee; BEGIN /* The following statement creates and executes the cursor in memory */ OPEN employee_crsr; LOOP /* sets a loop that allows program to step through records of cursor */ FETCH employee_crsr INTO my_emprec; EXIT WHEN employee_crsr%NOTFOUND; /* stop looping when no records found */ IF my_emprec.t_empid = 59697 OR my_emprec.t_empid = 76095 THEN UPDATE employee SET salary = my_emprec.t_salary*high_pctinc WHERE empid = my_emprec.t_empid; ELSIF my_emprec.t_empid = 39294 OR my_emprec.t_empid = 94329 THEN UPDATE employee SET salary = my_emprec.t_salary*low_pctinc WHERE empid = my_emprec.t_empid; ELSE UPDATE employee SET salary = my_emprec.t_salary*mid_pctinc WHERE empid = my_emprec.t_empid; END IF; END LOOP; END; )he additional "ode re;uired to su ort re"ords in this "ase may well !e worth it if there are many varia!les in the PL/SQL !lo"k' <e"ords give the develo er a more o!&e"t4oriented method for handling the varia!les re;uired for "ursor mani ulation'
Self #$ercises
9' 0hat must !e done in order to make a "ursor e%ist in memory: 2' 0hat ste must !e a""om lished to ut data in a "ursor: >' (ow is data retrieved from a "ursor:
review rogram on, !ased on the first letter of the last name' )his ro"ess "ould !e a""om lished with the use of "ursor arameters' )he develo er "ould allow the "ursor to a""e t a low and high limit, and then sele"t data from the ta!le for the "ursor using that range' DECLARE /* extract from a salary review program */ High_pctinc constant number := 1.20; Med_pctinc constant number := 1.10; Low_pctinc constant number := 1.05; TYPE t_emp IS RECORD ( T_salary number, t_empid number); my_emprec t_emp; CURSOR employee_crsr(low_end VARCHAR2, high_end VARCHAR2) IS SELECT empid, salary FROM employee WHERE substr(lastname,1,1) BETWEEN UPPER(low_end) AND UPPER(high_end); BEGIN 0ith the arameter assing defined, the develo er "an set u the "ursor with more "ontrol over the data that is ultimately ro"essed' 7or e%am le, if the develo er wants only to ro"ess salary in"reases for em loyees whose last names start with 3 through ., she "an develo the following "ode !lo"k: DECLARE /* extract from a salary review program */ High_pctinc constant number := 1.20; Med_pctinc constant number := 1.10; Low_pctinc constant number := 1.05; TYPE t_emp IS RECORD ( T_salary number, t_empid number); my_emprec t_emp; CURSOR employee_crsr(low_end VARCHAR2, high_end VARCHAR2) IS SELECT empid, salary FROM employee WHERE substr(lastname,1,1) BETWEEN UPPER(low_end) AND UPPER(high_end); BEGIN /* The following statement creates and executes the cursor in memory */ OPEN employee_crsr(A,M); LOOP /* sets a loop that allows program to step through records of cursor */ FETCH employee_crsr INTO my_emprec; EXIT WHEN employee_crsr%NOTFOUND; /* stop looping when no records found */ IF my_emprec.t_empid = 59697 OR my_emprec.t_empid = 76095
THEN UPDATE employee SET salary = my_emprec.t_salary*high_pctinc WHERE empid = my_emprec.t_empid; ELSIF my_emprec.t_empid = 39294 OR my_emprec.t_empid = 94329 THEN UPDATE employee SET salary = my_emprec.t_salary*low_pctinc WHERE empid = my_emprec.t_empid; ELSE UPDATE employee SET salary = my_emprec.t_salary*mid_pctinc WHERE empid = my_emprec.t_empid; END IF; END LOOP; END; =oti"e that this "ode !lo"k/the o+en statement that o ens, arses, and e%e"utes the "ursor/now "ontains two values assed into the "ursor "reation as arameters' )his arameter assing is re;uired for the "ursor to resolve into a set of data rows'
Self #$ercises
9' 0hat value does assing arameters to a "ursor rovide: 2' (ow "an a "ursor !e defined to a""e t arameters:
DECLARE /* extract from a salary review program */ High_pctinc constant number := 1.20; Med_pctinc constant number := 1.10; Low_pctinc constant number := 1.05; CURSOR employee_crsr(low_end VARCHAR2, high_end VARCHAR2) IS SELECT empid, salary FROM employee WHERE substr(lastname,1,1) BETWEEN UPPER(low_end) AND UPPER(high_end); BEGIN /* The following statement creates and executes the cursor in memory */ /* sets a loop that allows program to step through records of cursor */ FOR my_emprec in employee_crsr(A,M) LOOP IF my_emprec.empid = 59697 OR my_emprec.empid = 76095 THEN UPDATE employee SET salary = my_emprec.salary*high_pctinc WHERE empid = my_emprec.empid; ELSIF my_emprec.empid = 39294 OF my_emprec.empid = 94329 THEN UPDATE employee SET salary = my_emprec.salary*low_pctinc WHERE empid = my_emprec.empid; ELSE UPDATE employee SET salary = my_emprec.t_salary*mid_pctinc; WHERE empid = my_emprec.t_empid; END IF; END LOOP; END; )ake an e%tra moment to review the "ode !lo"k detailing a cursor for loo and "onfirm the following features the loo handles im li"itly' =ote that the !enefit of using a cursor for loo is that there are fewer re;uirements to set u the loo , resulting in fewer lines of "ode, fewer mistakes, and easier4to4 read rograms' )he features that cursor for loo s handle im li"itly are listed in the following: )he cursor for loo handles o ening, arsing, and e%e"uting the "ursor automati"ally' )he cursor for loo fet"hes row data im li"itly for ea"h iteration of the loo ' )he cursor for loo handles the cursor_name;notfound "ondition im li"itly and a ro riately terminates the loo when the attri!ute is )<*$ )he cursor for loo handles the definition of a re"ord to store the row values returned !y the "ursor fet"h automati"ally, resulting in a smaller de"laration se"tion'
Self #$ercises
9' 0hat ste s in "ursor loo handling does a cursor for loo handle im li"itly: 2' (ow is the e$it "ondition defined for a "ursor for loo :
#rror 3andling
In this se"tion, you will "over the following areas related to error handling: )he three !asi" ty es of e%"e tions Identifying "ommon e%"e tions #oding the e%"e tion handler )he handling of errors in PL/SQL is argua!ly the !est "ontri!ution PL/SQL makes to "ommer"ial rogramming' $rrors in PL/SQL need not !e tra ed and handled with if statements dire"tly within the rogram, as they are in other ro"edural languages like #' Instead, PL/SQL allows the develo er to raise exceptions when an error "ondition is identified and swit"h "ontrol to a s e"ial rogram area in the PL/SQL !lo"k, "alled the exception handler' )he "ode to handle an error does not "lutter the e%e"uta!le rogram logi" in PL/SQL, nor is the rogrammer re;uired to terminate rograms with return or e$it statements' )he e%"e tion handler is a "leaner way to handle errors'
Predefined #$ce+tions
In order to fa"ilitate error handling in PL/SQL, Ora"le has designed several 1!uilt4in1 or redefined e%"e tions' )hese e%"e tions are used to handle "ommon situations that may o""ur on the data!ase' 7or e%am le, there is a !uilt4in e%"e tion that "an !e used to dete"t when a statement returns no data, or when a statement e% e"ting one ie"e of data re"eives more than one ie"e of data' )here is no invoking a redefined e%"e tion/they are tested and raised automati"ally !y Ora"le' (owever, in order to have something done when the redefined error o""urs, there must !e something in the e%"e tion handler !oth to identify the error and to define what ha ens when the error o""urs' In the ne%t dis"ussion, 1#ommon $%"e tions,1 several of the most
"ommon e%"e tions will !e resented' All common exceptions in this discussion are predefined.
*IP: In order to tra+ a +redefined e$ce+tion) t-ere "ust !e an e$ce+tion -andler coded for it in t-e e$ce+tions section
User2defined #$ce+tions
In addition to redefined e%"e tions, there "an !e "reated a whole host of user4defined e%"e tions that handle situations that may arise in the "ode' 3 user4defined e%"e tion may not rodu"e an Ora"le errorK instead, user4defined e%"e tions may enfor"e !usiness rules in situations where an Ora"le error would not ne"essarily o""ur' *nlike redefined e%"e tions, whi"h are im li"itly raised when the asso"iated error "ondition arises, a user4defined e%"e tion must have e% li"it "ode in the PL/SQL !lo"k designed to raise it' )here is "ode re;uired for all three se"tions of a PL/SQL !lo"k if the develo er lans on using user4defined e%"e tions' )he re;uired "ode is detailed in the !ullets that follow: #$ce+tion declaration In the de"laration se"tion of the PL/SQL !lo"k, the e%"e tion name must !e de"lared' )his name will !e used to invoke, or raise, the e%"e tion in the e%e"ution se"tion if the "onditions of the e%"e tion o""ur' #$ce+tion testing In the e%e"ution se"tion of the PL/SQL !lo"k, there must !e "ode that e% li"itly tests for the user4defined error "ondition, whi"h raises the e%"e tion if the "onditions are met' #$ce+tion -andling In the e%"e tion handler se"tion of the PL/SQL !lo"k, there must !e a s e"ified w-en "lause that names the e%"e tion and the "ode that should !e e%e"uted if that e%"e tion is raised' 3lternately, there should !e a w-en ot-ers e%"e tion handler that a"ts as a "at"hall' )he following "ode !lo"k rovides an e%am le for "oding a user4defined e%"e tion' In the e%am le, assume that there is some ro!lem with an em loyee,s salary re"ord !eing =*LL' )he following "ode will sele"t a re"ord from the data!ase' If the re"ord sele"ted has a =*LL salary, the user4defined e%"e tion will identify the ro!lem with an out ut message' DECLARE My_empid number; My_emp_record employee%ROWTYPE; My_salary_null EXCEPTION; BEGIN My_empid := 59694; SELECT * FROM employee INTO my_emp_record WHERE empid = my_empid; IF my_emp_record.salary IS NULL THEN RAISE my_salary_null;
END IF; EXCEPTION WHEN NO_DATA_FOUND THEN DBMS_OUTPUT.PUT_LINE(No Data Found); WHEN my_salary_null THEN DBMS_OUTPUT.PUT_LINE(Salary column was null for employee); END; =ote that "ode must a ear for user4defined e%"e tions in all three areas of the PL/SQL !lo"k' 0ithout one of these "om onents, the e%"e tion will not o erate ro erly and the "ode will rodu"e errors'
the e$ce+tion/init ragma en&oy the same im li"it e%"e tion handling as redefined e%"e tions do'
#$ercises
9' 0hat is a redefined error: (ow are they invoked: 2' 0hat is a user4defined error: 0here must "ode !e defined in order to "reate a user4defined e%"e tion: >' 0hat "an !e used to asso"iate an Ora"le error with a user4defined error:
DBMS_OUTPUT.PUT_LINE(No Data Found); END; =oti"e that there is no "ode that e% li"itly tells PL/SQL to write the out ut message if no data is found in the arti"ular select statement in the e%e"uta!le ortion of the !lo"k' Instead, the e%"e tion is im li"itly raised when a redefined e%"e tion "ondition o""urs' )his layer of a!stra"tion is useful !e"ause the additional if statement re;uired for "he"king this "ondition manually is unne"essary'
Self #$ercises
9' 0hat redefined e%"e tion is used to identify the situation where no data is returned !y a select statement: 2' 0hat redefined e%"e tion is used to identify when the dataty e of the information returned is not the same dataty e as the de"lared varia!le:
*IP: once an e$ce+tion is raised) PL/SQL l flow control +asses to t-e e$ce+tion -andler Once t-e e$ce+tion is -andled) t-e PL/SQL !loc( will !e e$ited In ot-er words) once t-e e$ce+tion is raised) t-e e$ecution +ortion of t-e PL/SQL !loc( is over
Self #$ercises
9' 0hat are the "om onents of an e%"e tion handler: 2' 0hat is the ot-ers e%"e tion, and how is it used:
C-a+ter Su""ar&
PL/SQL rogramming is the to i" of this "ha ter' )he su!&e"t areas of PL/SQL that were dis"ussed in"lude overview of PL/SQL, modular "oding ra"ti"es, develo ing PL/SQL !lo"ks, intera"ting with Ora"le, "ontrolling ro"ess flow with "onditional statements and loo s, "ursors, and error handling' )he PL/SQL areas of O#P $%am 9 "om rise a!out 22 er"ent of the overall test' PL/SQL is the !est method availa!le for writing and managing stored ro"edures that work with Ora"le data' PL/SQL "ode "onsists of three su!!lo"ks/the de"laration se"tion, the e%e"uta!le se"tion, and the e%"e tion handler' In addition, PL/SQL "an !e used in four different rogramming "onstru"ts' )he ty es are ro"edures and fun"tions, a"kages, and triggers' Pro"edures and fun"tions are similar in that they !oth "ontain a series of instru"tions that PL/SQL will e%e"ute' (owever, the main differen"e is that a fun"tion will always return one and only one value' Pro"edures "an return more than that num!er as out ut arameters' Pa"kages are "olle"ted li!raries of PL/SQL ro"edures and fun"tions that have an interfa"e to tell others what ro"edures and fun"tions are availa!le as well as their arameters, and the !ody "ontains the a"tual "ode e%e"uted !y those ro"edures and fun"tions' )riggers are s e"ial PL/SQL !lo"ks that e%e"ute when a triggering event o""urs' $vents that fire triggers in"lude any SQL statement' )he de"laration se"tion allows for the de"laration of varia!les and "onstants' 3 varia!le "an have either a sim le or 1s"alar1 dataty e, su"h as =*.2$< or +3<#(3<2' 3lternately, a varia!le "an have a referential dataty e that uses referen"e to a ta!le "olumn to derive its dataty e' #onstants "an !e de"lared in the de"laration se"tion in the same way as varia!les, !ut with the addition of a constant keyword and with a value assigned' If a value is not assigned to a "onstant in the de"laration se"tion, an error will o""ur' In the e%e"uta!le se"tion, a varia!le "an have a value assigned to it at any oint using the assignment e% ression 5:<6' *sing PL/SQL allows the develo er to rodu"e "ode that integrates seamlessly with a""ess to the Ora"le data!ase' $%am les a eared in the "ha ter of using all SQL statements, in"luding data sele"tion, data "hange, and transa"tion ro"essing statements' )here are no s e"ial "hara"ters or keywords re;uired for 1em!edding1 SQL statements into PL/SQL, !e"ause SQL is an e%tension of PL/SQL' 3s su"h, there really is no em!edding at all' $very SQL statement
e%e"utes in a "ursor' 0hen a "ursor is not named, it is "alled an im li"it "ursor' PL/SQL allows the develo er to investigate "ertain return status features in "on&un"tion with the im li"it "ursors that run' )hese im li"it "ursor attri!utes in"lude ;notfound and ;found to identify if re"ords were found or not found !y the SQL statementK ;notfound, whi"h tells the develo er how many rows were ro"essed !y the statementK and ;iso+en, whi"h determines if the "ursor is o en and a"tive in the data!ase' #onditional ro"ess "ontrol is made ossi!le in PL/SQL with the use of if2t-en2 else statements' )he if statement uses a 2oolean logi" "om arison to evaluate whether to e%e"ute the series of statements after the t-en "lause' If the "om arison evaluates to )<*$, the t-en "lause is e%e"uted' If it evaluates to 73LS$, then the "ode in the else statement is e%e"uted' =ested if statements "an !e la"ed in the else "lause of an if statement, allowing for the develo ment of "ode !lo"ks that handle a num!er of different "ases or situations' Pro"ess flow "an !e "ontrolled in PL/SQL with the use of loo s as well' )here are several different ty es of loo s, from sim le loo+2e$it statements to loo+2 e$it w-en statements, w-ile loo+ statements, and for loo+ statements' 3 sim le loo+2e$it statement "onsists of the loo+ and end loo+ keywords en"losing the statements that will !e e%e"uted re eatedly, with a s e"ial if2 t-en statement designed to identify if an e$it "ondition has !een rea"hed' )he if2t-en statement "an !e eliminated !y using an e$it w-en statement to identify the e$it "ondition' )he entire ro"ess of identifying the e$it "ondition as art of the ste s e%e"uted in the loo "an !e eliminated with the use of a w-ile loo+ statement' )he e$it "ondition is identified in the w-ile "lause of the statement' 7inally, the for loo+ statement "an !e used in "ases where the develo er wants the "ode e%e"uting re eatedly for a s e"ified num!er of times' #ursor mani ulation is useful for situations where a "ertain o eration must !e erformed on ea"h row returned from a ;uery' 3 "ursor is sim ly an address in memory where a SQL statement e%e"utes' 3 "ursor "an !e e% li"itly named with the use of the cursor cursor_name is statement, followed !y the SQL statement that will "om rise the "ursor' )he cursor cursor_name is statement is used to define the "ursor in the de"laration se"tion only' On"e de"lared, the "ursor must !e o ened, arsed, and e%e"uted !efore its rows "an !e mani ulated' )his ro"ess is e%e"uted with the o+en statement' On"e the "ursor is de"lared and o ened, rows from the resultant dataset "an !e o!tained if the SQL statement defining the "ursor was a select using the fetcstatement' 2oth loose varia!les for ea"h "olumn,s value or a PL/SQL re"ord may !e used to store fet"hed values from a "ursor for mani ulation in the statement' $%e"uting ea"h of the o erations asso"iated with "ursor mani ulation "an !e sim lified in situations where the user will !e loo ing through the "ursor results using the cursor for loo statement' )he cursor for loo s handle many as e"ts of "ursor mani ulation e% li"itly' )hese ste s in"lude in"luding o ening, arsing, and e%e"uting the "ursor statement, fet"hing the value from
the statement, handling the e%it when data not found "ondition, and even im li"itly de"laring the a ro riate re"ord ty e for a varia!le identified !y the loo in whi"h to store the fet"hed values from the ;uery' )he e%"e tion handler is argua!ly the finest feature PL/SQL offers' In it, the develo er "an handle "ertain ty es of redefined e%"e tions without e% li"itly "oding error4handling routines' )he develo er "an also asso"iate user4defined e%"e tions with standard Ora"le errors, there!y eliminating the "oding of an error "he"k in the e%e"uta!le se"tion' )his ste re;uires defining the e%"e tion using the e$ce+tion/init ragma and "oding a routine that handles the error when it o""urs in the e%"e tion handler' 7or "om letely user4defined errors that do not raise Ora"le errors, the user "an de"lare an e%"e tion and "ode a rogrammati" "he"k in the e%e"ution se"tion of the PL/SQL !lo"k, followed !y some routine to e%e"ute when the error o""urs in the e%"e tion handler' 3 s e"ial redefined e%"e tion "alled ot-ers "an !e "oded into the e%"e tion handler as well to fun"tion as a "at"hall for any e%"e tion that o""urs that has no e%"e tion4handling ro"ess defined' On"e an e%"e tion is raised, "ontrol asses from the e%e"ution se"tion of the !lo"k to the e%"e tion handler' On"e the e%"e tion handler has "om leted, "ontrol is assed to the ro"ess that "alled the PL/SQL !lo"k'
*wo2%inute .rill
PL/SQL is a rogramming environment that is native to the Ora"le data!ase' It features seamless integration with other data!ase o!&e"ts in Ora"le and with SQL' )here are three arts to a PL/SQL rogram: the de"laration area, the e%e"ution area, and the e%"e tion handler' )here are four ty es of PL/SQL !lo"ks: ro"edures, fun"tions, a"kages, and triggers' Pro"edures allow the develo er to s e"ify more than one out ut arameter, while fun"tions only allow one return value' Other than that, the two PL/SQL !lo"ks are similar in fun"tion and usage' +aria!les are defined in the de"laration se"tion' +aria!les "an have a s"alar dataty e like =*.2$< or +3<#(3<2, or a referential dataty e defined !y use of a ta!le and/or "olumn referen"e followed !y ;t&+e or ;rowt&+e' #onstants are de"lared the same way as varia!les, e%"e t for the fa"t that the constant keyword is used to denote a "onstant and the "onstant must have a value assigned in the de"laration se"tion' +aria!les "an have values assigned anywhere in the PL/SQL !lo"k using the assignment o erator, whi"h looks like 5:<6' 3ny SQL statement is valid for use in PL/SQL' )his in"ludes all SQL statements su"h as select and delete, and transa"tion "ontrol statements su"h as set transaction or co""it' #onditional ro"essing is handled in PL/SQL with if2t-en2else statements'
If2t-en2else statements rely on 2oolean logi" to determine whi"h set of statements will e%e"ute' If the "ondition is )<*$, the statements in the t-en "lause will e%e"ute' If the "ondition is 73LS$, the statements in the else "lause will e%e"ute' )he if statements "an !e nested into one another,s else "lause' Several loo s also "ontrol the re etition of !lo"ks of PL/SQL statements' )he loo+2e$it statement is a sim le definition for a loo that marks the !eginning and end of the loo "ode' 3n if2t-en statement tests to see if "onditions are su"h that the loo should e%it' 3n e$it statement must !e s e"ified e% li"itly' )he if2t-en statement "an !e re la"ed with an e$it w-en statement, whi"h defines the e$it "ondition for the loo ' )he w-ile statement eliminates the need for an e$it statement !y defining the e$it "ondition in the w-ile loo+ statement' If the rogrammer wants her "ode to e%e"ute a s e"ified num!er of times, the for loo+ "an !e used' $very SQL statement e%e"utes in an im li"it "ursor' 3n e% li"it "ursor is a named "ursor "orres onding to a defined SQL statement' 3n e% li"it "ursor "an !e defined with the cursor cursor_name is statement' #ursors "an !e defined to a""e t in ut arameters that will !e used in the w-ere "lause to limit the data mani ulated !y the "ursor' On"e de"lared, a "ursor must !e o ened, arsed, and e%e"uted in order to have its data used' )his task is a""om lished with the o+en statement' In order to o!tain data from a "ursor, the rogrammer must fetc- the data into a varia!le' )his task is a""om lished with the fetc- statement' )he varia!le used in the fetc- "an either "onsist of several loose varia!les for storing single4"olumn values or a re"ord dataty e that stores all "olumn values in a re"ord' 3 s e"ial loo e%ists to sim lify use of "ursors, the cursor for loo ' )he cursor for loo handles the ste s normally done in the o+en statement, and im li"itly fet"hes data from the "ursor until the data not found "ondition o""urs' )his statement also handles the de"laration of the varia!le and asso"iated re"ord ty e, if any is re;uired' )he e%"e tion handler in PL/SQL handles all error handling' )here are user4defined e%"e tions, redefined e%"e tions, and ragma e%"e tions in PL/SQL' Only user4defined e%"e tions re;uire e% li"it "he"ks in the e%e"ution ortion of PL/SQL "ode to test to see if the e%"e tion "ondition has o""urred' 3 named e%"e tion "an have a w-en "lause defined in the e%"e tion handler that e%e"utes whenever that e%"e tion o""urs' )he ot-ers e%"e tion is a "at"hall e%"e tion designed to o erate if an e%"e tion o""urs that is not asso"iated with any other defined e%"e tion handler'
NOTES TAKEN FROM ORACLE certified professional DBA certification exam !ide" #ason S Co!c$man Oracle %ress &'((