Home
PL/SQL User's Guide and Reference, Release 8.0
Contents
1. Error Number Character Conversion Date Misc SQLCODE ABS ASCII CHARTOROWID ADD_MONTHS DECODE SOLERRM ACOS CHR CONVERT LAST_DAY DUMP ASIN CONCAT HEXTORAW ONTHS BETWEEN GREATES ATAN INITCAP NLS_CHARSET_ID EW_TIME GREATES ATAN2 INSTR NLS_CHARSET_NAME EXT_DAY EAS CEIL INSTRB RAWTOHEX ROUND LEAST_UB COs ENGTH ROWIDTOCHAR SYSDATE VL COSH ENGTHB TO_CHAR TRUNC UID EXP OWER O_DATE USER FLOOR PAD O_ LABEL USERENV LN LTRI O_MULTI_BYTE VSIZE LOG NLS_INITCAP O_NUMBER MOD NLS_LOWER O_SINGLE BYTE POWER NLS_UPPER ROUND NLSSORT SIGN REPLACE SI RPAD SINH RTRIM SORT SOUNDEX TAl SUBSTR TANH SUBSTRB TRUNC TRANSLATE UPPER 2 52 PL SQL User s Guide and Reference 3 Control Structures One ship drives east and another drives west With the selfsame winds that blow Tis the set of the sails and not the gales Which tells us the way to go Ella Wheeler Wilcox This chapter shows you how to structure the flow of control through a PL SQL program You learn how statements are connected by simple but powerful control structures that have a single entry and exit point Collectively these structures can handle any situation And their proper use leads naturally to a well structured program Major Topics Overview Conditional Control IF Statements Iterative Control LOOP and EXIT Statements Sequential Control GOTO
2. WHEN ZERO_DIVIDE THEN Though PL SQL does not support continuable exceptions you can still handle an exception for a statement then continue with the next statement Simply place the statement in its own sub block with its own exception handlers If an error occurs in the sub block a local handler can catch the exception When the sub block terminates the enclosing block continues to execute at the point where the sub block ends Consider the following example DECLARE pe_ratio NUMBER 3 1 BEGI DELETE FROM stats WHERE symbol XYZ BEGIN sub block begins SELECT price NVL earnings 0 INTO pe_ratio FROM stocks WHERE symbol XYZ EXCEPTIO WHEN ZERO_DIVIDE THEN pe_ ratio 0 END sub block ends INSERT INTO stats symbol ratio VALUES XYZ pe ratio EXCEPTION 6 20 PL SQL User s Guide and Reference Useful Techniques In this example if the SELECT INTO statement raises a ZERO_DIVIDE exception the local handler catches it and sets pe_ratio to zero Execution of the handler is complete so the sub block terminates and execution continues with the INSERT statement Retrying a Transaction After an exception is raised rather than abandon your tra
3. Interaction with Oracle 5 41 Using Cursor Attributes END IF END LOOP CLOSE bin_cur INSERT INTO temp VALUES NULL bins_looked_at lt bins looked at COMMIT END Implicit Cursor Attributes Implicit cursor attributes return information about the execution of an INSERT UPDATE DELETE or SELECT INTO statement The values of the cursor attributes always refer to the most recently executed SQL statement Before Oracle opens the SQL cursor the implicit cursor attributes yield NULL FOUND Until a SOL data manipulation statement is executed SFOUND yields N ULL Thereafter SF OUND yields TRUE if an INSERT UPDATE or DELETE statement affected one or more rows or a SELECT INTO statement returned one or more rows Otherwise FOUND yields FALSE In the following example you use sFOUND to insert a row if a delete succeeds DELETE FROM emp WHERE empno my_empno IF SOLSFOUND THEN delete succeeded INSERT INTO new_emp VALUES my_empno my_ename ISOPEN Oracle closes the SQL cursor automatically after executing its associated SQL statement As a result ISOPEN always yields FALSE NOTFOUND SNOTFOUND is the logical opposite of FOUND SNOTFOUND yields TRU INSERT UPDATE or DELETE statement affected no
4. NOWAIT This optional keyword tells Oracle not to wait if the table has been locked by another user Control is immediately returned to your program so it can do other work before trying again to acquire the lock If you omit the keyword NOWAIT Oracle waits until the table is available the wait has no set limit Table locks are released when your transaction issues a commit or rollback A table lock never keeps other users from querying a table and a query never acquires a table lock 11 94 PL SQL User s Guide and Reference LOCK TABLE Statement Example Related Topics If your program includes SQL locking statements make sure the Oracle users requesting locks have the privileges needed to obtain the locks Your DBA can lock any table Other users can lock tables they own or tables for which they have a such as SELECT INS privilege ERT UPDATE or DELETE The following statement locks the accts table in shared mode LOCK TABII E accts IN SHARE MODE r COMMIT Statement ROLLBACK Statement UPDATE Statement Language Elements 11 95 LOOP Statements LOOP Statements Syntax LOOP statements execute a sequence of statements multiple times The loop encloses the sequence of statements that is to be repeated PL SQL provides the following types of loop statements a basic loop WHILE loop FOR loo
5. x INTEGER y INTEGER RETURN INTEGER AS find greatest common divisor of x and y x MOD y 0 THEN ans y ans gcd y x ELSE ans gcd y x MOD y CREATE TYPE Rational AS OBJECT num INTEGER den INTEGER MEMBER PROCEDURE normalize CREATE TYPE BODY Rational AS MEMBER PROCEDURE g INTEGER BEGIN normalize IS the next two statements ar quivalent g gcd SELF g gcd num num SELF den den num num g den den g END normalize ND E Object Types 9 9 Components of an Object Type Overloading Like packaged subprograms methods of the same kind functions or procedures can be overloaded That is you can use the same name for different methods if their formal parameters differ in number order or datatype family When you call one of the methods PL SQL finds it by comparing the list of actual parameters with each list of formal parameters You cannot overload two methods if their formal parameters differ only in parameter mode Also you cannot overload two member functions that differ only in return type For more information see Overloading on page 7 18 Map and Order Methods The values of a scalar datatype such as CHAR or REAL have a predefined order which allows them to be compared But
6. Interactive Session Connected to Oracle as user SCOTT Enter department number 20 Employee Job Salary SMITH CLERK 800 00 JONES MANAGER 2975 00 SCOTT ANALYST 3000 00 ADAMS CLERK 1100 00 FORD ANALYST 3000 00 B 26 PL SQL User s Guide and Reference C CHAR versus VARCHAR2 Semantics This appendix explains the semantic differences between the CHAR and VARCHAR2 base types These subtle but important differences come into play when you assign compare insert update select or fetch character values Major Topics Assigning Character Values Comparing Character Values Inserting Character Values Selecting Character Values CHAR versus VARCHAR2 Semantics C 1 Assigning Character Values Assigning Character Values When you assign a character value to a CHAR variable if the value is shorter than the declared length of the variable PL SQL blank pads the value to the declared length So information about trailing blanks is lost For example given the following declaration the value of name includes six trailing blanks not just one name CHAR 10 CHEN note trailing blank If the character value is longer than the declared length of the CHAR variable PL SQL aborts the assignment and raises the predefined exception VALUE_ERROR PL SQL neither truncates the value nor tries to trim trailing blanks For example given the declaration
7. 7 26 PL SQL User s Guide and Reference Recursion When a positive integer n is passed to odd or even the functions call each other by turns At each call n is decremented Ultimately n becomes zero and the final call returns TRUE or FALSE For instance passing the number 4 to odd results in this sequence of calls odd 4 even 3 odd 2 even 1 odd 0 returns FALSE On the other hand passing the number 4 to even results in the following sequence of calls even 4 odd 3 even 2 odd 1 even 0 returns TRUE Recursion versus Iteration Unlike iteration recursion is not essential to PL SQL programming Any problem that can be solved using recursion can be solved using iteration Also the iterative version of a subprogram is usually easier to design than the recursive version However the recursive version is usually simpler smaller and therefore easier to debug Compare the following functions which compute the nth Fibonacci number recursive version FUNCTION fib n POSITIVE RETURN INTEGER IS BEGIN IF n 1 OR n 2 THEN RETURN 1 ELSE RETURN fib n 1 fib n 2 END IF END fib iterative version FUNCTION fib n POSITIVE posl INTEGER 1 pos2 INTEGER 0 cum INTEGER Y ETURN INTEGER IS Subprograms 7 27 Recursion
8. In general do not depend on the interaction between TRIM and DELETE It is better to treat nested tables like fixed size arrays and use only DELETE or to treat them like stacks and use only TRIM and EXTEND PL SQL does not keep placeholders for trimmed elements So you cannot replace a trimmed element simply by assigning it a new value Collections and Records 4 25 Using Collection Methods Using DELETE This procedure has three forms DELETE remove DELETE n removes the nth element from a nes s all elements from a collection ted table If nis null DELETE n does nothing DELETE m n removes all elements in the range m n from a nested table If mis larger than n or if mor nis null DEL ETE m n does nothing Some examples follow BEGIN courses DELETE 2 deletes element 2 courses DELETE 7 7 deletes element 7 courses DE E 6 3 does nothing courses DELETE 3 6 deletes elements 3 through 6 projects DELETE deletes all elements END Varrays are dense so you cannot delete their individual elements If an element to be deleted does not exist DELETE simply skips it no exception is raised PL SQL keeps placeholders for deleted elements So you can replace a deleted element simply by assigning it a new va
9. PROCEDURE award_bonuses members IN Staff IS BEGI IF members COUNT gt 10 THEN apply method END IF END END personnel For varray parameters the value of LIMIT is always derived from the parameter type definition regardless of the parameter mode Avoiding Collection Exceptions In most cases if you reference a nonexistent collection element PL SQL raises a predefined exception Consider the following example DECLARE YPE NumList IS TABLE OF BER nums NumList atomically null BEGIN Assume that execution continues despite the raised exceptions nums 1 1 raises COLLECTION_IS_NULL 1 nums NumList 1 2 initialize table nums NULL 3 raises VALUE_ERROR 2 nums 0 3 raises SUBSCRIPT_OUTSIDE_ LIMIT 3 nums 3 3 raises SUBSCRIPT_BEYOND_COUNT 4 nums DELETE 1 delete element 1 IF nums 1 1 THEN raises NO DATA FOUND 5 Collections and Records 4 27 What Is a Record In the first case the nested table is atomically null In the second case the subscript is null In the third case the subscript is outside the legal range In the fourth case the subscript exceeds the number of elements in the table In the fifth case the subscript designates a deleted element The following list shows when a given
10. You can also pass a cursor variable to PL SQL by calling a stored procedure that declares a cursor variable as one of its formal parameters To centralize data retrieval you can group type compatible queries in a packaged procedure as the following example shows CREATE PACKAGE emp_data AS TYPE EmpCurTyp IS REF CURSOR RETURN emp ROWTYP PROCEDURE open_emp_cv emp_cv IN OUT EmpCurTyp choice IN BER E E Z D emp data CREATE PACKAGE BODY emp data AS PROCEDURE open_emp_cv emp_cv IN OUT EmpCurTyp choice IN NUMBER IS IF choice 1 THEN OPEN emp_cv FOR SELECT FROM emp WHERE comm IS NOT NULL choice 2 THE OPEN emp_cv FOR SELECT FROM emp WHERE sal gt 2500 choice 3 THE OPEN emp_cv FOR SELECT FROM emp WHERE deptno 20 zj n Ky H y n Ky nj Language Elements 11 43 Cursor Variables END IF END open_emp_cv END emp_data Alternatively you can use a stand alone procedure to open the cursor variable Simply define the REF CURSOR type in a separate package then reference that type in the stand alone procedure For instance if you create the following bodiless package you can create stand alone procedures that reference the types it defines CREATE PACKAGE cv_typ
11. E G se RN emp ROWTYP RN emp ROWTYP A Fl se E G PROCEDURE open emp cv emp cv IN OUT EmpCurTyp tmp_cv IN OUT TmpCurTyp IS BEGIN emp_cv tmp cv causes wrong type error END However if one or both cursor variables are weakly typed they need not have the same datatype If you try to fetch from close or apply cursor attributes to a cursor variable that does not point to a query work area PL SQL raises the predefined exception INVALID_CURSOR You can make a cursor variable or parameter point to a query work area in two ways a OPEN the cursor variable FOR the query a Assign to the cursor variable the value of an already OPENed host cursor variable or PL SQL cursor variable The following example shows how these ways interact DECLARE YPE EmpCurTyp IS REF CURSOR RETURN emp ROWTYPE emp_cvl EmpCurTyp emp_cv2 EmpCurTyp emp_rec emp SROWTYPE se se BEGIN The following assignment is useless because emp_cvl does not point to a query work area yet emp_cv2 emp cvl useless Make emp_cvl point to a query work area OPEN emp_cvl FOR SELECT FROM emp Use emp_cvl to fetch first row from emp table FETCH emp_cvl INTO emp_rec 5 34 PL SQL User s Guide and Reference Using Cursor Variables
12. raise _salary emp_number amount EXCEPTION WHEN null_salary THEN INSERT INTO emp audit VALUES emp_number END END E EC This technique allows the calling application to handle error conditions in specific exception handlers Redeclaring Predefined Exceptions Remember PL SQL declares predefined exceptions globally in package STANDARD so you need not declare them yourself Redeclaring predefined exceptions is error prone because your local declaration overrides the global declaration EXCEPTION WHEN invalid number OR STANDARD INVALID_NUMBER THEN handle the error WHEN OTHERS THEN 6 10 PL SQL User s Guide and Reference How Exceptions Are Raised How Exceptions Are Raised Internal exceptions are raised implicitly by the runtime system as are user defined exceptions that you have associated with an Oracle error number using EXCEPTION_INIT However other user defined exceptions must be raised explicitly by RAISE statements Using the RAISE Statement PL SQL blocks and subprograms should raise an exception only when an error makes it undesirable or impossible to finish processing You can place RAISE statements for a given exception anywhere within the scope of that exception In the following example you alert your PL SQL block to a user defined exception named out_of_stock
13. CREATE PROCEDURE fire_employee emp_id BER AS BEGI DELETE FROM emp WHERE empno emp_id END When creating subprograms you can use the keyword AS instead of IS in the specification for readability For more information about creating and using stored subprograms see Oracle8 Application Developer s Guide 7 10 PL SQL User s Guide and Reference Actual versus Formal Parameters Actual versus Formal Parameters Subprograms pass information using parameters The variables or expressions referenced in the parameter list of a subprogram call are actual parameters For example the following procedure call lists two actual parameters named emp_num and amount raise_salary emp_num amount The next procedure call shows that expressions can be used as actual parameters raise_salary emp num merit cola The variables declared in a subprogram specification and referenced in the subprogram body are formal parameters For example the following procedure declares two formal parameters named emp_idand increase PROCEDURE raise_salary emp_id INTEGER increase REAL IS current_salary REAL BEGI SELECT sal INTO current_salary FROM emp WHERE empno emp_id UPDATE emp SET sal sal increase WHERE empno emp_id END raise_salary A good programming practice is to use different names for actual and formal parameters When you
14. my_sal UMBER 7 2 BEGIN OPEN cl FOR i IN 1 5 LOOP FETCH cl INTO my_ename my_empno my_sal EXIT WHEN cl NOTFOUND in case the number requested is more than the total number of employees B 12 PL SQL User s Guide and Reference Sample 3 Scoping INSERT INTO temp VALUES my_sal my_empno my_ename COMMIT END LOOP CLOSE cl END Output Table SQL gt SELECT FROM temp ORDER BY coll DESC COL1 COL2 ESSAGE 5000 7839 KING 3000 7902 FORD 3000 7788 SCOTT 2975 7566 JONES 2850 7698 BLAKE Sample 3 Scoping The following example illustrates block structure and scope rules An outer block declares two variables named x and counter and loops four times Inside this loop is a sub block that also declares a variable named x The values inserted into the temp table show that the two x s are indeed different Input Table Not applicable PL SQL Block available online in file sample3 DECLARE x BER 0 counter BER 0 BEGIN FOR i IN 1 4 LOOP x x 1000 counter counter 1 INSERT INTO temp VALUES x counter outer loop start an inner block DECLARE x BER 0 this is a local version of x Sample Programs B 13 Sample 3 Scoping
15. In the following example you update the salary of an employee and at the same time retrieve the employee s name and new salary into PL SQL variables PROCEDURE update_salary emp_id NUMBER IS name VARCHAR2 15 new_sal BER BEGI UPDATE emp SET sal sal 1 1 WHERE empno emp_id RETURNING ename sal INTO name new_sal END Use Serially Reusable Packages To help you manage the use of memory PL SQL provides the pragma SERIALLY_REUSABLE which lets you mark some packages as serially reusable You can so mark a package if its state is needed only for the duration of one call to the server for example an OCI call to the server a PL SQL client to server RPC or a server to server RPC The global memory for such packages is pooled in the System Global Area SGA not allocated to individual users in the User Global Area UGA That way the package work area can be reused When the call to the server ends the memory is returned to the pool Each time the package is reused its public variables are initialized to their default values or to NULL Interaction with Oracle 5 55 Processing Transactions The maximum number of work areas needed for a package is the number of concurrent users of that package which is usually much less than the number of logged on users The increased use of SGA memory is more than offset by the decreased
16. OU RAU Each item in column passengers is a varray that will store the passenger list for a given flight Now you can populate database table flights as follows BEGIN INSERT INTO flights VALUES 109 80 DFW 6 35PM PassengerList Passenger 1 Passenger 1 Passenger 1 INSERT INTO flights VALUES 114 12B PassengerList Passenger 1 Passenger 1 Passenger 1 INSERT INTO flights VALUES 27 34 JEK 7 05AM PassengerList Passenger 27 Passenger 27 Passenger 27 4 36 PL SQL User s Guide and Reference SFO 9 45AM HOU 7 40PM Paula Trusdale 13C Louis Jemenez 22F Joseph Braun 11B LAX 12 10PM Earl Benton 23A Alma Breckenridge 10E Mary Rizutto 11C TA 9 55AM Raymond Kiley 34D Beth Steinberg 3A Jean Lafevre 19C Dd Dd Manipulating Records In the example below you fetch rows from database table flights into record flight_info That way you can treat all the information about a flight including its passenger list as a logical unit DECLARE YPE FlightRec IS RECORD flight_no NUMBER 3 gate 5 departure 15 arrival CHAR 15 passengers PassengerList flight_info FlightRec CURSOR cl IS SELECT FROM flights BEGIN OPEN cl LOOP FETCH cl INTO flight_info EXIT WHEN c1SNOTFOUND FOR i IN 1 flight_info passengers LAST LOOP IF flight_info passengers i
17. BEGIN FOR i IN 1 4 LOOP x x 1 this increments the local x counter counter 1 INSERT INTO temp VALUES x counter inner loop END LOOP END END LOOP COMMIT END Output Table SQL gt SELECT FROM temp ORDER BY col2 COL1 COL2 ESSAGE 1000 1 OUTER loop i 2 inner loop 2 3 inner loop 3 4 inner loop 4 5 inner loop 2000 6 OUTER loop 1 7 inner loop 2 8 inner loop 3 9 inner loop 4 10 inner loop 3000 11 OUTER loop 1 12 inner loop 2 13 inner loop 3 14 inner loop 4 15 inner loop 4000 16 OUTER loop ds 17 inner loop 2 18 inner loop 3 19 inner loop 4 20 inner loop 20 records selected B 14 PL SQL User s Guide and Reference Sample 4 Batch Transaction Processing Sample 4 Batch Transaction Processing Input Tables In the next example the accounts table is modified according to instructions stored in the action table Each row in the action table contains an account number an action to be taken I U or D for insert update or delete an amount by which to update the account and a time tag used to sequence the transactions On an insert if the account already exists an update is done instead On an update if the account does not exist it is created by an insert On a delete if the row does not exist no action is taken SQL gt SELECT FROM accounts ORDER BY account_id ACCOUNT_ID BAL 1 1000 2 2000 3 1500 4 6500 5 500 SQL gt SELECT FROM acti
18. BEGIN IF n 1 OR n 2 THEN RETURN 1 ELSE cum posl pos2 FOR i IN 3 n LOOP pos2 posl posl cum cum posl pos2 END LOOP RETURN cum END IF END fib The recursive version of fib is more elegant than the iterative version However the iterative version is more efficient it runs faster and uses less storage That is because each recursive call requires additional time and memory As the number of recursive calls gets larger so does the difference in efficiency Still if you expect the number of recursive calls to be small you might choose the recursive version for its readability 7 28 PL SQL User s Guide and Reference 8 Packages Good as it is to inherit a library it is better to collect one Augustine Birrell This chapter shows you how to bundle related PL SQL programming constructs into a package The packaged constructs might include a collection of procedures or a pool of type definitions and variable declarations For example a Human Resources package might contain hiring and firing procedures Once written your general purpose package is compiled then stored in an Oracle database where like a library unit its contents can be shared by many applications Major Topics What Is a Package Advantages of Packages The Package Specification The Package Body Some Examples Private versus Public Items Overloading Package STANDARD Product speci
19. BEGIN SELECT p home_address street INTO my_street FROM persons p WHERE p last_name Lucas Inserting Objects You use the INSERT statement to add objects to an object table In the following example you insert a Person object into object table persons BEGIN INSERT INTO persons VALUES Jenifer Lapidus 9 36 PL SQL User s Guide and Reference Manipulating Objects Alternatively you can use the constructor for object type Person to insert an object into object table persons BEGIN INSERT INTO persons VALUES Person Albert Brooker In the next example you use the RETURNING clause to store Person refs in local variables Notice how the clause mimics a SELECT statement You can also use the RETURNING clause in UPDATE and DELETE statements DECLARE pl_ref REF Person p2_ref REF Person BEGIN INSERT INTO persons p VALUES Person Paul Chang URNING REF p INTO pl_ref INTO persons p VALUES Person Ana Thorne RNING REF p INTO p2_ref Y dG To insert objects into an object table you can use a subquery that returns objects of the same type An example follows BEGIN INSERT INTO persons2 SELECT VALUE p FROM persons p WHERE p last_name LIKE SJones The rows
20. se END cv_types stand alone procedure CREATE PROCEDURE open emp cv emp cv IN OUT cv_types EmpCurTyp AS OPEN emp_cv FOR SELECT FROM emp END open _ emp cv anonymous PL SQL block in Pro C program EXEC SQL EXECUTE BEGIN OPEN cv FOR SELECT FROM dept Interaction with Oracle 5 35 Using Cursor Variables open_emp_cv cv raises ROWTYP E MISMATCH because emp and dept tables have different rowtypes END END EXEC Guarding Against Aliasing Like all pointers cursor variables introduce the possibility of aliasing Consider the example below After the assignment emp_cv2 is an alias of emp_cv1 because both point to the same query work area So both can alter its state That is why the first fetch from emp_cv2 fetches the third row not the first and why the second fetch from emp_cv2 fails after you close emp_cv1 PROCEDURE get_emp data emp cv1 IN OUT EmpCurTyp emp_cv2 IN OUT EmpCurTyp IS emp_rec emp ROWTYPE BEGIN OPEN emp_cvl FOR SELECT FROM emp emp_cv2 emp_cvl FETCH emp_cvl INTO emp_rec fetches first row FETCH emp_cvl INTO emp_rec fetches second row FETCH emp_cv2 INTO emp_rec fetches third row CLOSE emp_cvl FETCH emp_cv2 INTO emp_rec raises INVALID_CURSOR END get_emp_data Alia
21. An implicit savepoint is marked before executing an INSERT UPDATE or DELETE statement If the statement fails a rollback to the implicit savepoint is done Normally just the failed SQL statement is rolled back not the whole transaction However if the statement raises an unhandled exception the host environment determines what is rolled back COMMIT Statement ROLLBACK Statement 11 138 PL SQL User s Guide and Reference SELECT INTO Statement SELECT INTO Statement Syntax The SELECT INTO statement retrieves data from one or more database tables then assigns the selected values to variables or fields For a full description of the SELECT statement see Oracle8 SQL Reference select_into_statement variable_name record_name LOS table_reference rest_of_statement select_item function_name NULL RK gt column_name Language Elements 11 139 SELECT INTO Statement Keyword and Parameter Description select_item This is a value returned by the SELECT statement then assigned to the corresponding variable or field in the INTO clause variable_name variable_name This identifies a list of previously declared scalar variables into which select_itemvalues are fetched For each select_item value returned by the query there must be a corresponding type compatible variabl
22. SELECT bal INTO acct_bal FRO acc UNCTION balance acct_id INTEGER RETURN REAL IS acct_bal REAL EGI ts WHERE acctno acct_id Collections Packages Procedures Records 11 82 PL SQL User s Guide and Reference GOTO Statement GOTO Statement Syntax The GOTO statement branches unconditionally to a statement label or block label The label must be unique within its scope and must precede an executable statement or a PL SQL block The GOTO statement transfers control to the labelled statement or block For more information see GOTO Statement on page 3 15 label_declaration lt lt label_name gt goto_statement Baro a Keyword and Parameter Description Usage Notes label_name This is an undeclared identifier that labels an executable statement or a PL SQL block You use a GOTO statement to transfer control to the statement or block following lt lt label_name gt gt Some possible destinations of a GOTO statement are illegal In particular a GOTO statement cannot branch into an IF statement LOOP statement or sub block For example the following GOTO statement is illegal BEGIN GOTO update_row illegal branch into IF statement IF valid THEN lt lt update_row gt gt UPDATE emp SET END IF Language Elements 11 83 GOTO Statement Examples From the current block a GOTO statement can branch to another place in the
23. Rows in the result set are not retrieved when the OPEN statement is executed Rather the FETCH statement retrieves the rows Passing Parameters You use the OPEN statement to pass parameters to a cursor Unless you want to accept default values each formal parameter in the cursor declaration must have a corresponding actual parameter in the OPEN statement For example given the cursor declaration DECLARE mp nam mp enameSTYPE salary emp sal TYPE CURSOR cl name VARCHAR2 salary NUMBER IS SELECT any of the following statements opens the cursor OPEN cl emp_name 3000 OPEN cl ATTLEY 1500 OPEN cl emp_name salary In the last example when the identifier salary is used in the cursor declaration it refers to the formal parameter But when it is used in the OPEN statement it refers to the PL SQL variable To avoid confusion use unique identifiers Formal parameters declared with a default value need not have a corresponding actual parameter They can simply assume their default values when the OPEN statement is executed Interaction with Oracle 5 11 Managing Cursors You can associate the actual parameters in an OPEN statement with the formal parameters in a cursor declaration using positional or named notation See Positional and Named Notation on page 7 12 The datatypes of each actual parameter and its corresponding for
24. You can declare collections as the formal parameters of functions and procedures That way you can pass collections to stored subprograms and from one subprogram to another In the following example you declare a nested table as the formal parameter of a packaged procedure CREATE PACKAGE personnel AS TYPE Staff IS TABLE OF Employee PROCEDURE award_bonuses members IN Staff Also you can specify a collection type in the RETURN clause of a function specification as the following example shows DECLARE YPE SalesForce IS VARRAY 25 OF Salesperson FUNCTION top_performers n INTEGER RETURN SalesForce IS 4 8 PL SQL User s Guide and Reference Initializing and Referencing Collections Collections follow the usual scoping and instantiation rules In a block or subprogram collections are instantiated when you enter the block or subprogram and cease to exist when you exit In a package collections are instantiated when you first reference the package and cease to exist when you end the database session Initializing and Referencing Collections Until you initialize it a collection is atomically null that is the collection itself is null not its elements To initialize a collection you use a constructor which is a system defined function with the same name as the collection type This function constructs collections from the element
25. T The OCI attribute names for these properties are OCI_ATTR_CHARSET_ID and OCI_ATTR_CHARSET_FORM For more information about using NLS data with the OCI see Oracle Call Interface Programmer s Guide Repositioning Parameters Remember each formal parameter must have a corresponding parameter in the PARAMETERS clause Their positions can differ because PL SQL associates them by name not by position However the PARAMETERS clause and the C prototype for the external procedure must have the same number of parameters in the same order Passing Parameters by Reference In C you can pass IN scalar parameters by value the value of the parameter is passed or by reference a pointer to the value is passed When an external procedure expects a pointer to a scalar specify the BY REF phrase to pass the parameter by reference An example follows CREATE PROCEDURE find_root x IN REAL AS EXTERNAL LIBRARY c_utils External Procedures 10 15 Passing Parameters to an External Procedure NAME c_find_root PARAMETERS Z BY BEBE weet In this case the C prototype would be void c_find_root float x rather than the default void c_find_root float x Using the WITH CONTEXT Clause By including the WITH CONTEXT clause you can give an external procedure access to information about parameters exceptio
26. Y amp E RETURN 10 D CREAT E PACKAGE pkgl AS UNCTION funcl RETURN NU BER RAGMA RESTRICT_REFERENC E PACKAGE BODY pkgl AS S t1 10 no row expression S 10 no row expression E FUNCTION funcl RETURN NUMBER AS GIN BER IS B EGIN R CTION funcl RETURN SELEC funcl FROM dual SELEC funcl FROM dual ETURN 20 E ES funcl WNDS RNDS WNPS RNPS Name Resolution E 11 Calling Subprograms and Methods SELECT pkgl funcl FROM dual SELECT pkgl funcl FROM dual x N ER x funcl x funcl SELECT funcl INTO x FROM dual SELECT funcl INTO x FROM dual S S T ECT pkgl funcl INTO x FROM dual ELECT pkgl funcl INTO x FROM dual Z Example 2 CREATE OR REPLACE TYPE typel AS OBJECT a MEMBER FUNCTION f RETURN number PRAGMA RESTRICT_REFERENCES WNDS RNDS WNPS RNPS E H CREATE TYPE BODY typel AS MEMBER FUNCTION f RETURN number IS BEGIN RETURN 1 END ea Oo ari CREATE TABLE tabl coll typel INSERT INTO tabl VALUES typel 10 SELECT x coll f
27. Constants and Variables Syntax You can declare constants and variables in the declarative part of any PL SQL block subprogram or package Declarations allocate storage space for a value specify its datatype and name the storage location so that you can reference it Declarations can also assign an initial value and impose the NOT NULL constraint For more information see Declarations on page 2 28 variable_declaration gt expression datatype cursor_variable_name gt column_name db_table_name object_name TYPE t I REF object_type_name record_name TYPE record_type_name 1 ref_cursor_type_name scalar_datatype_name variable_name TYPE 4 lt U m X Language Elements 11 29 Constants and Variables constant_declaration Keyword and Parameter Description constant_name This identifies a program constant For naming conventions see Identifiers on page 2 4 CONSTANT This keyword denotes the declaration of a constant You must initialize a constant in its declaration Once initialized the value of a constant cannot be changed record_name field_name This identifies a field in a user defined or SROWTYPE record previously declared within the current scope scalar_type_name This identifies a predefined scalar datatype such as BOOLEAN NUMBER or VARCHAR2
28. DECLARE my_ename VARCHAR2 10 Or use a block label to qualify references as in lt lt main gt gt DECLARE ename VARCHAR2 10 KING BEGIN DELETE FROM emp WHERE ename main ename 2 36 PL SQL User s Guide and Reference Scope and Visibility The next example shows that you can use a subprogram name to qualify references to local variables and formal parameters FUNCTION bonus deptno IN NUMBER RETURN REAL IS job CHAR 10 BEGI SELECT WHERE deptno bonus deptno AND job bonus job For a full discussion of name resolution see Appendix E Scope and Visibility References to an identifier are resolved according to its scope and visibility The scope of an identifier is that region of a program unit block subprogram or package from which you can reference the identifier An identifier is visible only in the regions from which you can reference the identifier using an unqualified name Figure 2 2 shows the scope and visibility of a variable named x which is declared in an enclosing block then redeclared in a sub block Identifiers declared in a PL SQL block are considered local to that block and global to all its sub blocks If a global identifier is redeclared in a sub block both identifiers remain in scope Within the sub block however only the local identifier is visible because you must use
29. EGER Defining Object Types Object Type Rational A rational number is a number expressible as the quotient of two integers a numerator and a denominator Like most languages PL SQL does not have a rational number type or predefined operations on rational numbers Let us remedy that omission by defining object type Rational First we write the object type specification as follows CREATE TYPE Rational AS OBJECT num INTEGER den INTEGER AP MEMBER FUNCTION convert RETURN REAL EMBER PROCEDURE normalize EMBER FUNCTION reciprocal RETURN Rational EMBER FUNCTION plus x Rational RETURN Rational BER FUNCTION less x Rational RETURN Rational EMBER FUNCTION times x Rational RETURN Rational EMBER FUNCTION divby x Rational RETURN Rational PRAGMA RESTRICT REFERENCES DEFAULT RNDS WNDS RNPS WNPS y PL SQL does not allow the overloading of operators That is why we define methods named plus less the word minus is reserved times and divby instead of overloading the infix operators and Next we create the following stand alone stored function which will be called by method normalize CREATE FUNCTION gcd x INTEGER y INTEGER RETURN INTEGER AS find greatest common divisor of x and
30. END IF lt lt end_loop gt gt illegal END LOOP not an executable statement END To debug the last example simply add the NULL statement as follows DECLARE done BOOLEAN BEGIN FOR i IN 1 50 LOOP IF done THEN GOTO end_loop END IF lt lt end_loop gt gt ULL an executable statement END LOOP END As the following example shows a GOTO statement can branch to an enclosing block from the current block DECLARE my_ename CHAR 10 BEGIN lt lt get_name gt gt SELECT ename INTO my_ename FROM emp WHERE BEGIN GOTO get_name branch to enclosing block END END 3 16 PL SQL User s Guide and Reference Sequential Control GOTO and NULL Statements The GOTO statement branches to the first enclosing block in which the referenced label appears Restrictions Some possible destinations of a GOTO statement are illegal Specifically a GOTO statement cannot branch into an IF statement LOOP statement or sub block For example the following GOTO statement is illegal BEGIN GOTO update_row illegal branch into IF statement IF valid THEN lt lt update_row gt gt UPDATE emp SET END IF END Also a GOTO statement cannot branch from one IF statement clause to another as the following example shows BEGIN IF valid THEN GOTO update_row
31. SB1 SB2 SB4 UB1 UB2 UB4 SIZE_T External Procedures 10 9 Passing Parameters to an External Procedure Table 10 1 Parameter Datatype Mappings Cont PL SQL Type Supported External Types Default External Type NATURAL UNSIGNED CHAR UNSIGNED INT NATURALI UNSIGNED SHORT POSITIVE UNSIGNED INT POSITIVEN UNSIGNED LONG SIGNTYPE SB1 SB2 SB4 UB1 UB2 UB4 IZE_T FLOAT FLOAT FLOAT REAL DOUBLE PRECISION DOUBLE DOUBLE CHAR STRING STRING CHARACTER LONG NCHAR NVARCHAR2 ROWID VARCHAR VARCHAR2 LONG RAW RAW RAW RAW BFILE OCILOBLOCATOR OCILOBLOCATOR BLOB CLOB NCLOB In some cases you can use the PARAMETERS clause to override the default datatype mappings For example you can re map the PL SQL datatype BOOLEAN from external datatype INT to external datatype CHAR 10 10 PL SQL User s Guide and Reference Passing Parameters to an External Procedure To avoid errors when declaring C prototype parameters refer to Table 10 2 which shows the C datatype to specify for a given external datatype and PL SQL parameter mode For example if the external datatype of an OUT parameter is STRING specify the datatype char in your C prototype Table 10 2 External Datatype Mappings External Datatype CHAR UNSIGNED CHAR SHORT UNSIGNED SHORT 2 n na Q f ED INT
32. AL IS ECT bal INTO acct_bal FROM accts WHE RE acctno acct_id Language Elements 11 133 ROLLBACK Statement ROLLBACK Statement The ROLLBACK statement is the inverse of the COMMIT statement It undoes some or all database changes made during the current transaction For more information see Processing Transactions on page 5 44 Syntax rollback_statement SAVEPOINT go E Keyword and Parameter Description ROLLBACK When a parameterless ROLLBACK statement is executed all database changes made during the current transaction are undone WORK This keyword is optional and has no effect except to improve readability ROLLBACK TO This statement undoes all database changes and releases all locks acquired since the savepoint identified by savepoint_name was marked SAVEPOINT This keyword is optional and has no effect except to improve readability savepoint_name This is an undeclared identifier which marks the current point in the processing of a transaction For naming conventions see Identifiers on page 2 4 11 134 PL SQL User s Guide and Reference ROLLBACK Statement Usage Notes Related Topics All savepoints marked after the savepoint to which you roll back are erased However the savepoint to which you roll back is not eras ed For example if you mark savepoints A B C and D in that order then roll back to savepoint B only savepoints
33. function _name field_name illegal no parameter list Instead declare a local user defined record to which you can assign the function result then reference its fields directly In the following example you define a RECORD type named DeptRecTyp declare a record named dept_rec then select a row of values into the record DECLARE YPE DeptRecTyp IS RECORD deptno BER 2 dname CHAR 14 loc CHAR 13 dept_rec DeptRecTyp BEGI SELECT deptno dname loc INTO dept_rec FROM dept WHERE deptno 20 Assignment Statement Collections Functions Procedures Language Elements 11 131 RETURN Statement RETURN Statement The RETURN statement immediately completes the execution of a subprogram and returns control to the caller Execution then resumes with the statement following the subprogram call In a function the RETURN statement also sets the function identifier to the result value For more information see RETURN Statement on page 7 7 Syntax return_statement expression Keyword and Parameter Description expression This is an arbitrarily complex combination of variables constants literals operators and function calls The simplest expression consists of a single variable When the RETURN statement is executed the value of expression is assigned to the function identifier Usage Notes Do not confus
34. Concatenation Operator The concatenation operator ignores null operands For example the expression apple NULL NULL sauce applesauce Functions If a null argument is passed to a built in function a null is returned except in the following cases The function DECODE compares its first argument to one or more search expressions which are paired with result expressions Any search or result expression can be null If a search is successful the corresponding result is returned In the following example if the column rating is null DECODE returns the value 1000 SELECT DECODE rating NULL 1000 C 2000 B 4000 A 5000 INTO credit_limit FROM accts WHERE acctno my_acctno The function NVL returns the value of its second argument if its first argument is null In the example below if hire_date is null NVL returns the value of SYSDATE Otherwise NVL returns the value of hire_date start_date NVL hire date SYSDATE r 2 50 PL SQL User s Guide and Reference Built In Functions The function REPLACE returns the value of its first argument if its second argument is null whether the optional third argument is present or not For instance after the assignment new_string REPLACE old_string NULL my_string the values of old_stringand new_stringare the same If its third argu
35. PROCEDURE fire employee emp id NUMBER E 4 D emp_actions CREATE PACKAGE BODY emp_actions AS package body PROCEDURE hire employee empno NUMBER ename CHAR IS BEGI INSERT INTO emp VALUES empno ename ND hire employee ROCEDURE fire employee emp_id NUMBER IS EGIN DELETE FROM emp WHERE empno emp_id ID fire employee END emp_actions E Y tu E Overview 1 13 Main Features Only the declarations in the package specification are visible and accessible to applications Implementation details in the package body are hidden and inaccessible Packages can be compiled and stored in an Oracle database where their contents can be shared by many applications When you call a packaged subprogram for the first time the whole package is loaded into memory So subsequent calls to related subprograms in the package require no disk I O Thus packages can enhance productivity and improve performance Data Abstraction Data abstraction lets you extract the essential properties of data while ignoring unnecessary details Once you design a data structure you can forget the details and focus on designing algorithms that manipulate the data structure Collections The collection types TABLE and VARRAY allow you to declare nested tables and variable size arrays varrays for short A collec
36. a The Listener must start agent extproc on the machine that runs the Oracle server Starting extproc on a different machine is not supported a The maximum number of parameters that you can pass to a C external procedure is 128 However if you pass float or double parameters by value the maximum is less than 128 How much less depends on the number of such parameters and your operating system To get a rough estimate count each float or double passed by value as two parameters Examples Assume that C routine c_gcd which finds the greatest common divisor of two numbers is stored in DLL utils d11 and that you have EX alias library c_ut ils The C prototype for c_gcd follows int c_gcd int x_ val int y val ECUTE privileges on In the following example you write a PL SQL stand alone function named gcd that registers the C routine c_gcdas an external function CREATE FUNCTION gcd find greatest common divisor of x and y x BINARY_INTEGER y BINARY INTEGER RETURN BINARY_INTEGER AS EXTERNAL LIBRARY c_utils AME C_gcd quotes preserve lower cas ANGUAGE C In the example below you call PL SQL function gcd from an anonymous block PL SQL passes the two integer parameters to external function c_gcd which returns their greatest common divisor DECLARE g INTEGER a INTEGER b INTEGER
37. positional notation credit_acct amount gt amt acct_no gt acct named notation credit_acct acct_no gt acct amount gt amt named notation credit_acct acct amount gt amt mixed notation Positional Notation The first procedure call uses positional notation The PL SQL compiler associates the first actual parameter acct with the first formal parameter acct_no And the compiler associates the second actual parameter amt with the second formal parameter amount Named Notation The second procedure call uses named notation An arrow gt serves as the association operator which associates the formal parameter to the left of the arrow with the actual parameter to the right of the arrow The third procedure call also uses named notation and shows that you can list the parameter pairs in any order Therefore you need not know the order in which the formal parameters are listed Mixed Notation The fourth procedure call shows that you can mix positional and named notation In this case the first parameter uses positional notation and the second parameter uses named notation Positional notation must precede named notation The reverse is not allowed For example the following procedure call is illegal credit_acct acct_no gt acct amt illegal 7 12 PL SQL User s Guide and Reference Parameter Modes Parameter Modes IN Mode OUT Mode You use parameter modes to defin
38. 2 n nan Q ED LONG SIZE_T SB1 UB1 SB2 UB2 SB4 UB4 FLOAT DOUBLE STRING RAW OCILOBLOCATOR IN RETURN char unsigned char short unsigned short int unsigned int long unsigned long size t float double char unsigned char OCILobLocator IN by Ref RETURN by Ref char unsigned char short unsigned short int unsigned int long unsigned long size t sbl ubl sb4 ub4 float double char unsigned char OCILobLocator IN OUT OUT char unsigned char short unsigned short ont unsigned int long unsigned long size t sbis ubl sb4 ub4 float double char unsigned char OCILobLocator External Procedures 10 11 Passing Parameters to an External Procedure Using the PARAMETERS Clause Generally the PL SQL subprogram that registers an external procedure declares a list of formal parameters as the following example shows CREATE FUNCTION interp find the value of y at x degrees using Lagrange interpolation x IN FLOAT y IN FLOAT RETURN FLOAT AS EXTERNAL AME interp LIBRARY mathlib ANGUAGE C Each formal parameter declaration specifies a name parameter mode and PL SQL datatype which maps to the default external datatype That might be all the information the external procedure
39. Blocks x INTEGER BEGIN IF x outer x THEN refers to global x END IF END END outer DECLARE This keyword signals the start of the declarative part of a PL SQL block which contains local declarations Items declared locally exist only within the current block and all its sub blocks and are not visible to enclosing blocks The declarative part of a PL SQL block is optional It is terminated implicitly by the keyword BEGIN which introduces the executable part of the block PL SQL does not allow forward references So you must declare an item before referencing it in other statements including other declarative statements Also you must declare subprograms at the end of a declarative section after all other program items collection_declaration This identifies a nested table index by table or varray previously declared within the current scope For the syntax of collection_declaration see Collections on page 11 21 constant_declaration This construct declares a constant For the syntax of constant_declaration see Constants and Variables on page 11 29 cursor_declaration This construct declares an explicit cursor For the syntax of cursor_declaration see Cursors on page 11 45 cursor_variable_ declaration This construct declares a cursor variable For the syntax of cursor_variable_declaration see Cursor Variables on page 11 38 11 10 PL SQL User s
40. Blocks on page 11 7 item_declaration This declares a program object For the syntax of item_declaration see Blocks on page 11 7 function_declaration This construct declares a function For the syntax of function_declaration see Functions on page 11 79 procedure _declaration This construct declares a procedure For the syntax of procedure_declaration see Procedures on page 11 121 exception_handler This construct associates an exception with a sequence of statements which is executed when that exception is raised For the syntax of exception_handler see Exceptions on page 11 54 A function is called as part of an expression For example the function sal_ok might be called as follows promotable sal_ok new_sal new_title AND rating gt 3 Every function must contain at least one RETURN statement Otherwise PL SQL raises the predefined exception PROGRAM_ERROR at run time Language Elements 11 81 Functions To be callable from SQL expressions a stored function must obey certain rules meant to control side effects For packaged functions you must use the pragma RI Application Developer s Guide ESTRICT_REFERENCES to enforce the rules For more information see Oracle8 You can write the function specification and body as a unit Or you can separate the function specification from its body That way you can hide implementation details by placi
41. DECLARE out_of_stock EXCEPTION number_on_hand NUMBER 4 BEGIN IF number_on_hand lt 1 THEN RAISE out_of_stock END IF EXCEPTION WHEN out_of_stock THEN handle the error END You can also raise a predefined exception explicitly That way an exception handler written for the predefined exception can process other errors as the following example shows DECLARE acct_type INTEGER BEGIN IF acct_type NOT IN 1 2 3 THEN RAISE INVALID_NUMBER raise predefined exception END IF Error Handling 6 11 How Exceptions Propagate EXCEPTION WHEN INVALID _NUMBER THEN ROLLBACK END How Exceptions Propagate When an exception is raised if PL SQL cannot find a handler for it in the current block or subprogram the exception propagates That is the exception reproduces itself in successive enclosing blocks until a handler is found or there are no more blocks to search In the latter case PL SQL returns an unhandled exception error to the host environment However exceptions cannot propagate across remote procedure calls RPCs Therefore a PL SQL block cannot catch an exception raised by a remote subprogram For a workaround see Using raise_application_error on page 6 9 Figure 6 1 Figure 6 2 and Figure 6 3 illustrate the basic propagation rules Figure 6 1 Propaga
42. DECLARE start_time CHAR 5 finish time CHAR 5 elapsed_time NUMBER 5 BEGI Get system time as seconds past midnight SELEC O_ CHAR SYSDATE SSSSS INTO start_time FROM sys dual do something Get system time again SELEC O_CHAR SYSDATE SSSSS INTO finish time FROM sys dual Comput lapsed time in seconds e mE lapsed time finish time start_time SERT INTO results VALUES elapsed time Before assigning a selected column value to a variable PL SQL will if necessary convert the value from the datatype of the source column to the datatype of the variable This happens for example when you select a DATE column value into a VARCHAR2 variable Likewise before assigning the value of a variable to a database column PL SQL will if necessary convert the value from the datatype of the variable to the datatype of the target column If PL SQL cannot determine which implicit conversion is needed you get a compilation error In such cases you must use a datatype conversion function Table 2 1 shows which implicit conversions PL SQL can do 2 26 PL SQL User s Guide and Reference Datatype Conversion Table 2 1 Implicit Conversions BIN_INT CHAR DATE LONG NUMBER PLS_INT RAW ROWID VARCHAR2 BIN_INT x x x x x CHAR Xx x X X x x x X DATE X X X LONG X X x NUMBER X X X x x PLS _INT x x x x x
43. NAME This clause specifies the external procedure to be called If you enclose the procedure name in double quotes it becomes case sensitive If you omit this clause the procedure name defaults to the upper case name of the PL SQL subprogram LANGUAGE This clause specifies the third generation language in which the external procedure was written Currently the only language name allowed is C If you omit this clause the language name defaults to C CALLING STANDARD This clause specifies the Windows NT calling standard C or Pascal under which the external procedure was compiled Under the Pascal Calling Standard arguments are reversed on the stack and the called function must pop the stack If you omit this clause the calling standard defaults to C WITH CONTEXT This clause specifies that a context pointer will be passed to the external procedure The context data structure is opaque to the external procedure but is available to service routines called by the external procedure Language Elements 11 71 External Procedures By including the WITH CONTEXT clause you can give an external procedure access to information about parameters exceptions memory allocation and the user environment PARAMETERS This clause specifies the positions and datatypes of parameters passed to the external procedure It can also specify parameter properties such as current length and maximum length and the preferred parameter passin
44. You can pass a cursor variable to PL SQL by calling a stored procedure that declares a cursor variable as one of its formal parameters However remote subprograms on another server cannot accept the values of cursor variables Therefore you cannot use a remote procedure call RPC to open a cursor variable When you declare a cursor variable as the formal parameter of a subprogram that opens the cursor variable you must specify the IN OUT mode That way the subprogram can pass an open cursor back to the caller In the following Pro C example you pass a host cursor variable and selector to a PL SQL block which opens the cursor variable for the chosen query EXEC SQL BEGIN DECLARE SECTION Declare host cursor variable SOL CURSOR generic_cv int choice EXEC SOL END DECLARE SECTION 11 114 PL SQL User s Guide and Reference OPEN FOR Statement Initialize host cursor variable EXEC SQL ALLOCATE generic_cv Pass host cursor variable and selector to PL SQL block EXEC SQL EXECUTE BEGIN IF choice 1 THEN OPEN generic_cv FOR SELECT FROM emp ELSIF choice 2 THEN OPEN generic_cv FOR SELECT FROM dept ELSIF choice 3 THEN OPEN generic_cv FOR SELECT FROM salgrade END IF END END E EC To centralize data retrieval you can group type
45. ccc cece cece cecscseseseececscsssesescecscssseseececscsssnsneseeeees 5 61 6 Error Handling vi DV CLV LE Wie oss frees Saas aa e Sa eda tate ghee ve Sateen dea Uses as Paks ea as Ed E 6 2 Advantages of Exceptions cunado 6 3 Predefined Exceptions ii A E 6 4 User Defined Exceptions cies 6 6 Declaring Exceptions urarii tes linealidad cido E de 6 6 SCOPE RULES vitoria lesan dhe lian aa 6 7 Using EXCEPTION INIT vesical a aR E ea R KORSO ERT REAA 6 8 Using raise application errot snose ienai i e a AEDE EE 6 9 Redeclaring Predefined Exceptions oococococononononcnncnrnnenncnonnnrnnnacannnnnnnnnrornnnnnnnanannnnnnararanannn raras 6 10 How Exceptions Are Raised oooonnnnicicnnnnnnnnnncncncnnncncncncncononocncncn cono nonnrn rn cono nann nono a N aE ei 6 11 Using the RAISE Statement cccccccsssesssssssseescecesesescsnenessseseseeesesescecesesssesnaneneseseseeseseseeeeees 6 11 How Exceptions Propagate ccccccccccesssessesesescnseeceesenessssesesessnsesescssesescscsesecesessesesaeassesseeeesesnees 6 12 Reraising an Excepuon icsi 0 csi nics evana chaebol nein ein ice 6 14 Handling Raised Excepti nS isi sisendiga sikins ninkai eisian roin tiasar kaai 6 15 Exceptions Raised in Declarations sicoiir trein sesasbareier ieri ateses iet asi 6 16 Exceptions Raised in Handlers c cccsccccesessssesesescesesescsssnsneseseseeesesescecesescsssnansnesesesnenensseeeeees 6 17 Branching to or from an Exception HandleT oooconeconinoncononene
46. clrec comm 0 25 INSERT INTO bonuses VALUES clrec empno bonus END LOOP COMMIT END Cursors EXIT Statement FETCH Statement OPEN Statement ROWTYPE Attribute Language Elements 11 101 NULL Statement NULL Statement Syntax Usage Notes Examples The NULL statement explicitly specifies inaction it does nothing other than pass control to the next statement In a construct allowing alternative actions the NULL statement serves as a placeholder For more information see NULL Statement on page 3 19 null_statement HO The NULL statement improves readability by making the meaning and action of conditional statements clear It tells readers that the associated alternative has not been overlooked but that indeed no action is necessary Each clause in an IF statement must contain at least one executable statement The NULL statement meets this requirement So you can use the NULL statement in clauses that correspond to circumstances in which no action is taken The NULL statement and Boolean non value NULL are unrelated In the following example the NULL statement emphasizes that only salespeople receive commissions IF job title SALESPERSON THEN compute_commission emp_id ELSE ULL END IF In the next example the NULL statement shows that no action is taken for unnamed exceptions EXCEPTION WHEN O
47. illegal branch into ELSE clause ELSE lt lt update_row gt gt UPDATE emp SET END IF END The next example shows that a GOTO statement cannot branch from an enclosing block into a sub block BEGIN IF status OBSOLETE THEN GOTO delete part illegal branch into sub block E iS H a Control Structures 3 17 Sequential Control GOTO and NULL Statements lt lt delete_part gt gt DELETE FROM parts WHERE END END Also a GOTO statement cannot branch out of a subprogram as the following example shows DECLARE PROCEDURE compute_bonus emp_id NUMBER IS BEGI GOTO update_row illegal branch out of subprogram D BEGIN E lt lt update_row gt gt UPDATE emp SET END Finally a GOTO statement cannot branch from an exception handler into the current block For example the following GOTO statement is illegal DECLARE pe_ratio REAL BEGIN SELECT price NVL earnings 0 INTO pe_ratio FROM lt lt insert_row gt gt INSERT INTO stats VALUES pe_ratio EXCEPTION WHEN ZERO_DIVIDE THEN pe_ratio 0 GOTO insert_row illegal branch into current block END However a GOTO statement can branch from an exception handler into an enclosin
48. int OCIExtProcRaiseExcp OCIExtProcContext with_context size_t error_number The parameters with_context and error_number are the context pointer and Oracle error number The return values OCIEXTPROC_SUCCESS and OCIEXTPROC_ERROR indicate success or failure In SQL Plus suppose you register external procedure divide as follows SQL gt CREATE PROCEDURE divide 2 dividend IN BINARY_ INTEGER 3 divisor IN BINARY_INTEGER 4 result OUT FLOAT 5 AS EXTERNAL 6 NAME divide 7 LIBRARY mathlib 8 WITH CONTEXT 9 PARAMETERS 10 CONTEXT 11 dividend int 12 divisor int 13 result float When called divide finds the quotient of two numbers As the following example shows if the divisor is zero divide uses OCIExtProcRaiseExcp to raise the predefined exception ZERO_DIVIDE void divide ctx dividend divisor result OCIExtProcContext ctx int dividend int divisor float result Check for zero divisor if divisor int 0 Raise exception ZERO_DIVIDE which is Oracle error 1476 if OCIExtProcRaiseExcp ctx int 1476 OCIEXTPROC_SUCCESS External Procedures 10 19 Using Service Routines return else Incorrect parameters were passed assert 0 result float dividend float divisor OCIExtProcRaiseExcpWithMsg This service
49. package body PROCEDURE hire employee emp_id INTGER name VARCHAR2 IS BEGI INSERT INTO emp VALUES empno ename END hire employee Subprograms 7 9 Declaring Subprograms PROCEDURE fire_employee emp_id INTEGER IS BEGI DELETE FROM emp WHERE empno emp_id END fire employee PROCEDURE raise _salary emp_id INTEGER increase REAL IS salary REAL BEGIN SELECT sal INTO salary FROM emp WHERE empno emp_id END raise _salary END emp_actions You can define subprograms in a package body without declaring their specifications in the package specification However such subprograms can be called only from inside the package For more information about packages see Chapter 8 Stored Subprograms Generally tools such as Oracle Forms that incorporate the PL SQL engine can store subprograms locally for later strictly local execution However to become available for general use by all tools subprograms must be stored in an Oracle database To create subprograms and store them permanently in an Oracle database you use the CREATE PROCEDURE and CREATE FUNCTION statements which you can execute interactively from SQL Plus or Enterprise Manager For example you might create the procedure fire_employee as follows
50. strcpy pwd arr tiger pwd len strlen pwd arr Sample Programs B 19 Sample 5 Embedded PL SQL printf n n printf Trying to connect Embedded P L SQL Debit Transaction Demo n n YG E WHEN EC SQL EC SOL ER SQI ECT EXI CONN ERROR GOTO errprint uid ID ENTIFIED BY pwd printf connected n for Gr Loop infinitely printf n Debit which account number 1 to end gets buf acct atoi buf if acct 1 Need to disconnect from Oracle and exit loop if account is 1 EC SQL COMMIT R EL EAS exit 0 printf gets buf debit atof buf r What is the debit amount EC SQL EXI ECUT ECLAF insufficient_funds old_bal min_bal E H WH ER new_bal IF new_bal gt min_bal THI UPDATE HER RT VALUI tus accounts E B 20 PL SQL User s Guide and Reference ECT bal INTO old bal F E account_id acc If the account doesn exception will be au old bal debi S EXC EPTION BER BER 500 ROM accounts r t exist the NO DATA FOUND omatically raised Ly ah ET bal new_bal E account_id acct
51. Balance is now 700 00 Debit which account number 1 to What is the debit amount 500 Status Transaction completed Balance is now 1500 00 Debit which account number 1 to What is the debit amount 100 Status Transaction completed Balance is now 1400 00 Debit which account number 1 to What is the debit amount 100 Status Account not found end 1 end 2 end 2 end 99 Debit which account number 1 to nd 1 SQL gt SELECT FROM accounts ORDER BY account_id ACCOUNT_ID BAL 700 1400 1500 6500 500 OF WN EF SQL gt SELECT FROM journal ORDER BY date_tag ACCOUNT_ID ACTION AMOUNT DATE_TAG 1 Debit 300 28 NOV 88 2 Debit 500 28 NOV 88 2 Debit 100 28 NOV 88 PL SQL User s Guide and Reference Sample 6 Calling a Stored Procedure Sample 6 Calling a Stored Procedure This Pro C program connects to Oracle prompts the user for a department number then calls procedure get_employees which is stored in package personnel The procedure declares three index by tables as OUT formal parameters then fetches a batch of employee data into the index by tables The matching actual parameters are host arrays When the procedure finishes it automatically assigns all row values in the index by tables to corresponding elements in the host arrays The program calls the procedure repeatedly displaying each batch of employee data until no more dat
52. END LOOP outer Language Elements 11 97 LOOP Statements basic_loop_statement The simplest form of LOOP statement is the basic or infinite loop which encloses a sequence of statements between the keywords LOOP and END LOOP With each iteration of the loop the sequence of statements is executed then control resumes at the top of the loop If further processing is undesirable or impossible you can use the EXIT GOTO or RAISE statement to complete the loop A raised exception will also complete the loop while_loop_statement The WHILE LOOP statement associates a Boolean expression with a sequence of statements enclosed by the keywords LOOP and END LOOP Before each iteration of the loop the expression is evaluated If the expression yields TRUE the sequence of statements is executed then control resumes at the top of the loop If the expression yields FALSE or NULL the loop is bypassed and control passes to the next statement boolean_expression This is an expression that yields the Boolean value TRUE FALSE or NULL It is associated with a sequence of statements which is executed only if the expression yields TRUE For the syntax of boolean_expression see Expressions on page 11 59 for_loop_statement Whereas the number of iterations through a WHILE loop is unknown until the loop completes the number of iterations through a FOR loop is known before the loop is entered Numer
53. FROM dept SUBTYPE DeptFile IS cl ROWTYPE based on cursor rowtype However you cannot specify a constraint on the base type For example the following definitions are illegal DECLARE SUBTYPE Accumulator IS NUMBER 7 2 illegal must be BER SUBTYPE Delimiter IS CHAR 1 illegal must be CHAR SUBTYPE Word IS VARCHAR2 15 illegal Although you cannot define constrained subtypes directly you can use a simple workaround to define size constrained subtypes indirectly Simply declare a size constrained variable then use TYPE to provide its datatype as shown in the following example DECLARE temp VARCHAR2 15 SUBTYPE Word IS temp TYPE maximum size of Word is 15 Likewise if you define a subtype using TYPE to provide the datatype of a database column the subtype adopts the size constraint if any of the column However the subtype does not adopt other kinds of constraints such as NOT NULL Fundamentals 2 23 User Defined Subtypes Using Subtypes Once you define a subtype you can declare items of that type In the example below you declare two variables of type Counter Notice how the subtype name indicates the intended use of the variables DECLARE SUBTYPE Counter IS NATURAL rows Counter mployees Counter The following example shows that you can constrain a user defined s
54. INTO journal ES acct Debit SYSDATI debit Transaction completed insufficient_funds Sample 5 Embedded PL SQL EXCEPTION WHEN NO_DATA FOUND THEN status Account not found new_bal 1 WHEN insufficient_funds THEN status Insufficient funds new_bal old bal WHEN OTHERS THEN ROLLBACK status Error SOLERRM SOLCODE new_bal 1 END END E EC eE End the PL SQL block status arr status len 0 null terminate the string e printf Ann Status s n status arr if new_bal gt 0 printf Balance is now 2f n new_bal End of loop errprint EXEC SOL WHENEVER SOLERROR CONTINUE printf Anin gt gt gt gt gt Error during execution In printf siIn sqlca sglerrm sqlerrmc EXEC SOL ROLLBACK RELEASE exit 1 Interactive Session Embedded PL SQL Debit Transaction Demo Trying to connect connected Debit which account number 1 to end 1 What is the debit amount 300 Status Transaction completed Balance is now 700 00 Sample Programs B 21 Sample 5 Embedded PL SQL kx kk kx Output Tables B 22 Debit which account number 1 to What is the debit amount 900 Status Insufficient funds
55. Outsource Payroll 12350 Evaluate Merger Proposal 2750 Audit Accounts Payable 1425 925300 Repair Leak in Roof 2850 Install New Door Locks 1700 Wash Front Windows 975 Repair Faulty Wiring 1350 Winterize Cooling System 1125 Issue New Employee Badges 13500 Find Missing Computer Chips 2750 Upgrade Alarm System 3350 VALUES 60 Security 750400 ProjectList Project 1 Project 2 Project 3 Project 4 Inspect Emergency Exits 1900 In the following example you update the list of projects assigned to the Security Department DECLARE new_projects ProjectList ProjectList Project 1 Issue New Employee Badges 13500 Project 2 Develop New Patrol Plan 1250 Project 3 Inspect Emergency Exits 1900 Collections and Records 4 17 Manipulating Collections Project 4 Upgrade Alarm System 3350 Project 5 Analyze Local Crime Statistics 825 BEGIN UPDATE department SET projects new_projects WHERE dept_id 60 In the next example you retrieve all the projects for the Accounting Department into a local varray DECLARE my_projects ProjectList BEGI SELECT projects INTO my_projects FROM department WHERE dept_id 30 In the final example you delete the Accounting Department and its project list from table department B
56. Rows in the result set are not retrieved when the OPEN statement is executed The FETCH statement retrieves the rows With a FOR UPDATE cursor the rows are locked when the cursor is opened If formal parameters are declared actual parameters must be passed to the cursor The formal parameters of a cursor must be IN parameters Therefore they cannot return values to actual parameters The values of actual parameters are used when the cursor is opened The datatypes of the formal and actual parameters must be compatible The query can also reference PL SQL variables declared within its scope Unless you want to accept default values each formal parameter in the cursor declaration must have a corresponding actual parameter in the OPEN statement Formal parameters declared with a default value need not have a corresponding actual parameter They can simply assume their default values when the OPEN statement is executed You can associate the actual parameters in an OPEN statement with the formal parameters in a cursor declaration using positional or named notation For more information see Positional and Named Notation on page 7 12 If a cursor is currently open you cannot use its name in a cursor FOR loop Given the cursor declaration CURSOR parts_cur IS SELECT part_num part_price FROM parts the following statement opens the cursor OPEN parts_cur Given the cursor declaration C
57. The TYPE and SROWTYPE attributes further integrate PL SQL with the data dictionary For example you can use the TYPE attribute to declare variables basing the declarations on the definitions of database columns If a definition changes the variable declaration changes accordingly at run time This provides data independence reduces maintenance costs and allows programs to adapt as the database changes to meet new business needs Overview 1 23 Advantages of PL SQL 1 24 PL SQL User s Guide and Reference 2 Fundamentals There are six essentials in painting The first is called spirit the second rhythm the third thought the fourth scenery the fifth the brush and the last is the ink Ching Hao The previous chapter provided an overview of PL SQL This chapter focuses on the small scale aspects of the language Like every other programming language PL SQL has a character set reserved words punctuation datatypes rigid syntax and fixed rules of usage and statement formation You use these basic elements of PL SQL to represent real world objects and operations Major Topics Character Set Lexical Units Datatypes User Defined Subtypes Datatype Conversion Declarations Naming Conventions Scope and Visibility Assignments Expressions and Comparisons Built In Functions Fundamentals 2 1 Character Set Character Set You write a PL SQL program as lines of text using a specific set of character
58. The following fetch raises an exception because emp_cv2 does not point to a query work area yet FETCH emp_cv2 INTO emp_rec raises INVALID_CURSOR EXCEPTION WHEN INVALID CURSOR THE Make emp_cvl and emp_cv2 point to same work area emp_cv2 emp_cvl Use emp_cv2 to fetch second row from emp table ETCH emp_cv2 INTO emp_rec Reuse work area for another query OPEN emp_cv2 FOR SELECT FROM old_emp Use emp_cvl to fetch first row from old_emp table The following fetch succeeds because emp_cvl and emp_cv2 point to the same query work area ETCH emp_cvl INTO emp_rec succeeds Fr tj END Be careful when passing cursor variables as parameters At run time PL SQL raises ROWTYPE_MISMATCH if the return types of the actual and formal parameters are incompatible In the Pro C example below you define a packaged REF CURSOR type specifying the return type empSROWTYPE Next you create a stand alone procedure that references the new type Then inside a PL SQL block you open a host cursor variable for a query of the dept table Later when you pass the open host cursor variable to the stored procedure PL SQL raises ROWTYPE_MISMATCH because the return types of the actual and formal parameters are incompatible T bodiless package CREATE PACKAGE cv_types AS TYPE EmpCurTyp IS REF CURSOR RETURN empSROWTYPE
59. Then extproc loads the DLL and runs the external procedure Also extproc handles service calls such as raising an exception and callbacks to the Oracle server Finally extproc passes to PL SQL any values returned by the external procedure Figure 10 2 shows the flow of control External Procedures 10 7 How PL SQL Calls an External Procedure Figure 10 2 How an External Procedure Is Called a Database t After the external procedure completes extproc remains active throughout your Oracle session When you log off extproc is killed So you incur the cost of spawning extproc only once no matter how many calls you make Still you should call an external procedure only when the computational benefits outweigh the cost Note The Listener must start extproc on the machine that runs the Oracle server Starting extproc on a different machine is not supported Environment Variables The Listener sets a few required environment variables such as ORACLE_HOME ORACLE_SID and LD_LIBRARY_PATH for extproc Otherwise it provides extproc with a clean environment The environment variables set for extproc are independent of those set for the client server and Listener So external procedures which run in the extproc process cannot read environment variables set for the client server or Listener process 10 8 PL SQL User s Guide and Reference Passing Parameters to an External Procedure
60. example DECLARE YPE DeptRec IS RECORD dept_num BER 2 dept_name VARCHAR2 14 location VARCHAR2 13 TYPE DeptItem IS RECORD dept_num BER 2 dept_name VARCHAR2 14 location VARCHAR2 13 deptl_info DeptRec dept2_info DeptItem BEGIN deptl_info dept2_info illegal different datatypes Collections and Records 4 33 Assigning and Comparing Records As the next example shows you can assign a ROWTYPE record to a user defined record if their fields match in number and order and corresponding fields have compatible datatypes DECLARE YPE DeptRec IS RECORD dept_num NUMBER 2 dept_name CHAR 14 location CHAR 13 deptl_info DeptRec dept2_info dept SROWTYPE se SELECT INTO dept2_info FROM dept WHERE deptno 10 deptl_info dept2_info Second you can use the SELECT or FETCH statement to fetch column values into a record as the example below shows The columns in the select list must appear in the same order as the fields in your record DECLARE YPE DeptRec IS RECORD dept_num BE dept_name CHAR location CHAR dept_info DeptRec SELECT deptno dname loc INTO dept_info FROM dept WHERE deptno 20 However you cannot use the INSERT statement to insert user defined records into a database table So the followin
61. job_title i salary i if get_emp snotfound then close get_emp 1 done_fetch exit else found found 1 end if end loop nd get_employees end personnel B 6 PL SQL User s Guide and Reference Running the Programs Loading the Data Below is a listing of the SQL Plus script examplod The INSERT statements in this script load or reload the database tables processed by the sample programs To run the script invoke SOL Plus in the same Oracle account from which you ran exampbl d then issue the following command SQL gt START examplod examplod Script delete from accounts insert insert insert insert insert delete insert insert insert insert insert insert insert delete insert in in in in in to to to to to from in in in in in in in to to to to to to to accounts values 1 1000 00 accounts values 2 2000 00 accounts values 3 1500 00 accounts values 4 6500 00 accounts values 5 500 00 action action action action action action action action from bins into bins values values values values values values values values 3 u 599 null sysdate 6 i 20099 null sysdate 5 qd null null sysdate 7 u 1599 null sysdate 1 i 399
62. mode your DBA must set the Oracle initialization parameter COMPATIBLE to 7 3 0 or higher When you specify READ COMMITTED if a transaction includes SQL data manipulation statements that require row locks held by another transaction the statement waits until the row locks are released USE ROLLBACK SEGMENT This clause assigns the current transaction to the specified rollback segment and establishes the transaction not generate rollback infor as read write You cannot use this parameter with the READ ONLY parameter in the same transaction because read only transactions do mation The SET TRANSACTION statement must be the first SQL statement in your transaction and can appear only once in the transaction In the following example you establish a read only transaction COMMIT end previous transaction SET TRANSACTION READ ONLY SELEC FROM emp WHERE SELEC FROM dept WHERE SELEC FROM emp WHERE COMMIT end read only transaction COMMIT Statement ROLLBACK Statement SAVEPOINT Statement Language Elements 11 143 SQL Cursor SQL Cursor Syntax Oracle implicitly opens a cursor to process each SQL statement not associated with an explicit cursor PL SQL lets you refer to the most recent implicit cursor as the SQL cursor which has four attributes SFOUND ISOPEN SNOTFOUND and SROWCOUNT They give you informatio
63. name Hart Bell id_number 8022 department Accounting job_title Clerk salary 1750 rank 4 Object name Ann Polk id_number 8835 department Marketing job_title Analyst salary 3200 rank 3 9 4 PL SQL User s Guide and Reference Structure of an Object Type Why Use Object Types Object types reduce complexity by breaking down a large system into logical entities This allows you to create software components that are modular maintainable and reusable It also allows different teams of programmers to develop software components concurrently By encapsulating operations with data object types let you move data maintenance code out of SQL scripts and PL SQL blocks into methods Object types minimize side effects by allowing access to data only through approved operations Also object types hide implementation details so that you can change the details without affecting client programs Object types allow for realistic data modeling Complex real world entities and relationships map directly into object types Moreover object types map directly into classes defined in object oriented languages such as C Now your programs can better reflect the world they are trying to simulate Structure of an Object Type Like a package an object type has two parts a specification and a body refer to Figure 9 3 The specification is the interface to your applications it declares a data structure set of attr
64. title VARCHAR2 35 cost NUMBER 7 2 CREATE TYPE ProjectList AS VARRAY 50 OF Project define VARRAY type CREATE TABLE department idnum NU ER 2 r name VARCHAR2 15 budget NUMBER 11 2 projects ProjectList declare varray The identifier projects represents an entire varray Each element of projects will store a Project object 11 24 PL SQL User s Guide and Reference Collections Related Topics In the following example you declare a nested table as the formal parameter of a packaged procedure CREATE PACKAGE personnel AS TYPE Staff IS TABLE OF Employee PROCEDURE award_bonuses members IN Staff You can specify a collection type in the RETURN clause of a function specification as the following example shows DECLARE YPE SalesForce IS VARRAY 20 OF Salesperson FUNCTION top_performers n INTEGER RETURN SalesForce IS In the following example you update the list of projects assigned to the Security Department DECLARE new_projects ProjectList ProjectList Project 1 Issue New Employee Badges 13500 Project 2 Inspect Emergency Exits 1900 Project 3 Upgrade Alarm System 3350 Project 4 Analyze Local Crime Statistics 825 BEGIN UPDATE department SET projects new_projects WHER
65. 2 4 2 45 relational operator 2 4 2 45 remote access indicator 2 3 2 34 single line comment delimiter 2 4 statement terminator 2 3 11 12 subtraction negation operator 2 3 Index A abstraction 7 3 9 2 ACCESS_INTO_NULL exception 6 5 actual parameter 5 11 address 5 19 aggregate assignment 2 32 alias library 10 3 aliasing 5 36 ALL comparison operator 5 6 ALL option 5 3 ALL row operator 5 7 anonymous PL SQL block 7 2 ANY comparison operator 5 6 apostrophe 2 8 architecture 1 18 assignment aggregate 2 32 character string C 2 collection 4 12 cursor variable 5 34 field 4 33 record 4 33 semantics C 2 assignment operator 1 4 assignment statement syntax 11 3 association operator 7 12 asterisk option 5 3 asynchronous operation 8 18 atomically null 9 24 Index 1 attribute 1 7 ROWTYPE 2 31 TYPE 2 30 cursor 5 38 object 9 3 9 7 attribute indicator 1 7 AVG group function 5 3 base type 2 12 2 22 basic loop 3 6 BETWEEN comparison operator 2 45 5 6 BFILE datatype 2 20 binary operator 2 41 BINARY_INTEGER datatype 2 11 bind variable 5 19 binding 5 7 blank padding semantics C 3 BLOB datatype 2 20 block anonymous 7 2 label 2 39 maximum size 5 60 PL SQL 11 7 structure 1 2 body cursor 5 15 function 7 5 method 9 8 object 9 5 package 8 7 procedure 7 4 Boolean expression 2 46 literal 2 8 value 2 46 BOOLEAN datatype 2 21
66. 35 city VARCHARZ2 15 state CHAR 2 zip_code INTEGER CREATE TYPE Person AS OBJECT first_name VARCHARZ2 15 last_name VARCHARZ2 15 birthday DATE home_address Address nested object typ phone_number VARCHAR2 15 ss_number INTEGER y Address objects have twice as many attributes as Rational objects and Person objects have still more attributes including one of type Address When an object is large it is inefficient to pass copies of it from subprogram to subprogram It makes more sense to share the object You can do that if the object has an object identifier To share the object you use references refs for short A refis a pointer to an object Sharing has two important advantages First data is not replicated unnecessarily Second when a shared object is updated the change occurs in only one place and any ref can retrieve the updated values instantly 9 28 PL SQL User s Guide and Reference Sharing Objects Using Refs In the following example we gain the advantages of sharing by defining object type Home and then creating a table that stores instances of that object type CREATE TYPE Home AS OBJECT address VARCHAR2 35 owner VARCHAR2 25 age INTEGER style VARCHAR 15 floor plan BLOB price REAL 9 2 CREATE TABLE homes OF Home By revising object type Person we ca
67. END LOOP Insert new project ry my_projects position new_project Update department table UPDATE department SET projects my_projects WHERE dept_no dept_id END add project The following stored procedure updates a given project CREATE PROCEDURE update_project dept_no IN NUMBER proj_no IN NUMBER new_title IN VARCHAR2 DEFAULT NULL new_cost IN NUMBER DEFAULT NULL AS my_projects ProjectList BEGIN SELECT projects INTO my_projects FROM department WHERE dept_no dept_id FOR UPDATE OF projects Find project update it then exit loop immediately FOR i IN my_projects FIRST my projects LAST LOOP IF my projects i project_no IF new_title IS NOT NULL T my_projects 1 title proj_no THEN HEN new_title END IF IF new_cost IS NOT NULL THEN my_projects i cost new_cost END IF EXIT END IF END LOOP UPDATE department SET projects my_projects WHERE dept_no dept_id END update_project 4 20 PL SQL User s Guide and Reference Using Collection Methods In the final example you call stand alone procedure update_project to revise the cost of a project DECLARE dept_num NUMBER proj_num NUMBER BEGIN update_project dept_num proj_num new_cost
68. GOLF CLUB ER BALL E 12 3 81 MM 4 2 0 DD YY 50 0 DATE 51 1100 D YY 950 NUL 0 UL DD YY 3000 ULI UI ULL 10 DD YY 1500 0 30 iL 20 E 01 23 82 MM DD YY 1300 NULL 10 Sample Programs B 9 Running the Programs insert delete insert insert insert delete is delete delete is insert insert insert insert delete delete commit into from into into into from from from into into into into from from numl_tab values 4 num2_tab num2_tab values 1 num2_tab values 2 num2_tab values 3 purchase_record ratio result_table result_table values result_table values result_table values result_table values sum_tab temp B 10 PL SQL User s Guide and Reference 15 19 27 130 70 131 70 EL 132 73 133 81 87 194 98 Sample 1 FOR Loop Sample 1 FOR Loop The following example uses a simple FOR loop to insert ten rows into a database table The values of a loop index counter variable and either of two character strings are inserted Which string is inserted depends on the value of the loop index Input Table PL SQL Block Output Table Not applicable in fil available onlin DECLARE X BE
69. Inserting Character Values When you insert the value of a PL SQL character variable into an Oracle database column whether the value is blank padded or not depends on the column type not on the variable type When you insert a character value into a CHAR database column Oracle does not strip trailing blanks If the value is shorter than the defined width of the column Oracle blank pads the value to the defined width As a result information about trailing blanks is lost If the character value is longer than the defined width of the column Oracle aborts the insert and generates an error When you insert a character value into a VARCHAR2 database column Oracle does not strip trailing blanks If the value is shorter than the defined width of the column Oracle does not blank pad the value Character values are stored intact so no information is lost If the character value is longer than the defined width of the column Oracle aborts the insert and generates an error The same rules apply when updating When inserting character values to ensure that no trailing blanks are stored use the function RTRIM which trims trailing blanks An example follows DECLARE my_name VARCHAR2 15 BEGIN my_ename LEE note trailing blanks INSERT INTO emp VALUES my_empno RTRIM my_ename inserts LEE Selecting Character Values When you select a value from an Oracle databa
70. It is a good idea to use parentheses when doing comparisons For example the following expression is illegal because 100 lt tax yields TRUE or FALSE which cannot be compared with the number 500 100 lt tax lt 500 illegal The debugged version follows 100 lt tax AND tax lt 500 A Boolean variable is itself either true or false So comparisons with the Boolean values TRUE and FALSE are redundant For example assuming the variable done is Of type BOOLEAN the WHILE statement WHILE NOT done TRUE LOOP END LOOP can be simplified as follows WHILE NOT done LOOP END LOOP Handling Nulls When working with nulls you can avoid some common mistakes by keeping in mind the following rules comparisons involving nulls always yield NULL a applying the logical operator NOT to a null yields NULL a in conditional control statements if the condition yields NULL its associated sequence of statements is not executed 2 48 PL SQL User s Guide and Reference Expressions and Comparisons In the example below you might expect the sequence of statements to execute because x and y seem unequal But nulls are indeterminate Whether or not x is equal to yis unknown Therefore the IF condition yields NULL and the sequence of statements is bypassed x 5 y NULL IF x y THEN yields NULL not TRUE sequence_of_statements not executed EN
71. RAW X x x ROWID x x VARCHAR2 X X X X X X x x It is your responsibility to ensure that values are convertible For instance PL SQL can convert the CHAR value 02 JUN 92 to a DATE value but cannot convert the CHAR value YESTERDAY to a DATE value Similarly PL SQL cannot convert a VARCHAR2 value containing alphabetic characters to a NUMBER value Implicit versus Explicit Conversion DATE Values Generally to rely on implicit datatype conversions is a poor programming practice because they can hamper performance and might change from one software release to the next Also implicit conversions are context sensitive and therefore not always predictable Instead use datatype conversion functions That way your applications will be more reliable and easier to maintain When you select a DATE column value into a CHAR or VARCHAR2 variable PL SQL must convert the internal binary value to a character value So PL SQL calls the function TO_CHAR which returns a character string in the default date format To get other information such as the time or Julian date you must call TO_CHAR with a format mask Fundamentals 2 27 Declarations A conversion is also necessary when you insert a CHAR or VARCHAR2 value into a DATE column So PL SQL calls the function TO_DATE which expects the default date format To insert dates in other formats you must call TO_DATE with a format mask RAW and LONG RAW Values
72. ROWTYPE_MISMATCH before the first fetch So if you trap the error and execute the FETCH statement using a different INTO clause no rows are lost When you declare a cursor variable as the formal parameter of a subprogram that fetches from the cursor variable you must specify the IN or IN OUT mode However if the subprogram also opens the cursor variable you must specify the IN OUT mode If you try to fetch from a closed or never opened cursor variable PL SQL raises the predefined exception INVALID_CURSOR 5 26 PL SQL User s Guide and Reference Using Cursor Variables Example 1 Closing a Cursor Variable The CLOSE statement disables a cursor variable After that the associated result set is undefined The statement syntax follows CLOSE cursor_variable_name host_cursor_variable_name In the following example when the last row is processed you close the cursor variable emp_cv LOOP FETCH emp_cv INTO emp_rec EXIT WHEN emp_cvsNOTFOUND process data record END LOOP Close cursor variable CLOSE emp_cv When declaring a cursor variable as the formal parameter of a subprogram that closes the cursor variable you must specify the IN or IN OUT mode If you try to close an already closed or never opened cursor variable PL SQL raises the predefined exception INVALID_CURSOR Consider the stored procedure below which searches the database of a main library for boo
73. acronym CHAR 4 the following assignment raises VALUE_ERROR acronym SPCA note trailing blank When you assign a character value to a VARCHAR2 variable if the value is shorter than the declared length of the variable PL SQL neither blank pads the value nor strips trailing blanks Character values are assigned intact so no information is lost If the character value is longer than the declared length of the VARCHAR2 variable PL SQL aborts the assignment and raises VALUE_ERROR PL SQL neither truncates the value nor tries to trim trailing blanks Comparing Character Values You can use the relational operators to compare character values for equality or inequality Comparisons are based on the collating sequence used for the database character set One character value is greater than another if it follows it in the collating sequence For example given the declarations namel VARCHAR2 10 COLES name2 VARCHAR2 10 COLEMAN the following IF condition is true IF namel gt name2 THEN C 2 PL SQL User s Guide and Reference Comparing Character Values ANSI ISO SQL requires that two character values being compared have equal lengths So if both values in a comparison have datatype CHAR blank padding semantics are used That is before comparing character values of unequal length PL SQL blank pads the shorter value to the length of the longer value For example
74. built in function 2 51 BY REF phrase 10 15 by reference parameter passing 7 17 by value parameter passing 7 17 Index 2 C call subprogram 7 12 callback 10 22 example 10 22 restrictions 10 23 CALLING STANDARD clause 10 4 carriage return 2 3 case sensitivity identifier 2 5 string literal 2 8 case lower xix case upper xix CHAR column maximum width 2 14 CHAR datatype 2 14 CHAR semantics C 1 CHAR_CS value 2 28 character literal 2 7 character set 2 2 CHARACTER subtype 2 14 character value assigning C 2 comparing C 2 inserting C 4 selecting C 4 CHARSETFORM property 10 15 CHARSETID property 10 15 client program 9 2 CLOB datatype 2 20 CLOSE statement 5 13 5 27 syntax 11 14 collating sequence 2 47 collection 4 2 assigning 4 12 comparing 4 13 constructor 4 9 declaring 4 7 defining 4 5 element type 4 5 initializing 4 9 referencing 4 11 scope 4 9 syntax 11 21 collection exceptions when raised 4 28 collection method applying to parameters 4 27 COUNT 4 22 DELETE 4 26 EXISTS 4 22 EXTEND 4 24 FIRST 4 23 LAST 4 23 LIMIT 4 22 NEXT 4 23 PRIOR 4 23 syntax 11 16 TRIM 4 25 collection types 4 1 COLLECTION_IS_NULL exception 6 5 column alias 5 17 when needed 2 33 comment 2 9 restrictions 2 10 syntax 11 26 COMMENT clause 5 46 COMMIT statement 5 46 syntax 11 27 comparison of character values C 2 of collections 4 13 of expressi
75. called a nested object type That lets you build a complex object type from simpler object types Some object types such as queues lists and trees are dynamic meaning that they can grow as they are used Recursive object types which contain direct or indirect references to themselves allow for highly sophisticated data models Object Types 9 7 Components of an Object Type Methods In general a method is a subprogram declared in an object type specification using the keyword MEMBER The method cannot have the same name as the object type or any of its attributes Like packaged subprograms most methods have two parts a specification and a body The specification consists of a method name an optional parameter list and for functions a return type The body is the code that executes to perform a specific operation For example the functions plus less times and divby are methods of object type Complex These methods are always available to Complex objects For each method specification in an object type specification there must be a corresponding method body in the object type body To match method specifications and bodies the PL SQL compiler does a token by token comparison of their headers So the headers must match word for word In an object type methods can reference attributes and other methods without a qualifier as the example below shows CREATE TYPE Stack AS OBJECT top INTEGER EMBER F
76. dept_rec dept ROWTYP El se wW Gl Q H Z SELECT deptno dname loc INTO dept_rec FROM dept WHERE deptno 30 However you cannot assign a list of column values to a record by using an assignment statement So the following syntax is illegal record_name valuel value2 value3 illegal Although you can retrieve entire records you cannot insert or update them For example the following statement is illegal INSERT INTO dept VALUES dept_rec illegal Using Aliases Select list items fetched from a cursor associated with SROWTYPE must have simple names or if they are expressions must have aliases In the following example you use an alias called wages available online in file examp4 DECLARE CURSOR my_cursor IS SELECT sal NVL comm 0 wages ename FROM emp my_rec my_cursor ROWTYPE BEGIN OPEN my_cursor LOOP FETCH my_cursor INTO my_rec EXIT WHEN my_cursorSNOTFOUND IF my_rec wages gt 2000 THEN INSERT INTO temp VALUES NULL my_rec wages my_rec ename END IF END LOOP CLOSE my_cursor END se Ea Fundamentals 2 33 Naming Conventions Restrictions PL SQL does not allow forward references You must declare a variable or constant before referencing it in other statements including other declarative statements For example the followin
77. error The number that SOLCODE returns is negative unless the Oracle error is no data found in which case SQLCODE returns 100 For user defined exceptions SOLCODE returns 1 unless you used the pragma EXCEPTION_INIT to associate the exception with an Oracle error number in which case SQLCODE returns that error number For more information see Using SQLCODE and SOLERRM on page 6 18 Syntax sqlcode function Usage Notes You cannot use SOL CODE directly in a SOL statement First you must assign the value of SOLCODE to a local variable An example follows DECLARE my_sqlcode UMBER BEGIN EXCEPTION WHEN OTHERS THEN my_sqlcode SQLCODE INSERT INTO errors VALUES my_sqlcode END SQLCODE is especially useful in the OTHERS exception handler because it lets you identify which internal exception was raised Related Topics Exceptions SQLERRM Function 11 146 PL SQL User s Guide and Reference SQLERRM Function SQLERRM Function Syntax The function SQLERRM returns the error message associated with its error number argument or if the argument is omitted with the current value of SQLCODE SQLERRM with no argument is meaningful only in an exception handler Outside a handler SOLERRM with no argument always returns the message normal successful completion For
78. forward reference 2 34 forward type definition 9 30 FOUND cursor attribute 5 38 5 42 function 7 1 7 5 body 7 5 built in 2 51 call 7 6 parameter 7 5 parts 7 5 RETURN clause 7 5 specification 7 5 syntax 11 79 G gigabyte 2 20 GLB group function 5 3 GOTO statement 3 15 label 3 15 misuse 3 17 restriction 6 17 syntax 11 83 GROUP BY clause 5 3 group function AVG 5 3 COUNT 5 3 GLB 5 3 LUB 5 3 MAX 5 3 MIN 5 3 STDDEV 5 3 SUM 5 3 treatment of nulls 5 3 VARIANCE 5 3 H handler exception 6 2 handling exceptions 6 1 raised in declaration 6 16 raised in handler 6 17 using OTHERS handler 6 15 handling of nulls 2 48 hidden declaration 8 2 hiding information 1 16 host variable 5 19 hypertext markup language HTML 8 17 hypertext transfer protocol HTTP 8 17 identifier forming 2 4 maximum length 2 5 quoted 2 6 scope rules 2 37 IF statement 3 2 ELSE clause 3 3 ELSIF clause 3 4 syntax 11 85 THEN clause 3 3 implicit cursor 5 14 attribute 5 42 implicit datatype conversion 2 26 effect on performance 5 59 implicit declaration cursor FOR loop record 5 16 FOR loop counter 3 13 IN comparison operator 2 46 5 6 IN OUT parameter mode 7 14 IN parameter mode 7 13 incomplete object type 9 30 index cursor FOR loop 5 16 index by table 4 3 indicator 10 14 INDICATOR property 10 14 infinite loop 3 6 information hiding 1 16 8 4 initializ
79. gt 3750 Using Collection Methods The following collection methods help generalize code make collections easier to use and make your applications easier to maintain EXISTS COUNT LIMIT FIRST and LAST PRIOR and NEXT EXTEND TRI DELETE A collection method is a built in function or procedure that operates on collections and is called using dot notation The syntax follows collection_name method_name parameters Collection methods can be called from procedural statements but not from SQL statements EXISTS COUNT LIMIT FIRST LAST PRIOR and NEXT are functions which appear as part of an expression EXTEND TRIM and DELETE are procedures which appear as a statement Also EXISTS PRIOR NEXT TRIM EXTEND and DELETE take parameters Each parameter must be an expression that yields an integer Only EXISTS can be applied to atomically null collections If you apply another method to such collections PL SQL raises COLLECTION_IS_NULL Collections and Records 4 21 Using Collection Methods Using EXISTS Using COUNT Using LIMIT EXISTS n returns TRUE if the nth element in a collection exists Otherwise EXISTS n returns FALSE Mainly you use EXISTS with DELETE to maintain sparse nested tables You can also use EXISTS to avoid raising an exception when you reference a nonexistent element In the following example PL SQL e
80. immediately However to have multiple exit points in a subprogram is a poor programming practice In procedures a RETURN statement cannot contain an expression The statement simply returns control to the caller before the normal end of the procedure is reached However in functions a RETURN statement must contain an expression which is evaluated when the RETURN statement is executed The resulting value is assigned to the function identifier which acts like a variable of the type specified in the RETURN clause Observe how the function balance returns the balance of a specified bank account FUNCTION balance acct_id INTEGER RETURN REAL IS acct_bal REAL BEGI SELECT bal INTO acct_bal FROM accts WHERE acct_no acct_id RETURN acct_bal END balance The following example shows that the expression in a function RETURN statement can be arbitrarily complex FUNCTION compound years NUMBER amount NUMBER rate NUMBER RETURN NUMBER IS BEGI RETURN amount POWER rate 100 1 years END compound A function must contain at least one RETURN statement Otherwise PL SQL raises the predefined exception PROGRAM_ERROR at run time Subprograms 7 7 Declaring Subprograms Declaring Subprograms You can declare subprograms in any PL SQL block subprogram or package However you must declare subprograms a
81. null sysdate 9 qd null null sysdate 10 x null null sysdate 1 5469 650 Sample Programs B 7 Running the Programs insert Us insert insert hs insert insert insert delete insert insert insert insert insert insert delete insert 73 insert 74 insert 75 insert 75 insert 7654 MARTIN SALI into bins values 2 7243 450 into bins values 3 5469 120 into bins values 4 5469 300 into bins values 5 6085 415 into bins values 6 5469 280 into bins values 7 8159 619 from data_table into data_table values 1 10 167 17 into data_table values 1 16 223 35 into data_table values 2 34 547 2 into data_table values 3 23 318 11 into data_table values 1 17 266 15 into data_table values 1 20 117 9 from emp into emp values 69 SMITH CLERK 7902 TO_DATE 12 17 80 MM into emp values 99 ALLEN SALESMAN 7698 TO_DATE 02 20 81 into emp values 21 WARD SALESMAN 7698 TO_DATE 02 22 81 MM into emp values 66 JONES MANAGER 7839 TO_DATE 04 02 81 MM into emp values B 8 PL SQL User s Guide and Reference ESMAN 7698 TO_DATE 09 28 81 DD YY 800 NULL 20 DD YY 1600 300 30 DD
82. statements Language Elements 11 11 Blocks Example PL SQL statements are free format That is they can continue from line to line if you do not split keywords delimiters or literals across lines A semicolon serves as the statement terminator PL SQL supports a subset of SQL statements that includes data manipulation cursor control and transaction control statements but excludes data definition and data control statements such as ALTER CREATE GRANT and REVOKE EXCEPTION This keyword signals the start of the exception handling part of a PL SQL block When an exception is raised normal execution of the block stops and control transfers to the appropriate exception handler After the exception handler completes execution proceeds with the statement following the block If there is no exception handler for the raised exception in the current block control passes to the enclosing block This process repeats until an exception handler is found or there are no more enclosing blocks If PL SQL can find no exception handler for the exception execution stops and an unhandled exception error is returned to the host environment For more information see Chapter 6 exception_handler This construct associates an exception with a sequence of statements which is executed when that exception is raised For the syntax of exception_handler see Exceptions on page 11 54 END This keyword sig
83. tape_rec tapesSROWTYPE BEGIN get_title title title is a host variable find _item title lib cv FETCH lib cv INTO book_rec display_book book_rec EXCEPTION WHEN ROWIYPE_MISMATCH THEN BEGIN FETCH lib cv INTO periodical_rec display_periodical periodical_rec EXCEPTION WHEN ROWIYPE_MISMATCH THEN FETCH lib_cv INTO tape_rec display_tape tape_rec E END z 5 28 PL SQL User s Guide and Reference Using Cursor Variables Example 3 The following Pro C program prompts the user to select a database table opens a cursor variable for a query of that table then fetches rows returned by the query include lt stdio h gt include lt sqlca h gt void sql_error main char temp 32 EXEC SQL BEGIN DECLARE SECTION char uid scott tiger EL SOL CURSOR generic_cv cursor variable int table_num selector struct EMP record int num char emp_name 11 char job title 10 int manager char hire date 10 float salary float commission int dept_num emp rec struct D int dept_num char dept_name 15 char location 14 dept_rec struct char emp name 11 char job title 10 float salary bonus_rec EXEC SQL END DECLARE SECTION Handle Oracle errors Connect to Oracle EXEC SQL CONNEC
84. time trying to assign a null to a variable defined as NOT NULL raises the predefined exception VALUE_ERROR The constraint NOT NULL must be followed by an initialization clause Language Elements 11 31 Constants and Variables Usage Notes Examples Related Topics expression This is an arbitrarily complex combination of variables constants literals operators and function calls The simplest expression consists of a single variable When the declaration is elaborated the value of expression is assigned to the constant or variable The value and the constant or variable must have compatible datatypes Constants and variables are initialized every time a block or subprogram is entered By default variables are initialized to NULL So unless you expressly initialize a variable its value is undefined Whether public or private constants and variables declared in a package specification are initialized only once per session An initialization clause is required when declaring NOT NULL variables and when declaring constants You cannot use the attribute SROWTYPE to declare a constant If you use SROWTYPE to declare a variable initialization is not allowed Several examples of variable and constant declarations follow credit_limit CONSTANT NUMBER 5000 invalid BOOLEAN FALSE acct_id INTEGER 4 NO ULL DEFAULT 9999 pi CONSTANT REA
85. 06531 6531 CURSOR_ALREADY OPEN ORA 06511 6511 DUP_VAL_ON_INDEX ORA 00001 1 INVALID_CURSOR ORA 01001 1001 INVALID NUMBER ORA 01722 1722 LOGIN_DENTED ORA 01017 1017 NO_DATA FOUND ORA 01403 100 NOT_LOGGED_ON ORA 01012 1012 PROGRAM_ERROR ORA 06501 6501 ROWTYPE_MISMATCH ORA 06504 6504 STORAGE_ERROR ORA 06500 6500 SUBSCRIPT_BEYOND_COUNT ORA 06533 6533 SUBSCRIPT_OUTSIDE_LIMIT ORA 06532 6532 IMEOUT_ON_RESOURCE ORA 00051 51 TOO_MANY_ROWS ORA 01422 1422 VALUE_ERROR ORA 06502 6502 ZERO_DIVIDE ORA 01476 1476 6 4 PL SQL User s Guide and Reference Predefined Exceptions Brief descriptions of the predefined exceptions follow Exception Raised when ACCESS_INTO_NULL you try to assign values to the attributes of an uninitialized atomically null object COLLECTION_IS_NULL you try to apply collection methods other than EXISTS to an uninitialized atomically null nested table or varray or you try to assign values to the elements of an uninitialized nested table or varray CURSOR_ALREADY OPEN you try to open an already open cursor You must close a cursor before you can reopen it A cursor FOR loop automatically opens the cursor to which it refers So you cannot open that cursor inside the loop ir ad DUP_VAL_ON_IND you try to store duplicate values in a database column that is constrained by a unique index INVALID_CURSOR you try an illegal cursor operation such
86. 2 procedure versus function 7 5 recursive 7 24 standalone 1 19 stored 1 19 7 10 subquery 5 14 SUBSCRIPT_BEYOND_COUNT exception 6 6 SUBSCRIPT_OUTSIDE_LIMIT exception 6 6 SUBSTR function 6 19 subtype 2 12 2 22 CHARACTER 2 14 compatibility 2 24 DEC 2 13 DECIMAL 2 13 defining 2 23 DOUBLE PRECISION 2 13 FLOAT 2 13 INT 2 13 INTEGER 2 13 NATURAL 2 12 NATURALN 2 12 NUMERIC 2 13 overloading 7 20 POSITIVE 2 12 POSITIVEN 2 12 REAL 2 13 Index 14 SIGNTYPE 2 12 SMALLINT 2 13 STRING 2 17 VARCHAR 2 17 SUM group function 5 3 support for SQL 5 2 symbol compound 2 4 simple 2 3 syntax definition 11 1 syntax diagram reading 11 2 T tab 2 3 TABLE datatype 4 2 table index by 4 3 table nested 4 2 terminating condition 7 24 terminator statement 2 3 ternary operator 2 41 THEN clause 3 3 TIMEOUT_ON_RESOURCE exception 6 6 TOO_MANY_ROWS exception 6 6 top down design 1 16 trailing blanks how handled C 4 transaction 5 2 5 45 committing 5 46 distributed 5 45 ending properly 5 49 read only 5 50 rolling back 5 47 transaction processing 5 2 5 44 TRIM collection method 4 25 TRUE value 2 8 Trusted Oracle 2 10 TYPE attribute 2 30 syntax 11 149 type definition collection 4 5 forward 9 30 RECORD 4 29 REF CURSOR 5 20 U unary operator 2 41 underscore 2 4 unhandled exception 6 12 6 19 uninitialized object how treated 9 25 UNION ALL set operator 5 6 UNI
87. 25 000 LOOP total total salary EXIT WHEN total gt 25000 exit loop if condition is true END LOOP control resumes here Sequential Control The GOTO statement lets you branch to a label unconditionally The label an undeclared identifier enclosed by double angle brackets must precede an executable statement or a PL SQL block When executed the GOTO statement transfers control to the labeled statement or block as the following example shows IF rating gt 90 THEN GOTO calc_raise branch to label END IF lt lt calc_raise gt gt IF job title SALESMAN THEN control resumes here amount commission 0 25 ELSE amount salary 0 10 END IF Modularity lets you break an application down into manageable well defined logic modules Through successive refinement you can reduce a complex problem to a set of simple problems that have easy to implement solutions PL SQL meets this need with program units Besides blocks and subprograms PL SQL provides the package which allows you to group related program items into larger units Overview 1 11 Main Features Subprograms PL SQL has two types of subprograms called procedures and functions which can take parameters and be invoked called As the following example shows a subprogram is like a miniature program beginning with a header followed by an optional declarative part an
88. AS FUNCTION f1 p1 NUMBER RETURN t1 IS n ER BEGIN n scott packl fl n 10 dot separated chain of identifiers schema nam al used as scope qualifier followed by package name also used as scope qualifier followed by function name also used as scope qualifier followed by local variable name END FUNCTION 2 ql NUMBER RETURN t2 IS BEGIN NULL END END E 4 PL SQL User s Guide and Reference Name Resolution Algorithm Name Resolution Algorithm Let us take a look at the name resolution algorithm The first part of name resolution involves finding the basis The basis is the smallest prefix to a dot separated chain of identifiers that can be resolved by looking in the current scope then moving outward to schema level scopes In the previous examples the basis for 3 pack1 f1 p1 is PACK1 the basis for 4 scott pack1 f1 nis SCOTT PACK1 and the basis for 5 v1 ais V1 In 5 the A in V1 A is a component selector and resolves as field A of variable V1 because V1 is of type T1 which has a field called A If a basis is not found the compiler generates a not declared error If the basis is found the compiler tries to resolve the complete reference If it fails the compiler generates an error The length of the basis is always 1 2 or 3 And it can be 3 only inside SQL scope when the compiler resolves
89. An example follows my_sqlerrm SUBSTR SQLERRM 1 150 INSERT I END TO errors VA UES my_sqlerrm The string function SUBSTR ensures that a VALUE_ERROR exception for truncation is not raised when you assign the value of SQLERRM to my_sqlerrm SOLERRM is especially useful in the OTHERS exception handler because it lets you identify which internal exception was raised Related Topics Exceptions SQLCODE Function 11 148 PL SQL User s Guide and Reference TYPE Attribute TYPE Attribute Syntax The STYPE attribute provides the datatype of a field record nested table database column or variable You can use the TYPE attribute as a datatype specifier when declaring constants variables fields and parameters For more information see Using TYPE on page 2 30 type_attribute collection_name cursor_variable_name object_name field_name record_name PRA db_table_name C column_name variable_name i o EG Keyword and Parameter Description collection_name This identifies a nested table index by table or varray previously declared within the current scope cursor_variable_name This identifies a PL SQL cursor variable previously declared within the current scope Only the value of another cursor variable can be assigned to a cursor variable object_name This identifies an object instance of an object typ
90. BEGIN IF groupl group2 THEN causes compilation error This restriction also applies to implicit comparisons For example collections cannot appear in a DISTINCT GROUP BY or ORDER BY list Manipulating Collections Within PL SQL collections add flexibility and procedural power A big advantage is that your program can compute subscripts to process specific elements Within SQL you can manipulate whole collections easily Some Nested Table Examples In SOL Plus suppose you define object type Course as follows SQL gt CREATE TYPE Course AS OBJECT 2 course_no NUMBER 4 3 title VARCHAR2 35 4 credits NUMBER 1 Next you define TABLE type CourseList which stores Course objects SQL gt CREATE TYPE CourseList AS TABLE OF Course Finally you create database table department which has a column of type CourseList as follows SQL gt CREATE TABLE department 2 name VARCHARZ2 20 director VARCHAR2 20 office VARCHAR2 20 courses CourseList NESTED TABLE courses STORE AS courses_tab nu fs W 4 14 PL SQL User s Guide and Reference Manipulating Collections Each item in column courses is a nested table that will store the courses offered by a given department The NESTED TABLE clause is required because department has a nested table column The clause identifies the nested table and names a s
91. C and D are erased An implicit savepoint is marked before executing an INS statement If the statement fails a rollback to the implicit ERT UPDATE or DELETE savepoint is done Normally just the failed SOL statement is rolled back not the whole transaction However if the statement raises an unhandled exception determines what is rolled back COMMIT Statement SAVEPOINT Statement the host environment Language Elements 11 135 ROWTYPE Attribute ROWTYPE Attribute Syntax The SROWTYPE attribute provides a record type that represents a row in a database table The record can store an entire row of data selected from the table or fetched from a cursor or cursor variable Fields in a record and corresponding columns in a row have the same names and datatypes You can use the SROWTYPE attribute in variable declarations as a datatype specifier Variables declared using SROWTYPE are treated like those declared using a datatype name For more information see Using ROWTYPE on page 2 31 rowtype_attribute A Keyword and Parameter Description Usage Notes cursor_name This identifies an explicit cursor previously declared within the current scope cursor_variable_name This identifies a PL SQL strongly not weakly typed cursor variable previously declared within the current scope table_name This identifies a database table or view that must be accessible when th
92. Consider the following OR expression DECLARE on_hand INTEGER on_order INTEGER BEGIN IF on_hand 0 OR on_order on_hand lt 5 THEN END IF END When the value of on_hand is zero the left operand yields TRUE so PL SQL need not evaluate the right operand If PL SQL were to evaluate both operands before applying the OR operator the right operand would cause a division by zero error In any case it is a poor programming practice to rely on short circuit evaluation Comparison Operators Comparison operators compare one expression to another The result is always TRUE FALSE or NULL Typically you use comparison operators in the WHERE clause of SQL data manipulation statements and in conditional control statements 2 44 PL SQL User s Guide and Reference Expressions and Comparisons Relational Operators The relational operators allow you to compare arbitrarily complex expressions The following list gives the meaning of each operator Operator Meaning equal to lt gt not equal to lt less than gt greater than lt less than or equal to gt greater than or equal to IS NULL Operator The IS NULL operator returns the Boolean value TRUE if its operand is null or FALSE if it is not null Comparisons involving nulls always yield NULL Therefore to test for nullity the state of being null do not use the statement I
93. ELSIF choice 3 OPEN generic_cv FOR S ID IF END open_cv END emp_data SIF choice 2 EN generic_cv FOR S Using a Host Variable You can declare a cursor variable in a PL SQL host environment such as an OCI or Pro C program To use the cursor variable you must pass it as a host variable to PL SQL In the following Pro C example you pass a host cursor variable and selector to a PL SQL block which opens the cursor variable for the chosen query HEN HEN FROM dept EC SOL BEGIN DECLARE S Declare ECTION FROM salgrade ost cursor variable and selector to PL SQL block FROM emp FROM dept FROM salgrade host cursor variable SQL_CURSOR generic_cv int choice EXEC SQL END DECLARE SECTION Initialize host cursor variable EXEC SQL ALLOCATE generic_cv Pass h EXEC SQL EXECUTE BEGIN IF choice 1 THEN OPEN generic_cv FOR SELEC ELSIF choice 2 THEN OPEN generic_cv FOR SELEC ELSIF choice 3 THEN OPEN generic_cv FOR SELEC END IF END END EXEC Host cursor variables are compatible with any query return type They behave just like weakly typed PL SQL cursor variables Interaction with Oracle 5 25 Using Cursor Variables Fetching from a Cursor Variable The FETCH stateme
94. Embedded PL SOL oooiocicicocicicicinononiccnnonnnnnncnonononconnnnononanconnnnano a aae a e a spanta B 19 Sample 6 Calling a Stored Procedure ocicooniioinnnnnnocnnnnnacnnconocnanano ronca nncnano rin cncnonanorin canino B 23 C CHAR versus VARCHAR2 Semantics Assigning Character Values ccccccccscsssesescscscesesescscsesesesescsesesesesescsesesesesescsesesesesescseseseseseeeses C 2 Comparing Character Values reinari aiii iii Si ekaia aoei ieni C 2 xi D Inserting Character Value ooonicicococioionononnonnononoconanonononananancnononononanonononononanononononon R E C 4 Selecting Character Values cion id i C 4 PL SQL Wrapper Advantages of Wrapping ici ino cit cidade alada D 2 Running the PL SQL WrappeT cconococinionononnoncononoconananononanananononononononanononononananonononononononononarananoncnonoss D 2 E Name Resolution What Is Name Resolution iia E 2 Various Forms f References vicios ai a rica E 3 Name Resolution Al gorithm oooonicnnnnnnnnnnnnnnnnnnnnncncncncnnonorororocononoro nono corona nono rnrnnona raro ro coronan rarninns E 5 Understanding Capture inssin oia t e a aoa d aa E E a e Ra E 8 Avoiding Capture sereen AAA E E 10 Accessing Attributes and MethodS ooononnnnicncnnononicnnonononononcnonononononononononononononononononononononononcncnos E 10 Calling Subprograms and Methods ooocooocicicicicoconicnononannnnnonononanoncnononononanononononanonononononanananononono E 11 SOT versus PL
95. FROM salgrade ND IF END open_cv END emp_data E Related Topics CLOSE Statement Cursor Variables FETCH Statement LOOP Statements 11 116 PL SQL User s Guide and Reference Packages Packages Syntax A package is a schema object that groups logically related PL SQL types items and subprograms Packages have two parts a specification and a body For more information see Chapter 8 package_specification CREATE PACKAGE END collection_type_definition function_specification procedure_specification record_type_definition package_item_declaration package_body CREATE PACKAGE BODY EN aan O pragma_declaration lt collection_type_definition record_type_definition END Language Elements 11 117 Packages package_item_declaration collection_declaration constant_declaration exception_declaration object_declaration record_declaration variable_declaration Keyword and Parameter Description package_name This identifies a package For naming conventions see Identifiers on page 2 4 collection_declaration This identifies a nested table index by table or varray previously declared within the current scope For the syntax of collection_declaration see Collections on page 11 21 constant_declaration This construct decla
96. For more information see Chapter 9 The collection types TABLE and VARRAY allow you to declare nested tables and variable size arrays varrays for short A collection is an ordered group of elements all of the same type Each element has a unique subscript that determines its position in the collection A 2 PL SQL User s Guide and Reference NLS Types LOB Types NLS Types Collections work like the arrays found in most third generation programming languages They can store instances of an object type and conversely can be attributes of an object type Also collections can be passed as parameters So you can use them to move columns of data into and out of database tables or between client side applications and stored subprograms For more information see Chapter 4 The LOB large object datatypes BF ILE BLOB CLOB and NCLOB let you store blocks of unstructured data up to four gigabytes in size And they allow efficient random piece wise access to the data LOB types store values called locators that specify the location of large objects stored out of line or in an external file PL SQL operates on LOBs through the locators To manipulate LOBs you use the supplied package DBMS_LOB which is discussed in Oracle8 Application Developer s Guide For more information see Datatypes on page 2 10 Oracle8 offers extended NLS National Language Support including national character sets and the datatypes NCHA
97. Guide and Reference Blocks exception_declaration This construct declares an exception For the syntax of exception_declaration see Exceptions on page 11 54 object_declaration This identifies an object instance of an object type previously declared within the current scope For the syntax of ob ject_declaration see Object Types on page 11 103 record declaration This construct declares a user defined record For the syntax of record_declarat ion see Records on page 11 128 variable_declaration This construct declares a variable For the syntax of variable_declaration see Constants and Variables on page 11 29 function_declaration This construct declares a function For the syntax of function_declaration see Functions on page 11 79 procedure_decliaration This construct declares a procedure For the syntax of procedure_declaration see Procedures on page 11 121 BEGIN This keyword signals the start of the executable part of a PL SQL block which contains executable statements The executable part of a PL SQL block is required That is a block must contain at least one executable statement The NULL statement meets this requirement statement This is an executable not declarative statement that you use to create algorithms A sequence of statements can include procedural statements such as RAISE SQL statements such as UPDATE and PL SQL blocks sometimes called block
98. OPEN FOR statement cannot be FOR UPDATE You cannot use comparison operators to test cursor variables for equality inequality or nullity You cannot assign nulls to a cursor variable 7 You cannot use REF CURSOR types to specify column types ina CREATE TABLI or CREATE VIEW statement So database columns cannot store the values of cursor variables You cannot use a REF CURSOR type to specify the element type of a collection which means that elements in a nested table index by table or varray cannot store the values of cursor variables You cannot use cursor variables with dynamic SQL Cursors and cursor variables are not interoperable that is you cannot use one where the other is expected For example the following cursor FOR loop is illegal DECLARE CURSOR emp_cur IS SELECT FROM emp static cursor YPE EmpCurTyp IS REF CURSOR RETURN emp ROWTYPE emp_cv EmpCurTyp cursor variable BEGIN FOR emp_rec IN emp cv LOOP illegal END LOOP END Interaction with Oracle 5 37 Using Cursor Attributes Using Cursor Attributes Each cursor or cursor variable has four attributes FOUND ISOP EN SNOTFOUND and ROWCOUNT When appended to the cursor or cursor variable these attributes return useful information about the execution of a data manipulation statement You can use cursor attributes in procedural
99. Object Types object_type_body Keyword and Parameter Description type_name This identifies a user defined type specifier which is used in subsequent declarations of objects attribute_name This identifies an object attribute The name must be unique within the object type but can be reused in other object types You cannot initialize an attribute in its declaration using the assignment operator or DEFAULT clause Also you cannot impose the NOT NULL constraint on an attribute attribute_datatype This is any Oracle datatype except LONG LONG RAW MLSLABEL NCHAR NCLOB NVARCHA subtypes SROWTYP BOOLI EAN PLS_INT R2 ROWID the PL SQL specific types BINARY_INTEGER and its EGI ER R ECORD REF CURSOR TYPE and 11 104 PL SQL User s Guide and Reference E and types defined inside a PL SQL package Object Types MEMBER This keyword allows you to declare a function or procedure in an object type specification The method cannot have the same name as the object type or any of its attributes Like packaged subprograms methods have two parts a specification and a body The specification consists of a method name an optional parameter list and for functions a return type The body is the code that executes to perform a specific operation For each method specification in an object type specification there must be a corresponding method body
100. SQL User s Guide and Reference Conditional Control IF Statements Guidelines If the value of sales is more than 50000 the first and second conditions are true Nevertheless bonus is assigned the proper value of 1500 because the second condition is never tested When the first condition yields TRUE its associated statement is executed and control passes to the INSERT statement Avoid clumsy IF statements like those in the following example DECLARE overdrawn BOOLEAN BEGIN IF new_balance lt minimum_balance THEN overdrawn TRUE ELSE overdrawn FALSE END IF IF overdrawn TRUE THEN RAISE insufficient_funds END IF END This code disregards two useful facts First the value of a Boolean expression can be assigned directly to a Boolean variable So you can replace the first IF statement with a simple assignment as follows overdrawn new_balance lt minimum_balance Second a Boolean variable is itself either true or false So you can simplify the condition in the second IF statement as follows IF overdrawn THEN Control Structures 3 5 Iterative Control LOOP and EXIT Statements When possible use the ELSIF clause instead of nested IF statements That way your code will be easier to read and understand Compare the following IF statements IF conditionl THEN statement1 ELSE IF conditio
101. SQL statement is part of a transaction A distributed transaction includes at least one SQL statement that updates data at multiple nodes in a distributed database The COMMIT and ROLLBACK statements ensure that all database changes brought about by SQL operations are either made permanent or undone at the same time All the SOL statements executed since the last commit or rollback make up the current transaction The SAVEPOINT statement names and marks the current point in the processing of a transaction Interaction with Oracle 5 45 Processing Transactions Using COMMIT The COMMIT statement ends the current transaction and makes permanent any changes made during that transaction Until you commit the changes other users cannot access the changed data they see the data as it was before you made the changes Consider a simple transaction that transfers money from one bank account to another The transaction requires two updates because it debits the first account then credits the second In the example below after crediting the second account you issue a commit which makes the changes permanent Only then do other users see the changes BEGIN UPDATE accts SET bal my_bal debit WHERE acctno 7715 UPDATE accts SET bal my_bal credit WHERE acctno 7720 COMMIT WORK END The COMMIT statement releases all row and table locks It also erases any savepoints discussed l
102. SUBTYPE CHARACTER IS CHAR The subtype CHARACTER specifies the same set of values as its base type CHAR Thus CHARACTER is an unconstrained subtype Subtypes can increase reliability provide compatibility with ANSI ISO types and improve readability by indicating the intended use of constants and variables 2 22 PL SQL User s Guide and Reference User Defined Subtypes Defining Subtypes You can define your own subtypes in the declarative part of any PL SQL block subprogram or package using the syntax SUBTYPE subtype_name IS base_type where subt ype_name is a type specifier used in subsequent declarations and base_type is any scalar or user defined PL SQL type To specify base_type you can use TYPE which provides the datatype of a variable or database column Also you can use SROWTYPE which provides the rowtype of a cursor cursor variable or database table Some examples follow DECLARE SUBTYPE EmpDate IS DATE based on DATE type SUBTYPE Counter IS NATURAL based on NATURAL subtype PE NameList IS TABLE OF VARCHAR2 10 SUBTYPE EmpRoster IS NameList based on TABLE type YPE TimeRec IS RECORD minutes INTEGER hours INTEGER SUBTYPE Time IS TimeRec based on RECORD type SUBTYPE ID_Num IS emp empno TYPE based on column type CURSOR cl IS SELECT
103. TABLE tab2 coll NUMBER CREATE PROCEDURE proc AS CURSOR cl IS SELECT FROM tabl WHERE EXISTS SELECT FROM tab2 WHERE col2 10 BEGIN END In this example the reference to co12 in the inner SELECT statement binds to column co12 in table tab1 because table tab2 has no column named co12 If you add a column named co12 to table tab2 as follows ALTER TABLE tab2 ADD col2 NUMBER then procedure proc is invalidated and recompiled automatically upon next use However upon recompilation the co12 in the inner SELECT statement binds to column col2 in table tab2 because t ab2 is in the inner scope Thus the reference to col2 is captured by the addition of column co12 to table tab2 E 8 PL SQL User s Guide and Reference Understanding Capture The use of collections and object types allows for more inner capture situations Consider the following example CREATE TYPE typel AS OBJECT a BER CREATE TABLE tabl tab2 typel i CREATE TABLE tab2 x NUMBER SELECT FROM tabl s alias with same name as schema nam WHERE EXISTS SELECT FROM s tab2 note lack of alias WHERE x s tab2 a In this example the reference to s tab2 a resolves to attribute a of column tab2 in table tab1 via
104. WHERE name Psychology Some Varray Examples In SOL Plus suppose you define object type Project as follows TYPE Project AS OBJECT 2 project_no NUMBER 2 SQL gt CREATE 3 title 4 cost VARCHAR2 35 NUMBER 7 2 Next you define VARRAY type Project List which stores Project objects SQL gt CREATE TYP E ProjectList AS VARRAY 50 OF Project 4 16 PL SQL User s Guide and Reference Manipulating Collections Finally you create relational table department which has a column of type ProjectList as follows SQL gt CREATE 2 dept_id NUMBER 2 3 name VARCHAR2 15 4 budget NUMBER 11 2 5 projects ProjectList TABLE department Each item in column projects is a varray that will store the projects scheduled for a given department Now you are ready to populate relational table department In the following example notice how varray constructor ProjectList provides values for column projects BEGIN INSERT INTO department VALUES 30 ProjectList Project 1 Project 2 Project 3 Project 4 INSERT INTO department VALUES 50 Maintenance ProjectList Project 1 Project 2 Project 3 Project 4 Project 5 INSERT INTO department Accounting 1205700 Design New Expense Report 3250
105. YY 1250 500 30 I DD YY 2975 NULL 20 M DD YY 1250 1400 30 Running the Programs t in 698 in 82 in in 39 in 44 t in t in 900 t in 902 insert in 7934 delete insert insert insert delete delete insert insert insert fr in in fr fr into into into into to emp values to emp values to emp values to emp values BLAKE MANAGER 7839 CLARK MANAGER 7839 O _DA O_DA 7788 SCOTT ANALYST 7566 SYSDATE 85 30 E 05 1 81 MM DD YY 2850 E 06 9 81 MM DD YY 2450 KING PRESI ENT NULL O_DAT E 111 17 81 to emp values TURNER SAL to emp values to emp values JAMES CLERK to emp values to emp values MILLER CL T om inventory to to om journal om numl_tab FORD ANALYST 7566 ERK 7782 inventory values inventory values inventory values SOCC numl_tab values numl_tab values numl_tab values ESMAN 7698 TO_DAT El 09 8 81 7876 ADAMS CLERK 7788 SYS 1 7698 TO_DATE 12 3 81 MM D O_DA O_DA TEN 1 5 2 7 3 4 IS RACKET
106. a bind variable to PL SQL In the following Pro C example you pass a host cursor variable and selector to a PL SQL block which opens the cursor variable for the chosen query C SQL BEGIN DECLARE SECTION Declare host cursor variable SQL_CURSOR generic_cv int choice C SQL END DECLARE SECTION js Initialize host cursor variable C SQL ALLOCATE generic_cv js Pass host cursor variable and selector to PL SQL block C SQL EXECUTE 11 42 PL SQL User s Guide and Reference Cursor Variables Y E GIN IF choice 1 THEN OPEN generic_cv FOR SELECT FROM emp SIF choice 2 THEN OPEN generic_cv FOR SELECT FROM dept SIF choice 3 THEN OPEN generic_cv FOR SI END IF END END EXEC 7j 1j a ECT FROM salgrade Host cursor variables are compatible with any query return type They behave just like weakly typed PL SQL cursor variables When passing host cursor variables to PL SQL you can reduce network traffic by grouping OPEN FOR statements For example the following PL SQL block opens three cursor variables in a single round trip anonymous PL SQL block in host environment BEGIN OPEN emp_cv FOR SELECT FROM emp OPEN dept_cv FOR SELECT FROM dept OPEN grade_cv FOR SELECT FROM salgrade END 41
107. a qualified name to reference the global identifier Although you cannot declare an identifier twice in the same block you can declare the same identifier in two different blocks The two items represented by the identifier are distinct and any change in one does not affect the other However a block cannot reference identifiers declared in other blocks at the same level because those identifiers are neither local nor global to the block Fundamentals 2 37 Scope and Visibility Figure 2 2 Scope and Visibility Scope DECLARE X REAL BEGIN DECLARE X REAL BEGIN Outer x END END DECLARE X REAL BEGIN Inner x X REAL BEGIN END END DECLARE Visibility DECLARE XREAL BEGIN DECLARE XREAL BEGIN END END DECLARE X REAL BEGIN DECLARE X REAL BEGIN END END The example below illustrates the scope rules Notice that the identifiers declared in one sub block cannot be referenced in the other sub block That is because a block cannot reference identifiers declared in other blocks nested at the same level DECLARE a CHAR b REAL BEGI DECLARE a INTEGER c REAL BEGIN E ND 2 38 PL SQL User s Guide and Reference identifiers available here a CHAR b identifiers available here a INTEGER b c Scope and Visibility DECLARE d REAL BEGIN identifiers avail
108. a sequence of statements until a condition is met You can use iteration or recursion to solve such problems Use recursion when the problem can be broken down into simpler versions of itself For example you can evaluate 3 as follows 0 1 by definition 1 1 0 1 2 ZA 2 are 21 ag To implement this algorithm you might write the following recursive function which returns the factorial of a positive integer FUNCTION fac n POSITIVE RETURN INTEGER IS returns n BEGIN IF n 1 THEN terminating condition RETURN 1 ELSE RETURN n fac n 1 recursive call END IF END fac At each recursive call n is decremented Eventually n becomes 1 and the recursion stops 7 24 PL SQL User s Guide and Reference Recursion Example 2 Consider the procedure below which finds the staff of a given manager The procedure declares two formal parameters mgr_no and tier which represent the manager s employee number and a tier in his or her departmental organization Staff members reporting directly to the manager occupy the first tier When called the procedure accepts a value for mgr_no but uses the default value of tier For example you might call the procedure as follows find staff 7839 The procedure passes mgr_no to a cursor in a cursor FOR loop which finds staff members at successively lower tiers in the organization At each recursive call
109. a three part name as schema_name table_name column_name Here are more examples of bases variable_name type_name package_name schema_name package_nam schema_name function_name table_name table_name column_name schema_name table_nam schema_name table_name column_name Finding the Basis Now let us look at the algorithm for finding the basis If the compiler is resolving a name in SQL scope which includes everything in a SQL data manipulation statement except items in the INTO clause and schema level table names it first tries to find the basis in that scope If it fails it tries to find the basis in PL SQL local scopes and at the schema level just as it would for names in non SQL scopes Name Resolution E 5 Name Resolution Algorithm Here are the rules for finding the basis in SOL scope when the compiler expects to find a column name Given one identifier the compiler tries to find a basis of length using the identifier as an unqualified column name in one of the tables listed in any FROM clauses that are in scope starting with the current scope and moving outward Given a of chain two identifiers the compiler tries to find a basis of length 2 using the identifiers as a column name qualified by a table name or table alias starting with the current scope and moving outward Given a chain of three identifiers the compiler tries to find in each scope that it searches starting with the current scope an
110. acia ida ica cidad adds 4 23 Using PRIOR and NEXT cion ion iio ste Bie de hah a SEE AE oad he 4 23 Usine EXTEND A E IN NE TN 4 24 PA A O 4 25 Usines DELETE enasna n Ed NIN DIT TIEN IU 4 26 Applying Methods to Collection Parameters oconoconcnononenonncnnnnncncnrnnnenncarananonnnrnrornnnnnnnanaranoos 4 27 Avoiding Collection Excepti0NS ocoocioioininonnonnnnmnmmcsncnccacerin co rnanona ronca cn cnaro nono rn rrare ran cn cross 4 27 What Isa Recordando aia 4 28 Defining and Declaring RecordS ocoocicioininononionnnnnnncneccecncenanonenin cn nncnono ron anononono non cnnncnono ran cn anno 4 29 Declaring ReCOrds iii sccccises cusses chaencasnedgsenaadidcnnnsaesssdonnentardssetdentesadednararhisdeneesaaadadathgsuadseesdinenraaes 4 30 Initializing and Referencing Records 0 cccc ccc ccc ees eee cecseeeeeseececssenseseececssesseseeeeeenes 4 31 Referencing RecordS triada diet dh E Savanah ts 4 31 Assigning and Comparing RecordS oooociciciconociononnnnnnonnoncncnnnenacononincanncnononon cn cnanono ronca nrcna coran crono 4 33 Comparing Records vimos tas ci cs 4 35 IEC AAA 4 35 Interaction with Oracle SOL SUPPO iii aii 5 2 Data Mamip latiOnss nimeti ienest tock ios italia shah bes vhs tad cbse Pes Be ke 5 2 Transaction Control cin eel Ae eri ae e lS tact Gate Gar aS aAa aN 5 2 SOL Fines cea dal lea do Deak tase e dde Le 5 3 SOL PSeudOcOl uss ti AAA a ESEE ais 5 4 SOLO Pera O pt At E SE Neds A AE tai 5 6 SOLIZ Conformance A i
111. and white to be different Also trailing blanks are significant within string literals so White and White are different How a string literal compares to a variable does not depend on the variable trailing blanks in a literal are never trimmed Unlike the non value NULL the Boolean values TRUE and FALSE cannot be inserted into a database column Several examples of numeric literals follow 25 6 34 7E2 25e 03 al Ts 17 4 4 Several examples of character literals follow my rer mor ror ei g A few examples of string literals follow 5 000 02 AUG 87 Don t leave without saving your work Constants and Variables Expressions Language Elements 11 93 LOCK TABLE Statement LOCK TABLE Statement Syntax The LOCK TABLE statement lets you lock entire database tables in a specified lock mode so that you can share or deny access to tables while maintaining their integrity For more information see Using LOCK TABLE on page 5 52 lock_table_statement ZO DGI O Keyword and Parameter Description Usage Notes table_reference This identifies a table or view that must be accessible when you execute the LOCK TABLE statement For the syntax of table_reference see DELETE Statement on page 11 49 lock_mode This parameter specifies the lock mode It must be one of the following ROW SHARE ROW EXCLUSIVE SHARE UPDATE SHARE SHARE ROW EXCLUSIVE or EXCLUSIVE
112. and NULL Statements Control Structures 3 1 Overview Overview According to the structure theorem any computer program can be written using the basic control structures shown in Figure 3 1 They can be combined in any way necessary to deal with a given problem Figure 3 1 Control Structures Selection Iteration Sequence pur The selection structure tests a condition then executes one sequence of statements instead of another depending on whether the condition is true or false A condition is any variable or expression that returns a Boolean value TRUE or FALSE The iteration structure executes a sequence of statements repeatedly as long as a condition holds true The sequence structure simply executes a sequence of statements in the order in which they occur Conditional Control IF Statements Often it is necessary to take alternative actions depending on circumstances The IF statement lets you execute a sequence of statements conditionally That is whether the sequence is executed or not depends on the value of a condition There are three forms of IF statements IF THEN IF THEN ELSE and IF THEN ELSIF 3 2 PL SQL User s Guide and Reference Conditional Control IF Statements IF THEN IF THEN ELSE The simplest form of IF statement associates a condition with a sequence of statements enclosed by the keywords THEN and END IF not ENDIF as follows IF condition TH
113. as closing an unopened cursor INVALID_NUMBER in a SQL statement the conversion of character string to a number fails because the character string does not represent a valid number In procedural statements VALUE_ERROR is raised LOGIN_DENIED you try logging on to Oracle with an invalid username and or password NO_DATA_FOUND a SELECT INTO statement returns no rows or you reference a deleted element in a nested table or you reference an uninitialized element in an index by table The FETCH statement is expected to return no rows eventually so when that happens no exception is raised SQL group functions such as AVG and SUM always return a value or a null So a SELECT INTO statement that calls a group function will never raise NO_DATA_FOUND NOT_LOGGED_ON your PL SQL program issues a database call without being connected to Oracle PROGRAM_ERROR PL SQL has an internal problem Error Handling 6 5 User Defined Exceptions E xception Raised when ROWTYPI S SUBSCRIPT_BI SUBSCRIPT_OUTSIDI E MISMATCH TORAGE_ERROR EYOND_COUNT IMEOUT_ON_F VALUE_ERROR N ERO_DIVIDE ESOURCE TOO_MANY_ROWS E LIMIT the host cursor variable and PL SQL cursor variable involved in an assignment have incompatible return types For example when you pass an open host cursor
114. bad adenda 5 27 Example Zine e a aa a aae a Ma Ea E ear bos e E EEan Te EE iio 5 28 EXP ANETE EA E AE E T 5 29 Example Linyon A A EE E a a Ween AAA 5 31 Reducing Network Traffic nesre reiege n ned cries E EE E E 5 33 ANVOIGING EXCEPHONS iia aia sh E 5 34 Guarding A gainst A lasing sida mica aaier TEE aatis 5 36 RESITI HONS vii it nia esca isa iia 5 37 Using Cursor Attributes ooiocicinocinnnnononncnnonononananononononononononononononononononononononononon a oaiae araa 5 38 Explicit Cursor Attributes cccccccccscssssesesessseseseeceneseseecenenessseansnensssseeeesescssecanenesesesnaneneneees 5 38 Implicit Cursor AttHibytes npinins teri ieia a EE E Ea o eE EEE OREERT AEE AEE AEREE Enei 5 42 Processing Transactions ens io A EE EA E A AAA 5 44 How Transactions Guard Your Database ooonoconeninonnononnnnnnonnenneccnnnnenararannnnnnn ran nrneraranarannnnoso 5 45 Usme COMMIT EAN E a EA E E 5 46 Using ROLLBACK cintia ia Ie E A E aa E TE 5 47 Using SAVEPOINT asasena aie E td Eb EL EA A A 5 48 Implicit Rollbacks ii is 5 49 Ending Transact Ons cui ia ia crias 5 49 Using SET TRANSACTI N on A E 5 50 Overriding Default LockiNg cncnncncnnnnnnncnnnnnnnnnncncnnoconononononocononanncncnconanarn cn corona nano corn conaranninoos 5 51 Improving PerforManCe ccccnconnnoninnnnnnnnnnncncncaconanncncncncononncncococononncn corn ah Ab Ssa n Esa siroki ho det SeS E EEEa 5 54 Dealing with Size LimitatiodS cin ias 5 60 Ensuring Backward Compatibility
115. because an exception raised in a declaration propagates immediately to the enclosing block Exceptions Raised in Handlers Only one exception at a time can be active in the exception handling part of a block or subprogram So an exception raised inside a handler propagates immediately to the enclosing block which is searched to find a handler for the newly raised exception From there on the exception propagates normally Consider the following example EXCEPTION WHEN INVALID NUMBER THEN INSERT INTO might raise DUP_VAL_ON_INDEX WHEN DUP_VAL_ON_INDEX THEN cannot catch the exception Branching to or from an Exception Handler A GOTO statement cannot branch to an exception handler nor can it branch from an exception handler into the current block For example the following GOTO statement is illegal DECLARE pe_ratio NUMBER 3 1 BEGI DELETE FROM stats WHERE symbol XYZ SELECT price NVL earnings 0 INTO pe_ratio FROM stocks WHERE symbol XYZ lt lt my_label gt gt INSERT INTO stats symbol ratio VALUES XYZ pe ratio EXCEPTIO WHEN ZERO_DIVIDE THEN pe_ratio 0 GOTO my_label illegal branch into current block However a GOTO statement can branch from an exception handler into an enclosing block Error Handling 6 17 H
116. block or into an enclosing block but not into an exception handler From an exception handler a GOTO statement can branch into an enclosing block but not into the current block If you use the GOTO statement to exit a cursor FOR loop prematurely the cursor is closed automatically The cursor is also closed automatically if an exception is raised inside the loop A given label can appear only once in a block However the label can appear in other blocks including enclosing blocks and sub blocks If a GOTO statement cannot find its target label in the current block it branches to the first enclosing block in which the label appears A GOTO label cannot precede just any keyword It must precede an executable statement or a PL SQL block For example the following GOTO statement is illegal FOR ctr IN 1 50 LOOP DELETE FROM emp WHERE F SQLSFOUND THEN GOTO end_loop illegal END IF H lt lt end_loop gt gt END LOOP not an executable statement To debug the last example simply add the NULL statement as follows FOR ctr IN 1 50 LOOP DELETE FROM emp WHERE IF SOLSFOUND THEN GOTO end_loop END IF lt lt end_loop gt gt ULL an executable statement that specifies inaction END LOOP For more examples of legal and illegal GOTO statements see GOTO Statement on page 3 15 11 84 PL SQL User s Guide and Refere
117. call procedure raise_salary the actual parameters are evaluated and the result values are assigned to the corresponding formal parameters Before assigning the value of an actual parameter to a formal parameter PL SQL converts the datatype of the value if necessary For example the following call to raise_salary is legal raise_salary emp_num 2500 The actual parameter and its corresponding formal parameter must have compatible datatypes For instance PL SQL cannot convert between the DATE and REAL datatypes Also the result value must be convertible to the new datatype The following procedure call raises the predefined exception VALUE_ERROR because PL SQL cannot convert the second actual parameter to a number raise_salary emp_num 2500 note the dollar sign For more information see Datatype Conversion on page 2 25 Subprograms 7 11 Positional and Named Notation Positional and Named Notation When calling a subprogram you can write the actual parameters using either positional or named notation That is you can indicate the association between an actual and formal parameter by position or name For example given the declarations DECLARE acct INTEGER amt REAL PROCEDURE credit_acct acct_no INTEGER amount REAL IS you can call the procedure credit_acct in four logically equivalent ways BEGIN credit_acct acct amt
118. calling a function that returns a collection you use the following syntax to reference elements in the collection collection_name parameter_list subscript With the Oracle Call Interface OCI or the Oracle Precompilers you can bind host arrays to collections declared as the formal parameters of a subprogram That allows you to pass host arrays to stored functions and procedures Language Elements 11 23 Collections Examples To specify the element type of a collection you can use TYPE or SROWTYPE as the following example shows DECLARE YPE JobList IS VARRAY 10 OF emp job sTYPE based on column CURSOR cl IS SELECT FROM dept YPE DeptFile IS TABLE OF cl ROWIYPE based on cursor YPE EmpFile IS VARRAY 150 OF empSROWTYPE based on database table In the next example you use a RECORD type to specify the element type DECLARE YPE Entry IS RECORD term VARCHAR2 20 meaning VARCHAR2 200 YPE Glossary IS VARRAY 250 OF Entry When defining a VARRAY type you must specify its maximum size In the following example you define a type that stores up to 366 dates DECLARE YPE Calendar IS VARRAY 366 OF DATE Once you define a collection type you can declare collections of that type as the following SQL Plus script shows CREATE TYPE Project AS OBJECT project_no NUMBER 2
119. check_status part_id procedure call IF SOLSNOTFOUND THEN dangerous You can debug the code as follows UPDATE parts SET quantity quantity 1 WHERE partno part_id sql_notfound SQL NOTFOUND assign value to Boolean variable check_status part_id IF sql_notfound THEN Interaction with Oracle 5 43 Processing Transactions If a SELECT INTO statement fails to return a row PL SQL raises the predefined exception NO_DATA_FOUND whether you check NOTFOUND on the next line or not Consider the following example BEGI SELECT sal INTO my_sal FROM emp WHERE empno my_empno might raise NO_DATA FOUND IF SOLSNOTFOUND THEN condition tested only when false this action is never taken END IF The check is useless because the IF condition is tested only when SNOTFOUND is false When PL SQL raises NO_DATA_FOUND normal execution stops and control transfers to the exception handling part of the block However a SELECT INTO statement that calls a SQL group function never raises NO_DATA_FOUND because group functions always return a value or a null In such cases 3NOTFOUND yields FALSE as the following example shows BEGI SELECT MAX sal INTO my_sal FROM emp WHERE deptno my_deptno never raises NO_DATA FOUND IF SOLSNOTFOUND THEN always tested but never tru this action is nev
120. cl LOOP FETCH cl INTO numl num2 num3 EXIT WHEN c1SNOTFOUND yields TRUE when FETCH finds no more rows result num2 numl num3 INSERT INTO temp VALUES result NULL NULL END LOOP CLOSE cl COMMIT END In the next example you check all storage bins that contain part number 5469 withdrawing their contents until you accumulate 1000 units available online in file examp6 DECLARE CURSOR bin_cur part_number NUMBER IS SELECT amt_in_bin FROM bins WHERE part_num part_number AND amt_in_bin gt 0 ORDER BY bin_num FOR UPDATE OF amt_in_bin bin_amt bins amt_in_bin STYPE total_so_far NUMBER 5 0 amount_needed CONSTANT NUMBER 5 1000 bins_looked_at NUMBER 3 0 BEGIN OPEN bin_cur 5469 WHILE total_so_far lt amount_needed LOOP FETCH bin_cur INTO bin_amt EXIT WHEN bin _curSNOTFOUND 1f we exit there s not enough to fill the order bins_looked_at bins looked_at 1 IF total_so far bin_amt lt amount_needed THEN UPDATE bins SET amt_in_bin 0 WHERE CURRENT OF bin_cur take everything in the bin total_so far total_so far bin_amt ELSE we finally have enough UPDATE bins SET amt_in bin amt_in bin amount_needed total_so far WHERE CURRENT OF bin cur total_so far amount_needed
121. clause The parameter RETURN corresponds to the C function identifier which stores the result value Using INDICATOR An indicator is a parameter whose value indicates whether or not another parameter is null PL SQL does not need indicators because the RDBMS concept of nullity is built into the language However an external procedure might need to know if a parameter or function result is null Also an external procedure might need to signal the server that a returned value is actually a null and should be treated accordingly In such cases you can use the property INDICATOR to associate an indicator with a formal parameter If the PL SQL subprogram is a function you can also associate an indicator with the function result To check the value of an indicator you can use the constants OCI_IND_NULL and OCI_IND_NOTNULL If the indicator equals OCI_IND_NULL the associated parameter or function result is null If the indicator equals OCI_IND_NOTNULL the parameter or function result is not null For IN parameters INDICATOR is passed by value unless you specify BY REF and is read only even if you specify BY REF For OUT IN OUT and RETURN parameters INDICATOR is passed by reference Using LENGTH and MAXLEN In PL SQL there is no standard way to indicate the length of a raw or string parameter However in many cases you want to pass the length of a parameter to and from an external procedure Using t
122. collection 4 3 DEPT table xx DEREF operator 9 34 dereference 9 34 digits of precision 2 12 DISTINCT option 5 3 DISTINCT row operator 5 7 distributed transaction 5 45 DLL dynamic link library 10 3 dot notation 1 6 1 7 for collection methods 4 21 for global variables 3 13 for object attributes 9 25 for object methods 9 27 for package contents 8 6 for record fields 2 32 DOUBLE PRECISION subtype 2 13 DUP_VAL_ON_INDEX exception 6 5 dynamic FOR loop range 3 12 dynamic link library DLL 10 3 dynamic SQL support 5 7 E elaboration 2 29 element type collection 4 5 ellipsis xix ELSE clause 3 3 ELSIF clause 3 4 EMP table xx encapsulation data 1 16 END IF reserved words 3 3 END LOOP reserved words 3 9 Entry SQL support 5 7 error message maximum length 6 18 evaluation 2 41 short circuit 2 44 EXAMPBLD script B 3 EXAMPLOD script B 7 exception 6 2 declaring 6 6 predefined 6 4 propagation 6 12 raised in declaration 6 16 raised in handler 6 17 raising with RAISE statement 6 11 reraising 6 14 scope rules 6 7 syntax 11 54 user defined 6 6 WHEN clause 6 15 exception handler 6 15 branching from 6 17 OTHERS handler 6 2 using RAISE statement in 6 15 using SOLCODE function in 6 18 using SOLERRM function in 6 18 EXCEPTION_INIT pragma 6 8 syntax 11 52 using with raise_application_error 6 10 exception handling part function 7 6 PL SQL block 1 3 procedure 7 4 exe
123. column list THE The operand of THE is a subquery that returns a single column value to the INSERT statement The column value must be a nested table Operator THE informs Oracle that the value is a nested table not a scalar value subquery1 This is a select statement that provides a value or set of values to the INSERT statement Its syntax is like that of select_into_statement without the INTO clause See SELECT INTO Statement on page 11 139 As many rows are added to the table as are returned by the subquery in the VALUES clause The subquery must return a value for every column in the column list or for every column in the table if there is no column list subquery2 This is a select statement that provides a value or set of values to the VALUES clause The subquery must return only one row containing a value for every column in the column list or for every column in the table if there is no column list Language Elements 11 89 INSERT Statement RETURNING This clause lets you return values from the inserted row thereby eliminating the need to SELECT the row afterward You can retrieve the column values into variables and or host variables Usage Notes All character and date literals in the VALUES list must be enclosed by single quotes Numeric literals are not enclosed by quotes The implicit SOL cursor and cursor attributes SNOTFOUND SFOUND SROWCOUNT and ISOPEN let you acces
124. copied to object table persons2 are given new object identifiers No object identifiers are copied from object table persons The script below creates a relational table named department which has a column of type Person then inserts a row into the table Notice how constructor Person provides a value for column manager CREATE TABLE department dept_name VARCHAR2 20 manager Person location VARCHAR2 20 Object Types 9 37 Manipulating Objects INSERT INTO department VALUES Payroll Person Alan Tsai Los Angeles The new Person object stored in column manager is not referenceable because it is stored in a column not a row and therefore has no object identifier Updating Objects To modify the attributes of objects in an object table you use the UPDAT statement as the following example shows GI BEGIN UPDATE persons p SET p home_address 341 Oakdene Ave WHERE p last_name Brody UPDATE persons p SET p Person Beth Steinberg WHERE p last_name Steinway Deleting Objects You use the DELETE statement to remove objects rows from an object table To remove objects selectively you use the WHERE clause as the following example shows BEGIN DELETE FROM persons p WHERE p home_address 108 Palm Dr H 9 38 PL SQL User s Guide and R
125. database link 2 34 PL SQL User s Guide and Reference Naming Conventions Synonyms Scoping You can create synonyms to provide location transparency for remote schema objects such as tables sequences views stand alone subprograms and packages However you cannot create synonyms for items declared within subprograms or packages That includes constants variables cursors cursor variables exceptions and packaged procedures Within the same scope all declared identifiers must be unique So even if their datatypes differ variables and parameters cannot share the same name For example two of the following declarations are illegal DECLARE valid_id BOOLEAN valid_id VARCHAR2 5 illegal duplicate identifier FUNCTION bonus valid_id IN INTEGER RETURN REAL IS illegal triplicate identifier For the scoping rules that apply to identifiers see Scope and Visibility on page 2 37 Case Sensitivity Like other identifiers the names of constants variables and parameters are not case sensitive For instance PL SQL considers the following names to be the same DECLARE zip_code INTEGER Zip Code INTEGER same as zip code ZIP_CODE INTEGER same as zip code and Zip Code Name Resolution In potentially ambiguous SQL statements the names of local variables and formal parameters take precedence over the names of datab
126. date drop table ratio create table ratio sample_id number 3 not null ratio number drop table result_table create table result_table sample_id number 3 not null x number y number drop table sum_tab create table sum_tab sequence number 3 not null sum number 5 drop table temp create table temp num coll number 9 4 num_col2 number 9 4 char_col char 55 create or replace package personnel as type charArrayTyp is table of varchar2 10 index by binary_integer type numArrayTyp is table of float index by binary_integer procedure get_employees dept_number in integer batch_size in integer found in out integer done_fetch out integer emp_name out charArrayTyp job title out charArrayTyp salary out numArrayTyp end personnel Sample Programs B 5 Running the Programs create or replace package body personnel as cursor get_emp dept_number integer is select ename job sal from emp where deptno dept_number procedure get_employ dept_number in batch_size in found in out done_fetch out emp_name out job_title out salary out begin Ss integer integer integer integer charArrayT charArrayT YPr YPr numArrayTyp is if not get_emp isopen then open get_emp dept_number end if done_fetch 0 found 0 for i in 1 batch_size loop fetch get_emp into emp name i
127. directory see the Oracle installation or user s guide for your system The following list shows the names of the files and their locations in this guide Filename Location in Guide exampl on page 1 2 examp2 on page 1 9 examp3 on page 1 10 examp4 on page 2 33 examp5 on page 5 40 examp6 on page 5 41 examp7 on page 5 16 examp8 on page 5 18 examp11 on page 11 12 examp12 on page 11 35 examp13 on page 11 36 examp14 on page 11 36 samplel on page B 11 sample2 on page B 12 sample3 on page B 13 sample4 on page B 15 sample5 on page B 19 sample6 on page B 23 You run some samples interactively from SQL Plus others from Pro C programs You can experiment with the samples from any Oracle account However the Pro C examples expect you to use the SCOTT TIGER account Before trying the samples you must create some database tables then load the tables with data You do that by running two SQL Plus scripts exampb1d and examplod supplied with PL SQL You can find these scripts in the PL SQL demo directory B 2 PL SQL User s Guide and Reference Running the Programs Creating the Tables Below is a listing of the SQL Plus script exampbid The CREATE statements in this script build the database tables processed by the sample programs To run the script invoke SOL Plus then issue the following command SQL gt START exampbld exampbld Script set compatibility V7 ff drop table accounts create table acco
128. example the following statement returns the number of different job titles in the emp table SELECT COUNT DISTINCT job INTO job_ count FROM emp The COUNT function lets you specify the asterisk option which returns the number of rows in a table For example the following statement returns the number of employees in the emp table SELECT COUNT INTO emp_count FROM emp Except for COUNT all group functions ignore nulls Interaction with Oracle 5 3 SQL Support SQL Pseudocolumns PL SQL recognizes the following SQL pseudocolumns which return specific data items CURRVAL LEVEL NEXTVAL ROWID and ROWNUM Pseudocolumns are not actual columns in a table but they behave like columns For example you can select values from a pseudocolumn However you cannot insert values into update values in or delete values from a pseudocolumn You can use pseudocolumns in SQL statements but not in procedural statements In the following example you use the database sequence empno_seqand the pseudocolumn NEXTVAL which returns the next value in a database sequence to insert a new employee number into the emp table INSERT INTO emp VALUES empno_seq NEXTVAL new_ename Brief descriptions of the pseudocolumns follow For more information see Oracle8 SQL Reference CURRVAL and NEXTVAL A sequence is a schema object that generates sequential numbers When you create
129. exception is raised Exception Raised when COLLECTION_IS_NULL collection is atomically null NO_DATA_FOUND subscript designates an element that was deleted SUBSCRIPT_BEYOND_COUNT subscript exceeds number of elements in collection SUBSCRIPT_OUTSIDE_LIMIT subscript is outside the legal range VALUE_ERROR subscript is null or not convertible to an integer In some cases you can pass invalid subscripts to a method without raising an exception For instance when you pass a null subscript to procedure DELETE it does nothing Also you can replace deleted elements without raising NO_DATA_FOUND as the following example shows DECLARE YPE NumList IS TABLE OF BER nums NumList NumList 10 20 30 initialize table BEGIN nums DELETE 1 does not raise SUBSCRIPT_OUTSIDE_ LIMIT nums DELETE 3 delete 3rd element DBMS_OUTPUT PUT_LINE nums COUNT prints 2 nums 3 30 does not raise NO_DATA FOUND DBMS_OUTPUT PUT_LINE nums COUNT prints 3 What Is a Record A record is a group of related data items stored in fields each with its own name and datatype Suppose you have various data about an employee such as name salary and hire date These items are logically related but dissimilar in type A record containing a field for each item lets you trea
130. exception_handler This construct associates an exception with a sequence of statements which is executed when that exception is raised For the syntax of exception_handler see Exceptions on page 11 54 A procedure is called as a PL SQL statement For example the procedure raise_salary might be called as follows raise_salary emp_num amount Inside a procedure an IN parameter acts like a constant Therefore it cannot be assigned a value An OUT parameter acts like an uninitialized variable So its value cannot be assigned to another variable or reassigned to itself An IN OUT parameter acts like an initialized variable Therefore it can be assigned a value and its value can be assigned to another variable For summary information about the parameter modes see Table 7 1 on page 7 15 Language Elements 11 123 Procedures Examples Unlike OUT and IN OUT parameters IN parameters can be initialized to default values For more information see Parameter Default Values on page 7 15 Before exiting a procedure explicitly assign values to all OUT formal parameters Otherwise the values of corresponding actual parameters are indeterminate If you exit successfully PL SQL assigns values to the actual parameters However if you exit with an unhandled exception PL SQL does not assign values to the actual parameters You can write the procedure specification and body as a unit Or you can separate the procedure spec
131. executable part and an optional exception handling part PROCEDURE award_bonus emp_id NUMBER IS bonus REAL comm_missing EXCEPTION BEGI SELECT comm 0 15 INTO bonus FROM emp WHERE empno emp_id IF bonus IS NULL THEN RAISE com missing UPDATE payroll SET pay pay bonus WHERE empno emp_id END IF EXCEPTION WHEN comm missing THEN END award_ bonus When called this procedure accepts an employee number It uses the number to select the employee s commission from a database table and at the same time compute a 15 bonus Then it checks the bonus amount If the bonus is null an exception is raised otherwise the employee s payroll record is updated External Procedures Some programming tasks are more quickly or easily done in a lower level language such as C which is more efficient at machine precision calculations For example a Fast Fourier Transform FFT routine written in C runs faster than one written in PL SQL To support such special purpose processing PL SQL provides an interface for calling routines written in other languages This makes the strengths and capabilities of those languages available to you An external procedure is a third generation language routine stored in a dynamic link library DLL registered with PL SQL and called by you to do special purpose processing At run time PL SQL loads
132. fetch failed to return a row In the following example you use SNOTFOUND to exit a loop when FETCH fails to return a row LOOP FETCH cl INTO my_ename my_sal my_hiredate EXIT WHEN cl NOTFOUND END LOOP Before the first fetch SNOTFOUND evaluates to NULL So if FETCH never executes successfully the loop is never exited That is because the EXIT WHEN statement executes only if its WHEN condition is true To be safe you might want to use the following EXIT statement instead EXIT WHEN c1SNOTFOUND OR ci sNOTFOUND IS NULL If a cursor or cursor variable is not open referencing it with SNOTFOUND raises INVALID_CURSOR ROWCOUNT When its cursor or cursor variable is opened SROWCOUNT is zeroed Before the first fetch SROWCOUNT yields 0 Thereafter it yields the number of rows fetched so far The number is incremented if the last fetch returned a row In the next example you use SROWCOUNT to take action if more than ten rows have been fetched LOOP FETCH cl INTO my_ename my_deptno IF Cc1SROWCOUNT gt 10 THEN D IF E END LOOP If a cursor or cursor variable is not open referencing it with SROWCOUNT raises INVALID_CURSOR Interaction with Oracle 5 39 Using Cursor Attributes Table 5 1 shows what each cursor attribute yields before and after you execute an OPEN FETCH or CLOSE statement Table 5 1 Cursor Attribute Values FOUND
133. gigabytes BLOBs participate fully in transactions Changes made by package DBMS_LOB or the OCI can be committed or rolled back However BLOB locators cannot span transactions or sessions CLOB You use the CLOB datatype to store large blocks of single byte character data in the database in line or out of line Variable width character sets are not supported Every CLOB variable stores a locator which points to a large block of character data The size of a CLOB cannot exceed four gigabytes 2 20 PL SQL User s Guide and Reference Datatypes Other Types CLOBs participate fully in transactions Changes made by package DBMS_LOB or the OCI can be committed or rolled back However CLOB locators cannot span transactions or sessions NCLOB You use the NCLOB datatype to store large blocks of single byte or fixed width multi byte NCHAR data in the database in line or out of line Variable width character sets are not supported Every NCLOB variable stores a locator which points to a large block of NCHAR data The size of an NCLOB cannot exceed four gigabytes NCLOBs participate fully in transactions Changes made by package DBMS_LOB or the OCI can be committed or rolled back However NCLOB locators cannot span transactions or sessions The following types allow you to store and manipulate logical true false values date time values and Trusted Oracle operating system labels BOOLEAN You use the BOOLEAN datatype to
134. given consecutive subscripts starting at 1 That gives you array like access to individual rows Within PL SQL nested tables are like one dimensional arrays However nested tables differ from arrays in two important ways First arrays have a fixed upper bound but nested tables are unbounded see Figure 4 1 So the size of a nested table can increase dynamically 4 2 PL SQL User s Guide and Reference What Is a Collection Figure 4 1 Array versus Nested Table Array of Integers 321 17 99 407 83 622 105 19 67 278 x 1 x 2 x 8 x 4 x 5 x 6 Nested Table after Deletions x 7 x 8 x 9 x 10 321 2 99 407 622 105 19 278 x 3 x 4 x 6 x 7 x 10 Fixed Upper Bound Unbounded gt Second arrays must be dense have consecutive subscripts So you cannot delete individual elements from an array Initially nested tables are dense but they can be sparse have nonconsecutive subscripts So you can delete elements from a nested table using the built in procedure D EL ETE That might leave gaps in the index but the built in function NEXT lets you iterate over any series of subscripts Differences Between Nested Tables and Index by Tables Nested tables differ from Version 2 PL SQL tables called index by tables from here on in the following ways InSQL you can manipulate nes
135. has follows typedef struct OCIExtProcContext OCIExtProcContext Now let us see how service routines use the context information OCIExtProcAllocCallMemory This service routine allocates n bytes of memory for the duration of the external procedure call Any memory allocated by the function is freed automatically as soon as control returns to PL SQL Note The external procedure need not and should not call the C function free to free memory allocated by this service routine The C prototype for this function follows dvoid OCIExtProcAllocCallMemory OCIExtProcContext with_context size_t amount The parameters with_context and amount are the context pointer and number of bytes to allocate respectively The function returns an untyped pointer to the allocated memory A return value of zero indicates failure In SQL Plus suppose you register external function concat as follows SQL gt CREATE FUNCTION concat 2 strl IN VARCHAR2 str2 IN VARCHAR2 RETURN VARCHAR2 AS EXTERNAL NAME concat LIBRARY stringlib WITH CONTEX PARAMETERS CONTEXT strl STRING stri INDICATOR short HOG AMANDA oO B WwW PR External Procedures 10 17 Using Service Routines 12 str2 STRING 13 str2 INDICATOR short 14 RETURN INDICATOR short 15 RETURN LENGTH short 16 RETURN STRING When called co
136. identifier The numeric literal 147 and the Boolean literal FALSE are examples Numeric Literals Two kinds of numeric literals can be used in arithmetic expressions integers and reals An integer literal is an optionally signed whole number without a decimal point Some examples follow 030 6 14 0 32767 A real literal is an optionally signed whole or fractional number with a decimal point Several examples follow 6 6667 0 0 12 0 3 14159 8300 00 so 25 PL SQL considers numbers such as 12 0 and 25 to be reals even though they have integral values Numeric literals cannot contain dollar signs or commas but can be written using scientific notation Simply suffix the number with an E or e followed by an optionally signed integer A few examples follow 2E5 1 0E 7 3 14159e0 1E38 9 5e 3 E stands for times ten to the power of As the next example shows the number after E is the power of ten by which the number before E must be multiplied the double asterisk is the exponentiation operator 5E3 5 10 3 5 1000 5000 The number after E also corresponds to the number of places the decimal point shifts In the last example the implicit decimal point shifted three places to the right in the next example it shifts three places to the left 5E 3 5 10 3 5 0 001 0 005 Character Literals A character literal is an individual character enclosed by single quotes apostrophes Se
137. in a database table opens a cursor repeatedly fetches rows of values from the result set into fields in the record then closes the cursor when all rows have been processed In the following example the cursor FOR loop implicitly declares emp_rec as a record DECLARE CURSOR c1 IS SELECT ename sal hiredate deptno FROM emp BEGIN FOR emp_rec IN cl LOOP salary_total salary_total emp_rec sal END LOOP To reference individual fields in the record you use dot notation in which a dot serves as the component field selector Cursor Variables Like a cursor a cursor variable points to the current row in the result set of a multi row query But unlike a cursor a cursor variable can be opened for any type compatible query It is not tied to a specific query Cursor variables are true PL SQL variables to which you can assign new values and which you can pass to subprograms stored in an Oracle database This gives you more flexibility and a convenient way to centralize data retrieval Typically you open a cursor variable by passing it to a stored procedure that declares a cursor variable as one of its formal parameters The following procedure opens the cursor variable generic_cv for the chosen query PROCEDURE open_cv generic_cv IN OUT GenericCurTyp choice IN BER IS BEGI TF choice 1 THEN OPEN generic_cv FOR SELECT FROM emp ELSIF choice 2 THEN OPEN generic_c
138. in the object type body To match method specifications and bodies the compiler does a token by token comparison of their headers So the headers must match word for word All methods in an object type accept an instance of that type as their first parameter The name of this built in parameter is SELF Whether declared implicitly or explicitly SELF is always the first parameter passed to a method Ina method body SELF denotes the object whose method was called In member functions if SELF is not declared its parameter mode defaults to IN However in member procedures if SELF is not declared its parameter mode defaults to IN OUT You cannot specify a different datatype for SELF MAP This keyword indicates that a method orders objects by mapping them to values of a scalar datatype such as CHAR or REAL which have a predefined order PL SQL uses the ordering to evaluate Boolean expressions suchas x gt y and todo comparisons implied by the DISTINCT GROUP BY and ORDER BY clauses A map method returns the relative position of an object in the ordering of all such objects An object type can contain only one map method which must be a parameterless function having the return type DATE NUMBER VARCHAR2 or an ANSI SQL type such as CHARACTER INTEGER or REAL ORDER This keyword indicates that a method compares two objects Every order method takes just two parameters the built in p
139. in the sequence after the second is the sum of the two terms that immediately precede it In a recursive definition something is defined in terms of simpler versions of itself Consider the definition of n factorial n the product of all integers from 1 to n n n n 1 Subprograms 7 23 Recursion Recursive Subprograms A recursive subprogram is one that calls itself Think of a recursive call as a call to some other subprogram that does the same task as your subprogram Each recursive call creates a new instance of any items declared in the subprogram including parameters variables cursors and exceptions Likewise new instances of SOL statements are created at each level in the recursive descent Be careful where you place a recursive call If you place it inside a cursor FOR loop or between OPEN and CLOSE statements another cursor is opened at each call As a result your program might exceed the limit set by the Oracle initialization parameter OPEN_CURSORS There must be at least two paths through a recursive subprogram one that leads to the recursive call and one that does not That is at least one path must lead to a terminating condition Otherwise the recursion would theoretically go on forever In practice if a recursive subprogram strays into infinite regress PL SQL eventually runs out of memory and raises STORAGE_ERROR Example 1 To solve some programming problems you must repeat
140. indicator variable indicates the value or condition of its associated host variable For example in the Oracle Precompiler environment indicator variables let you detect nulls or truncated values in output host variables parameter_name This identifies a formal OUT or IN OUT parameter of the subprogram in which the assignment statement appears index This is a numeric expression that must yield a value of type BINARY_INTEGER ora value implicitly convertible to that datatype record_name field_name This identifies a field in a user defined or SROWTYPE record previously declared within the current scope 11 4 PL SQL User s Guide and Reference Assignment Statement Usage Notes variable_name This identifies a PL SQL variable previously declared within the current scope expression This is an arbitrarily complex combination of variables constants literals operators and function calls The simplest expression consists of a single variable For the syntax of expression see Expressions on page 11 59 When the assignment statement is executed the expression is evaluated and the resulting value is stored in the assignment target The value and target must have compatible datatypes By default unless a variable is initialized in its declaration it is initialized to NULL every time a block or subprogram is entered So never reference a variable before you assign it a value You cannot assig
141. instances of an object type have no predefined order To put them in order PL SQL calls a map method supplied by you In the following example the keyword MAP indicates that method convert orders Rational objects by mapping them to REAL values CREATE TYPE Rational AS OBJECT num INTEGER den INTEGER MAP MEMBER FUNCTION convert RETURN REAL CREATE TYPE BODY Rational AS MAP MEMBER FUNCTION convert RETURN REAL IS convert rational number to real number BEGI RETURN num den END convert END PL SQL uses the ordering to evaluate Boolean expressions such as x gt y and to do comparisons implied by the DISTINCT GROUP BY and ORDER BY clauses Map method convert returns the relative position of an object in the ordering of all Rational objects An object type can contain only one map method which must be a parameterless function with one of the following scalar return types DATE NUMBER VARCHAR2 an ANSI SQL type such as CHARACTER or REAL 9 10 PL SQL User s Guide and Reference Components of an Object Type Alternatively you can supply PL SQL with an order method In the example below the keyword ORDER indicates that method match compares two objects Every order method takes just two parameters the built in parameter SELF and another object of the same type If cl and c
142. internal exceptions SOLERRM returns the message associated with the Oracle error that occurred The message begins with the Oracle error code For user defined exceptions SOLERRM returns the message user defined exception unless you used the pragma EXCEPTION_INIT to associate the exception with an Oracle error number in which case SQLERRM returns the corresponding error message For more information see Using SQLCODE and SQLERRM on page 6 18 sqlerrm_function ap SO cae Keyword and Parameter Description Usage Notes error_number This must be a valid Oracle error number For a list of Oracle errors see Oracle8 Error Messages You can pass an error number to SQLERRM in which case SQLERRM returns the message associated with that error number The error number passed to SOLERRM should be negative Passing a zero to SQLERRM always returns the following message ORA 0000 normal successful completion Language Elements 11 147 SQLERRM Function Passing a positive number to SOLERRM always returns the message User Defined Exception unless you pass 100 in which case SQLERRM returns the following message ORA 01403 no data found You cannot use SQLI value of SOL DECLARE BEGIN my_sqlerrm CHAR 150 EXCEPTION WHEN OTH ERS THE N ERRM directly in a SQL statement First you must assign the ERRM to a local variable
143. is true NOT returns the opposite value logical negation of its operand For example NOT TRUE returns FALSE NOT NULL returns NULL because nulls are indeterminate It follows that if you apply the NOT operator to a null the result is also indeterminate Be careful Nulls can cause unexpected results see Handling Nulls on page 2 48 Order of Evaluation When you do not use parentheses to specify the order of evaluation operator precedence determines the order Compare the following expressions NOT valid AND done NOT valid AND done If the Boolean variables validand done have the value FALSE the first expression yields TRUE However the second expression yields FALSE because NOT has a higher precedence than AND therefore the second expression is equivalent to NOT valid AND done Fundamentals 2 43 Expressions and Comparisons In the following example notice that when valid has the value FALSE the whole expression yields FALSE regardless of the value of done valid AND done Likewise in the next example when valid has the value TRUE the whole expression yields TRUE regardless of the value of done valid OR done Short Circuit Evaluation When evaluating a logical expression PL SQL uses short circuit evaluation That is PL SQL stops evaluating the expression as soon as the result can be determined This allows you to write expressions that might otherwise cause an error
144. liabilities then use ratio analysis to compare the performance of two subsidiary companies DECLARE YPE FiguresRec IS RECORD cash REAL notes REAL subl_figs FiguresRec sub2_figs FiguresRec FUNCTION acid_test figs FiguresRec RETURN REAL IS BEGIN SELECT cash notes INTO subl_figs FROM assets liabilities WHERE assets sub 1 AND liabilities sub 1 SELECT cash notes INTO sub2_figs FROM assets liabilities WHERE assets sub 2 AND liabilities sub 2 IF acid_test subl_figs gt acid_test sub2_figs THEN z o Collections and Records 4 35 Manipulating Records Notice how easy it is to pass the collected figures to the function acid_test which computes a financial ratio In SQL Plus suppose you define object type Passenger as follows SQL gt CREATE TYPE Passenger AS OBJECT 2 flight_no NUMBER 3 3 name VARCHAR2 20 4 seat CHAR 5 Next you define VARRAY type Passengert List which stores Passenger objects SQL gt CREATE TYP PassengerList AS VARRAY 300 OF Passenger Finally you create relational table flights which has a column of type PassengerList as follows SQL gt CREATE TABLE flights 2 flight_no BER 3 gate CHAR 5 departure CHAR 15 arrival CHAR 15 passengers PassengerList
145. missing unknown or inapplicable value Remember Boolean literals are values not strings For example TRUE is no less a value than the number 25 2 8 PL SQL User s Guide and Reference Lexical Units Comments The PL SQL compiler ignores comments but you should not Adding comments to your program promotes readability and aids understanding Generally you use comments to describe the purpose and use of each code segment PL SQL supports two comment styles single line and multi line Single Line Single line comments begin with a double hyphen anywhere on a line and extend to the end of the line A few examples follow begin processing SELECT sal INTO salary FROM emp get current salary WHERE empno emp_id bonus salary 0 15 compute bonus amount Notice that comments can appear within a statement at the end of a line While testing or debugging a program you might want to disable a line of code The following example shows how you can comment out the line DELETE FROM emp WHERE comm IS NULL Multi line Multi line comments begin with a slash asterisk end with an asterisk slash and can span multiple lines Some examples follow BEGIN Compute a 15 bonus for top rated employees IF rating gt 90 THEN bonus salary 0 15 bonus is based on salary ELSE bonus 0 END If T
146. money withdraw money and return balance First we write the object type specification as follows CRI y EATE acc balance sta TYE t_number INTE GER 5 tus ER PROC EDU E REAL VARCHAR2 ER PROCEDURE ER PROCEDURE R PROCEDURE ER PROCEDUI R FUNCTIO ETURN REAL B B B EMB B B RI 10 open close deposit E withdraw curr_bal amount IN RI verify_acct E Bank_Account AS OBJECT num num IN INT EGER EGER amount OUT REAL num IN INT E R amount IN REAL num IN IN EGER amount IN REAL SELF IN OU EGER Bank_Account num IN INT Then we write the object type body as follows CREATE TYPE BODY Bank_Account AS MEMBER PROCEDURE open amount IN REAL IS open account with initial deposit BEGIN IF NOT amount gt 0 THEN RAISE_APPLICATION_ERROR 20104 bad amount END IF SELECT acct_sequence NEXTVAL INTO acct_number FROM dual status open balance amount END open EMBER PROCEDURE verify_acct num IN INTEGER IS check for wrong account number or closed account BEGIN IF num lt gt acct_number THEN RA
147. named past_due D ECLARE past_due EXCEPTION 6 6 PL SQL User s Guide and Reference E User Defined Exceptions Scope Rules Exception and variable declarations are similar But remember an exception is an error condition not a data item Unlike variables exceptions cannot appear in assignment statements or SQL statements However the same scope rules apply to variables and exceptions You cannot declare an exception twice in the same block You can however declare the same exception in two different blocks Exceptions declared in a block are considered local to that block and global to all its sub blocks Because a block can reference only local or global exceptions enclosing blocks cannot reference exceptions declared in a sub block If you redeclare a global exception in a sub block the local declaration prevails So the sub block cannot reference the global exception unless it was declared ina labeled block in which case the following syntax is valid block_label exception_name The next example illustrates the scope rules DECLARE past_due EXCEPTION acct_num NUMBER BEGI DECLARE sub block begins past_due EXCEPTION this declaration prevails acct_num NUMBER BEGIN IF THEN RAISE past_due this is not handled END IF END sub block ends EXCE
148. num2_cur INTO num2 XIT WHEN muml1_curSNOTFOUND OR mum2_curSNOTFOUND pair_num pair_num 1 INSERT INTO sum_tab VALUES pair_num numl num2 END LOOP CLOSE numl_cur CLOSE num2_cur END In the following example you use ISOPEN to make a decision IF NOT emp_cur SISOPEN THEN OPEN emp_cur END IF FETCH emp_cur INTO emp_rec The following PL SQL block uses SROWCOUNT to fetch the names and salaries of the five highest paid employees available online in file examp14 DECLARE CURSOR cl is 11 36 PL SQL User s Guide and Reference Cursor Attributes SELECT ename empno sal FROM emp ORDER BY sal DESC start with highest paid employ my_ename CHAR 10 my_empno NUMBER 4 my_sal NUMBER 7 2 BEGIN OPEN cl LOOP FETCH cl INTO my_ename my_empno my_sal EXIT WHEN c1SROWCOUNT gt 5 OR c1 SNOTFOUND INSERT INTO temp VALUES my_sal my_empno my_ename In the final example you use SROWCOUNT to raise an exception if an unexpectedly high number of rows is deleted DELETE FROM accts WHERE status BAD DEBT IF SOLSROWCOUNT gt 10 THEN RAISE out_of_bounds D IF E Z Related Topics Cursors Cursor Variables Language Elements 11 37 Cursor Variables
149. of an expression to a specific element in a collection using the syntax collection name subscript expression where expression yields a value of the type specified for elements in the collection type definition If subscript is null or not convertible to an integer PL SQL raises the exception VALUE_ERROR If the collection is atomically null PL SQL raises COLLECTION_IS_NULL Some examples follow DECLARE YPE NumList IS TABLE OF INTEGER nums NumList NumList 10 20 30 ints NumList BEGIN nums 1 TRUNC high low nums 3 nums 1 nums 2 ASCIT B Assume that execution continues despite the raised exception nums A 40 raises VALUE_ERROR ints 1 15 raises COLLECTION_IS_NULL Comparing Whole Collections Collections can be atomically null so they can be tested for nullity as the following example shows DECLARE YPE Staff IS TABLE OF Employee members Staff BEGIN IF members IS NULL THEN condition yields TRUE se Collections and Records 4 13 Manipulating Collections However collections cannot be compared for equality or inequality For instance the following IF condition is illegal DECLARE YPE Clientele IS TABLE OF Customer groupl Clientele Clientele group2 Clientele Clientele
150. or braces An ellipsis shows that the preceding syntactic element can be repeated Lower case denotes a syntactic element for which you must substitute a literal identifier or construct whichever is appropriate Upper case denotes PL SQL keywords which must be spelled as shown but can be entered in lower or mixed case Punctuation other than brackets braces vertical bars and ellipses must be entered as shown xix Sample Database Tables Most programming examples in this guide use two sample database tables named dept and emp Their definitions follow CREATE TABLE dept deptno NUMBER 2 NOT NULL dname VARCHAR2 14 loc VARCHAR2 13 CREATE TABLE emp empno UMBER 4 NOT NULL ename VARCHARZ2 10 job VARCHAR2 9 mgr UMBER 4 hiredate DATE sal NUMBER 7 2 comm UMBER 7 2 deptno UMBER 2 Sample Data Respectively the dept and emp tables contain the following rows of data DEPTNO DNAME LOC 10 ACCOUNTING NEW YORK 20 RESEARCH DALLAS 30 SALES CHICAGO 40 OPERATIONS BOSTON PNO ENAME JOB MGR HIREDATE SAL COMM DEPTNO 7369 SMITH CLERK 7902 17 DEC 80 800 20 7499 ALLEN SALESMAN 7698 20 FEB 81 1600 300 30 7521 WARD SALESMAN 7698 22 FEB 81 1250 500 30 7566 JONES MANAGER 7839 0
151. or anonymous blocks With a package the best solution is to divide it into smaller packages With a block the best solution is to redefine it as a series of subprograms which can be stored in the database For more information see Chapter 7 Another solution is to break the block into two sub blocks Consider the SOL Plus script below Before the first block terminates it inserts any data the second block needs into a database table called t emp When the second block starts executing it selects the data from t emp This approximates the passing of parameters from one procedure to another DECLARE mode NUMBER median NUMBER BEGIN INSERT INTO temp coll col2 col3 VALUES mode median blockA D Us a ECLARE mode NUMBER median NUMBER BEGI SELECT coll col2 INTO mode median FROM temp WHERE col3 blockA END The previous method works unless you must re execute the first block while the second block is still executing or unless two or more users must run the script concurrently 5 60 PL SQL User s Guide and Reference Processing Transactions Alternatively you can embed the blocks in a host language such as C COBOL or FORTRAN That way you can re execute the first block using flow of control statements Also you can store data in global host variables instead of a database table In the following example you embed two blo
152. or assigns the current transaction to a specified rollback segment Read only transactions are useful for running multiple queries against one or more tables while other users update the same tables For more information see Using SET TRANSACTION on page 5 50 set_transaction_statement READ ONLY S READ WRITE SET TRANSACTION SERIALIZABLE HG ISOLATION LEVEL a READ COMMITTED USE ROLLBACK SEGMENT rollback_segment_name Keyword and Parameter Description READ ONLY This clause establishes the current transaction as read only If a transaction is set to READ ONLY subsequent queries see only changes committed before the transaction began The use of READ ONLY does not affect other users or transactions READ WRITE This clause establishes the current transaction as read write The use of READ WRITE does not affect other users or transactions If the transaction executes a data manipulation statement Oracle assigns the transaction to a rollback segment ISOLATION LEVEL This clause specifies how transactions that modify the database are handled When you specify SERIALIZABLE if a serializable transaction tries to execute a SOL data manipulation statement that modifies any table already modified by an uncommitted transaction the statement fails 11 142 PL SQL User s Guide and Reference SET TRANSACTION Statement Usage Notes Example Related Topics To enable SERIALIZABLE
153. parameter modes define the behavior of formal parameters An IN parameter lets you pass values to the subprogram being called An OUT parameter lets you return values to the caller of the subprogram An IN OUT parameter lets you pass initial values to the subprogram being called and return updated values to the caller datatype This is a type specifier For the syntax of dat at ype see Constants and Variables on page 11 29 Y DEFAULT This operator or keyword allows you to initialize IN parameters to default values 11 122 PL SQL User s Guide and Reference Procedures Usage Notes expression This is an arbitrarily complex combination of variables constants literals operators and function calls The simplest expression consists of a single variable When the declaration is elaborated the value of expression is assigned to the parameter The value and the parameter must have compatible datatypes type_definition This specifies a user defined datatype For the syntax of type_definition see Blocks on page 11 7 item_declaration This declares a program object For the syntax of item_declaration see Blocks on page 11 7 function_declaration This construct declares a function For the syntax of function_declaration see Functions on page 11 79 procedure_decliaration This construct declares a procedure For the syntax of procedure_declaration see Procedures on page 11 121
154. price quantity of tickets on hand and receipts It also needs methods for the following operations purchase ticket take inventory replenish stock and collect receipts For receipts we use a three element varray Elements 1 2 and 3 record the ticket receipts for movies 1 2 and 3 respectively To declare a varray attribute we must first define its type as follows CREATE TYPE RealArray AS VARRAY 3 OF REAL Now we can write our object type specification as follows CREATE TYPE Ticket_Booth AS OBJECT price REAL aty_on hand INTEGER receipts RealArray EMBER PROCEDURE initialize EMBER PROCEDURE purchase movie INTEGER amount REAL change OUT REAL EMBER FUNCTION inventory RETURN INTEGER EMBER PROCEDURE replenish quantity INTEGER EMBER PROCEDURE collect movie INTEGER amount OUT REAL ED ED y Finally we write the object type body as follows CREATE TYPE BODY Ticket_Booth AS MEMBER PROCEDURE initialize IS BEGI price 2 50 aty_on_ hand 5000 provide initial stock of tickets Call constructor for varray and set elements 1 3 to zero receipts RealArray 0 0 0 END initialize Object Types 9 17 Defining Object Types ME
155. readable p code at compile time early binding At run time the PL SQL engine simply executes the p code Some Limitations However this design imposes some limitations For example the p code includes references to schema objects such as tables and stored procedures The PL SQL compiler can resolve such references only if the schema objects are known at compile time In the following example the compiler cannot process the procedure because the table is undefined until the procedure is executed at run time CREATE PROCEDURE create_table AS BEGIN CREATE TABLE dept deptno NUMBER 2 illegal END In the next example the compiler cannot bind the table reference in the DROP TABLE statement because the table name is unknown until the procedure is executed CREATE PROCEDURE drop_table table_name IN VARCHAR2 AS BEGIN DROP TABLE table_name illegal END Overcoming the Limitations However the package DBMS_SQL which is supplied with Oracle allows PL SQL to execute SQL data definition and data manipulation statements dynamically at run time For example when called the following stored procedure drops a specified database table CREATE PROCEDURE drop table table_name IN VARCHAR2 AS cid INTEGER 5 8 PL SQL User s Guide and Reference Managing Cursors BEGIN Open new cursor and return cur
156. routine raises a user defined exception and returns a user defined error message The C prototype for this function follows int OCIExtProcRaiseExcpWithMsg OCIExtProcContext with_context size_t error_number text error_message size_t len The parameters with_context error_number and error_message are the context pointer Oracle error number and error message text The parameter len stores the length of the error message If the message is a null terminated string len is zero The return values OCIEXTPROC_SUCCESS and OCIEXTPROC_ERROR indicate success or failure In the previous example you registered external procedure divide as follows SQL gt CREATE PROCEDURE divide 2 dividend IN BINARY_INTEGER 3 divisor IN BINARY_INTEGER 4 result OUT FLOAT 5 AS EXTERNAL 6 NAME divide z LIBRARY mathlib 8 WITH CONTEXT 9 PARAMETERS 10 CONTEXT 11 dividend int T2 divisor int 13 result float 10 20 PL SQL User s Guide and Reference Using Service Routines In the example below you use a different version of divide With this version if the divisor is zero divide uses OCIExtProcRaiseExcpWithMsg to raise a user defined exception void divide ctx dividend divisor result OCIExtProcContext ctx int dividend int divisor float result Check for zero divisor if divisor int 0 Rai
157. row in an object table For example to return a result set of Person objects you use VALUE as follows BEGIN INSERT INTO employees SELECT VALUE p FROM persons p WHERE p last_name LIKE Smith In the next example you use VALUE to return a specific Person object DECLARE pl Person p2 Person BEGIN SELECT VALUE p INTO pl FROM persons p WHERE p last_name Kroll 9 32 PL SQL User s Guide and Reference Manipulating Objects At this point p1 holds a local Person object which is a copy of the stored object whose last name is Kroll and p2 holds another local Person object which is a copy of p1 As the following example shows you can use these variables to access and update the objects they hold BEGIN pl last_name pl last_name Jr Now the local Person object held by p1 has the last name Kroll Jr Using Operator REF You can retrieve refs using the operator REF which like VALUE takes as its argument a correlation variable In the following example you retrieve one or more refs to Person objects then insert the refs into table person_refs BEGIN INSERT INTO person_refs SELECT REF p FROM persons p WHERE p last_name LIKE Smith In the next example you retrieve a ref and attribute at the same time DECLARE p_ref
158. rows or a SELECT statement returned no rows Otherwise 3NOTFOUND yields FALSE GI 5 42 PL SQL User s Guide and Reference E if an INTO Using Cursor Attributes ROWCOUNT SROWCOUNT yields the number of rows affected by an INSERT UPDATE or DELETE statement or returned by a SELECT INTO statement SROWCOUNT yields 0 if an INSERT UPDATE or DELETE statement affected no rows or a SELECT INTO statement returned no rows In the following example you use 4ROWCOUNT to take action if more than ten rows have been deleted DELETE FROM emp WHERE IF SOLSROWCOUNT gt 10 THEN more than 10 rows were deleted END IF If a SELECT INTO statement returns more than one row PL SQL raises the predefined exception TOO_MANY_ROWS and SROWCOUNT yields 1 not the actual number of rows that satisfy the query Guidelines The values of the cursor attributes always refer to the most recently executed SQL statement wherever that statement is It might be in a different scope for example in a sub block So if you want to save an attribute value for later use assign it to a Boolean variable immediately In the following example relying on the IF condition is dangerous because the procedure check_status might have changed the value of 3NOTFOUND UPDATE parts SET quantity quantity 1 WHERE partno part_id
159. s Guide and Reference Defining and Declaring Collections a Oracle stores varray data in line in the same tablespace But Oracle stores nested table data out of line in a store table which is a system generated database table associated with the nested table a When stored in the database varrays retain their ordering and subscripts but nested tables do not Which collection type should you use That depends on your wants and the size of the collection A varray is stored as an opaque object whereas a nested table is stored in a storage table with every element mapped to a row in the storage table So if you want efficient queries use nested tables If you want to retrieve entire collections as a whole use varrays However when collections get very large it becomes impractical to retrieve more than subsets So varrays are better suited for small collections Defining and Declaring Collections To create collections you define a collection type then declare collections of that type You can define TABLE and VARRAY types in the declarative part of any PL SQL block subprogram or package For nested tables you use the syntax TYPE type_name IS TABLE OF element_type NOT NULL and for varrays you use the following syntax TYPE type_name IS VARRAY VARYING ARRAY size_limit OF element_type NOT NULL where t ype_name is a type specifier used later to declare collections size_limit is a positive integ
160. s Guide and Reference Using Collection Methods You can use LIMIT wherever an integer expression is allowed In the following example you use LIMIT to determine if you can add 20 more elements to varray projects IF projects COUNT 20 lt projects LIMIT THEN add 20 more elements Using FIRST and LAST FIRST and LAST return the first and last smallest and largest index numbers in a collection If the collection is empty FIRST and LAST return NULL If the collection contains only one element FIRST and LAST return the same index number as the following example shows IF courses FIRST courses LAST THEN only one element The next example shows that you can use FIRST and LAST to specify the lower and upper bounds of a loop range provided each element in that range exists FOR i IN courses FIRST courses LAST LOOP In fact you can use FIRST or LAST wherever an integer expression is allowed In the following example you use FIRST to initialize a loop counter i courses FIRST WHILE i IS NOT NULL LOOP For varrays FIRST always returns 1 and LAST always equals COUNT For nested tables FIRST normally returns 1 But if you delete elements from the beginning of a nested table FIRST returns a number larger than 1 Also for nested tables LAST normally equals COUNT But if you delete elements from the middle of a nested table LAST becomes larger than COUNT When scanning elements FIRST and
161. scope cursor_variable_name This identifies a PL SQL cursor variable or parameter previously declared within the current scope host_cursor_variable_ name This identifies a cursor variable declared in a PL SQL host environment and passed to PL SQL as a bind variable The datatype of the host cursor variable is compatible with the return type of any PL SQL cursor variable Host variables must be prefixed with a colon variable_namel variable_name This identifies a list of previously declared scalar variables into which column values are fetched For each column value returned by the query associated with the cursor or cursor variable there must be a corresponding type compatible variable in the list 11 76 PL SQL User s Guide and Reference FETCH Statement Usage Notes record_name This identifies a user defined or SROWTYPE record into which rows of values are fetched For each column value returned by the query associated with the cursor or cursor variable there must be a corresponding type compatible field in the record You must use either a cursor FOR loop or the FETCH statement to process a multi row query Any variables in the WHERE clause of the query are evaluated only when the cursor or cursor variable is opened To change the result set or the values of variables in the query you must reopen the cursor or cursor variable with the variables set to their new values To reopen a curso
162. side PL SOL execution fewer round trips are needed which increases throughput In the following example you use the array interface to fetch employee names from the emp database table into an index by table DECLARE src_cur PLS_INTEGER num_rows PLS_INTEGER emp_tbl DBMS_SOL VARCHAR2_TABLE BEGIN Interaction with Oracle 5 57 Processing Transactions Open and parse cursor src_cur DBMS _SQL OPEN_CURSOR DBMS_SOL PARSE src_cur SELECT ename FROM emp DBMS _SOL V7 Define select item 1 as an array fetch into emp_tbl Rows will be fetched 10 at a time starting at index 1 DBMS_SOL DEFINE_ARRAY src_cur 1 emp tbl Execute the cursor num_rows DBMS_SOL EXECUTE src_cur Fetch all rows LOOP num_rows DBMS SOL FETCH_ROWS src_cur DBMS_SOL COLUMN_VALUE IF num_rows lt 10 THEN EXIT END IF END LOOP 10 1 src_cur 1 emp tbl at this point the data is available in emp_tbl 1l emp_tbl COUNT END For more information see Oracle8 Application Developer s Guide Use the PLS_INTEGER Datatype When you need to declare an integer variable u which is the most efficient numeric type That is se the datatype PLS_INTEGER because PLS_INTEGER values require less storage than INTEGER or NUMBER values whi
163. statements but not in SQL statements Explicit Cursor Attributes Explicit cursor attributes return information about the execution of a multi row query When an explicit cursor or a cursor variable is opened the rows that satisfy the associated query are identified and form the result set Rows are fetched from the result set one at a time FOUND After a cursor or cursor variable is opened but before the first fetch sF OUND yields NULL Thereafter it yields TRUE if the last fetch returned a row or FALS fetch failed to return a row In the following example you use FOUND to select an action LOOP FETCH cl INTO my_ename my_sal my_hiredate IF clSFOUND THEN fetch succeeded EXIT END IF END LOOP ELSE fetch failed so exit loop E if the last If a cursor or cursor variable is not open referencing it with SFOUND raises the predefined exception INVALID_CURSOR ISOPEN SISOPEN yields TRUE if its cursor or cursor variable is open otherwise yields FALSE In the following example you use ISOPEN to select an action IF clSISOPEN THEN cursor is open ELSE cursor is closed so open it OPEN cl END IF 5 38 PL SQL User s Guide and Reference 152 zZ ISOPI Using Cursor Attributes NOTFOUND SNOTFOUND is the logical opposite of FOUND SNOTFOUND yields FALSE if the last fetch returned a row or TRUE if the last
164. symbol XYZ In this example a subquery supplies values to the INSERT statement If earnings are zero the function DECODE returns a null Otherwise DECODE returns the price to earnings ratio Advantages of Exceptions Using exceptions for error handling has several advantages Without exception handling every time you issue a command you must check for execution errors as follows BEGI SELECT check for no data found error check for no data found error SELECT Check for no data found error Error processing is not clearly separated from normal processing nor is it robust If you neglect to code a check the error goes undetected and is likely to cause other seemingly unrelated errors With exceptions you can handle errors conveniently without the need to code multiple checks as follows BEGI SELEC SELEC SELEC EA EA EXCEPTION WHEN NO DATA FOUND THEN catches all no data found errors Exceptions improve readability by letting you isolate error handling routines The primary algorithm is not obscured by error recovery algorithms Exceptions also improve reliability You need not worry about checking for an error at every point it might occur Just add an exception handler to your PL SQL block If the exception is ever raised in that bloc
165. that Address is the datatype of attribute home_address in object type Student If sisa Student object you access the value of its zip_code attribute as follows s home_address zip_code Calling Constructors and Methods Calls to a constructor are allowed wherever function calls are allowed Like all functions a constructor is called as part of an expression as the following example shows DECLARE rl Rational Rational 2 3 FUNCTION average x Rational y Rational RETURN Rational IS BEGIN END BEGI rl average Rational 3 4 Rational 7 11 IF Rational 5 8 gt r1 THEN END 1F END 9 26 PL SQL User s Guide and Reference Calling Constructors and Methods Passing Parameters to a Constructor When you pass parameters to a constructor the call assigns initial values to the attributes of the object being instantiated You must supply a parameter for every attribute because unlike constants and variables attributes cannot have DEFAULT clauses As the following example shows the nth parameter assigns a value to the nth attribute DECLARE r Rational BEGIN r Rational 5 6 assign 5 to num 6 to den now r is 5 6 You can call a constructor using named notation instead of positional notation as the following example shows BEGIN r Rational den gt 6 num gt 5 assign 5 to num 6 to den Calling Methods Like pack
166. the emp database table DECLARE YPE EmpTabTyp IS TABLE OF empSROWTYP INDEX BY BINARY_INTEGER emp_tab EmpTabTyp BEGI Retrieve employee record SELECT INTO emp_tab 7468 WHERE empno 7468 El When defining a VARRAY type you must specify its maximum size In the following example you define a type that stores up to 366 dates DECLARE YPE Calendar IS VARRAY 366 OF DATE 4 6 PL SQL User s Guide and Reference Defining and Declaring Collections To specify the element type you can use TYPE which provides the datatype of a variable or database column Also you can use SROWTYPE which provides the rowtype of a cursor or database table Two examples follow DECLARE YPE EmpList IS TABLE OF emp enamesSTYPE based on column CURSOR cl IS SELECT FROM dept YPE DeptFile IS VARRAY 20 OF c1SROWTYPE based on cursor In the next example you use a RECORD type to specify the element type DECLARE YPE Entry IS RECORD term VARCHAR2 20 meaning VARCHAR2 200 YPE Glossary IS VARRAY 250 OF Entry In the final example you impose a NOT NULL constraint on the element type DECLARE YPE EmpList IS TABLE OF emp empno TYPE NOT NULL An initialization clause is not required or al
167. the library dynamically then calls the routine as if it were a PL SQL subprogram 1 12 PL SQL User s Guide and Reference Main Features Typically external procedures are used to interface with embedded systems solve scientific and engineering problems analyze data or control real time devices and processes In the following example you write a PL SQL stand alone function named interp that registers the C routine c_interp as an external function CREATE FUNCTION interp find the value of y at x degrees using Lagrange interpolation x FLOAT y FLOAT RETURN FLOAT AS EXTERNAL LIBRARY mathlib AME c_interp ANGUAGE C Packages PL SQL lets you bundle logically related types variables cursors and subprograms into a package Each package is easy to understand and the interfaces between packages are simple clear and well defined This aids application development Packages usually have two parts a specification and a body The specification is the interface to your applications it declares the types constants variables exceptions cursors and subprograms available for use The body defines cursors and subprograms and so implements the specification In the following example you package two employment procedures CREATE PACKAGE emp actions AS package specification PROCEDURE hire employee empno NUMBER ename CHAR
168. to declare nested tables and variable size arrays a the LOB large object datatypes BFILE BLOB CLOB and NCLOB which let you manipulate blocks of unstructured data up to four gigabytes in size extended National Language Support NLS including national character sets and the datatypes NCHAR and NVARCHAR2 which store NLS data For more information see Appendix A Note This guide applies to Oracle8 and the Oracle8 Enterprise Edition They have the same basic features However several advanced features are available only with the Enterprise Edition and some of these are optional For example to use object types you must have the Enterprise Edition and the Objects Option To find out which features are available to you see Getting to Know Oracle8 and the Oracle8 Enterprise Edition How This Guide Is Organized The PL SQL User s Guide and Reference has 11 chapters and 6 appendices Chapters 1 through 10 introduce you to PL SQL and shows you how to use its many features Chapter 11 serves as a reference to PL SQL commands syntax and semantics Appendices A through F provide a survey of new features sample programs supplementary technical information and a list of reserved words Chapter 1 Overview This chapter surveys the main features of PL SQL and points out the advantages they offer It also acquaints you with the basic concepts behind PL SQL and the general appearance of PL SQL programs Chapter 2 Fundamenta
169. transaction to READ ONLY subsequent queries see only changes committed before the transaction began The use of READ ONLY does not affect other users or transactions Restrictions Only the SELECT INTO OPEN FETCH CLOSE LOCK TABLE COMMIT and ROLLBACK statements are allowed in a read only transaction Also queries cannot be FOR UPDATE 5 50 PL SQL User s Guide and Reference Processing Transactions Overriding Default Locking By default Oracle locks data structures for you automatically However you can request specific data locks on rows or tables when it is to your advantage to override default locking Explicit locking lets you share or deny access to a table for the duration of a transaction With the SELECT FOR UPDATE statement you can explicitly lock specific rows of a table to make sure they do not change before an update or delete is executed However Oracle automatically obtains row level locks at update or delete time So use the FOR UPDATE clause only if you want to lock the rows before the update or delete You can explicitly lock entire tables using the LOCK TABLE statement Using FOR UPDATE When you declare a cursor that will be referenced in the CURRENT OF clause of an UPDATE or DELETE statement you must use the FOR UPDATE clause to acquire exclusive row locks An example follows DECLARE CURSOR cl IS SELECT empno sal FROM
170. use integer literals The maximum precision of a NUMBER value is 38 decimal digits If you do not specify precision it defaults to 38 or the maximum supported by your system whichever is less 2 12 PL SQL User s Guide and Reference Datatypes Scale which can range from 84 to 127 determines where rounding occurs For instance a scale of 2 rounds to the nearest hundredth 3 456 becomes 3 46 A negative scale rounds to the left of the decimal point For example a scale of 3 rounds to the nearest thousand 3456 becomes 3000 A scale of 0 rounds to the nearest whole number If you do not specify scale it defaults to 0 NUMBER Subtypes You can use the following NUMBER subtypes for compatibility with ANSI ISO and IBM types or when you want a more descriptive name DEC DECIMAL DOUBLE PRECISION NTEGER EAL ALLINT J I NUMERIC R S Use the subtypes DEC DECIMAL and NUMERIC to declare fixed point numbers with a maximum precision of 38 decimal digits Use the subtypes DOUBLE PRECISION and FLOAT to declare floating point numbers with a maximum precision of 126 binary digits which is roughly equivalent to 38 decimal digits Or use the subtype REAL to declare floating point numbers with a maximum precision of 63 binary digits which is roughly equivalent to 18 decimal digits Use the subtypes INTEGER INT and SMALLINT to declare integers with a maximum precision o
171. use its cursor and raise its exception When you create the package it is stored in an Oracle database for general use 8 8 PL SQL User s Guide and Reference Some Examples CREATE ie NI PACKAGE emp actions AS Declare externally visible types cursor exception YPE EmpRecTyp IS YPE DeptRecTyp IS CURSOR desc_salary salary_missing EXC RECORD emp_id INTEGER salary REAL RECORD dept_id INTEGER location VARCHARZ2 RETURN EmpRecTyp PTION Declare externally callable subprograms FUNCTION hire_employee ename VARCHAR2 job VARCHAR2 mgr NUMBER sal NUMBER comm NUMBER deptno NUMBER R ETURN INTEGER PROCEDURE fire employee emp_id INTEGER PROC FUNCTION nth_highes D emp_actions CRI KATE EDURE raise_salary emp_id INTEGER increase NUMBER t_salary n INTEGER RETURN EmpRecTyp PACKAGE BODY emp_actions AS number_hired INTEG ER visible only in this package Fully define cursor specified in package CURSOR desc_salary RETURN EmpRecTyp IS SELECT empno sal FROM emp ORDER BY sal DESC Fully define subprograms specified in package FUNCTION hire_employee ETURN INTEGER IS ER en
172. use the package follow the instructions in dbgextp sql Your Oracle account must have EXECUTE privileges on the package and CREATE LIBRARY privileges Note DEBUG_EXTPROC works only on platforms with debuggers that can attach to a running process Demo Program Also in the PL SQL demo directory is the script extproc sql which demonstrates the calling of an external procedure The companion file extproc c contains the C source code for the external procedure To run the demo follow the instructions in extproc sql You must use the SCOTT TIGER account which must have CREATE LIBRARY privileges 10 24 PL SQL User s Guide and Reference Restrictions on External Procedures Guidelines for External Procedures In future releases extproc might be a multi threaded process So be sure to write thread safe external procedures That way they will continue to run properly if extproc becomes multi threaded In particular avoid using static variables which can be shared by routines running in separate threads Otherwise you might get unexpected results For help in creating a dynamic link library look in the RDBMS subdirectory public where a template makefile can be found When calling external procedures never write to IN parameters or overflow the capacity of OUT parameters PL SQL does no runtime checks for these error conditions Likewise never read an OUT param
173. value of lexicon 1 also changes the value of word_list 1 PL SQL lets you overload subprogram names That is you can use the same name for several different subprograms as long as their formal parameters differ in number order or datatype family Suppose you want to initialize the first n rows in two index by tables that were declared as follows DECLARE YPE DateTabTyp IS TABLE OF DATE INDEX BY BINARY_INTEGER YPE RealTabTyp IS TABLE OF REAL INDEX BY BINARY_INTEGER hiredate_tab DateTabTyp sal_tab RealTabTyp You might write the following procedure to initialize the index by table named hiredate_tab PROCEDURE initialize tab OUT DateTabTyp n INTEGER IS BEGI FOR i IN 1 n LOOP tab i SYSDATE END LOOP END initialize se 7 18 PL SQL User s Guide and Reference Overloading Restrictions And you might write the next procedure to initialize the index by table named sal_tab PROCEDURE initialize tab OUT RealTabTyp n INTEGER IS BEGI FOR i IN 1 n LOOP tab i 0 0 END LOOP END initialize Because the processing in these two procedures is the same it is logical to give them the same name You can place the two overloaded initialize procedures in the same block subprogram or package PL SQL determines which of the two procedures i
174. visible the compiler generates a not declared error because an insufficient privileges error would acknowledge the existence of the object which is a security violation a Ifthe compiler fails to find a basis by searching for schema objects it generates a not declared error a Ifthe compiler finds a basis it tries to resolve the complete reference depending on how the basis was resolved If it fails to resolve the complete reference the compiler generates an error Name Resolution E 7 Understanding Capture Understanding Capture Inner Capture When a declaration or type definition in another scope prevents the compiler from resolving a reference correctly that declaration or definition is said to capture the reference Usually this is the result of migration or schema evolution There are three kinds of capture inner same scope and outer Inner and same scope capture apply only in SQL scope An inner capture occurs when a name in an inner scope that once resolved to an entity in an outer scope either a gets resolved to an entity in an inner scope or causes an error because the basis of the identifier chain got captured in an inner scope and the complete reference could not be resolved If the situation was resolved without error in an inner scope the capture might occur unbeknown to you Consider the following example CREATE TABLE tabl coll NUMBER col2 NUMBER CREATE
175. which does not yet exist CREATE TYPE Employee AS OBJECT name VARCHAR2 20 dept REF Department illegal CREATE TYPE Department AS OBJECT number INTEGER manager Employee y Switching the CREATE TYPE statements does not help because the object types are mutually dependent that is one depends on the other through a ref To solve this problem you use a special CREATE TYPE statement called a forward type definition which lets you define mutually dependent object types To debug the last example simply precede it with the following statement CREATE TYPE Department forward type definition at this point Department is an incomplete object type The object type created by a forward type definition is called an incomplete object type because until it is defined fully it has no attributes or methods An impure incomplete object type has attributes but compiles with semantic not syntactic errors because it refers to an undefined type For example the following CREATE TYPE statement compiles with a semantic error because object type Address is undefined CREATE TYPE Customer AS OBJECT id UMBER name VARCHAR2 20 9 30 PL SQL User s Guide and Reference Manipulating Objects addr Address not yet defined phone VARCHAR2 15 3 This allows you t
176. y ans INTEGER BEGI IF y lt x AND x MOD y 0 THEN ans y ELSIF x lt y THEN ans gcd y x recursive call F SE ans gcd y x MOD y recursive call END IF RETURN ans END Object Types 9 21 Defining Object Types Then we write the object type body as follows CREATE TYPE BODY Rational AS MAP MEMBER FUNCTION convert RETURN REAL IS convert rational number to real number BEGIN RETURN num den END convert MEMBER PROCEDURE normalize IS reduce fraction num den to lowest terms g INTEGER BEGIN g gcd num den num num g den den g END normalize MEMBER FUNCTION reciprocal RETURN Rational IS return reciprocal of num den BEGIN RETURN Rational den num call constructor END reciprocal MEMBER FUNCTION plus x Rational RETURN Rational IS return sum of SELF x r Rational BEGIN r Rational num x den x num den den x den r normalize RETURN r END plus EMBER FUNCTION less x Rational RETURN Rational IS return difference of SELF x r Rational BEGIN r Rational num x den x num den den x den r normalize RETURN r ND less E MEMBER FUNCTION times x Rational RETURN Rational IS ret
177. yields TRUE the current loop or the loop labeled by label_name is exited immediately For the syntax of boolean_expression see Expressions on page 11 59 The EXIT statement can be used only inside a loop PL SQL allows you to code an infinite loop For example the following loop will never terminate normally WHILE TRUE LOOP END LOOP In such cases you must use an EXIT statement to exit the loop Language Elements 11 57 EXIT Statement If you use an EXIT statement to exit a cursor FOR loop prematurely the cursor is closed automatically The cursor is also closed automatically if an exception is raised inside the loop Examples The EXIT statement in the following example is illegal because you cannot exit from a block directly you can exit only from a loop DECLARE amount maximum BEGI UY R R UJ BEGIN IF amount gt maximum THEN EXIT illegal END IF END The following loop normally executes ten times but it will exit prematurely if there are less than ten rows to fetch FOR i IN 1 10 FETCH cl INTO emp_rec EXIT WHEN cl NOTFOUND total_comm total_comm emp_rec comm END LOOP The following example illustrates the use of loop labels lt lt outer gt gt FOR i IN 1 10 LOOP lt lt inner gt gt FOR j IN 1 100 LOOP EXIT outer WHEN exits both
178. you close the cursor variable emp_cv LOOP FETCH emp_cv INTO emp_rec EXIT WHEN emp_cv NOTFOUND process data record END LOOP Close cursor variable CLOSE emp_cv FETCH Statement OPEN Statement OPEN FOR Statement Language Elements 11 15 Collection Methods Collection Methods Syntax A collection method is a built in function or procedure that operates on collections and is called using dot notation The methods 1 EXISTS COUNT LIMIT FIRST LAST PRIOR NEXT EXTEND TRIM and DELE TE help generalize code make collections easier to use and make your applications easier to maintain EXISTS COUNT LIMIT FIRST LAST PRIOR appear as part of an expression EXT appear as a statement EXISTS PRIOR NEXT integer parameters For more information see page 4 21 collection_method_call END TRIM and DELET and NEXT are functions which E are procedures which TRIM EXTEND and DELETE take Using Collection Methods on collection_name ROO TRIM DEDO 11 16 PL SQL User s Guide and Reference Collection Methods Keyword and Parameter Description collection_name This identifies a nested table index by table or varray previously declared within the current scope COUNT COUNT returns the number of el
179. 0 7 How PL SQL Calls an External Procedure ccccccecccessesesseeseeseeseeeeeceeecneecesecnecaeeseeaecaeeeeeaseas 10 7 Environments Variables c2 ccss cstetedsciestetesesdessetven cet foactee canes E E E E e E E esas 10 8 Passing Parameters to an External Procedure ooooninnncninnnnnnonicnnnnonononononanononononononononononononononononos 10 9 Specifying Dataty pesimista dates a ra aeaoe EEE S Sana SESVETE 10 9 Using the PARAMETERS Clause sisii terbis soiin e nE oap rean e Enor EA RNa AANE eiai eai aE 10 12 Using the WITH CONTEXT ClaUSO ococonenoccocononononnnoconnnnncncnrnnnnnncanananonnnnaranannn isina se tesia aa 10 16 Using Service Routines eesriie iasaid aate td essa eis Enant iei iban ae carr arena carne nerararnonanarao 10 17 OCIExtProcAllocCallMemory se eesse eE Eriet E EE TAE E E TE e 10 17 OCIEXtProcRaiseEXGp oriire a E AE Sots A E ti 10 19 OCIExtProcRais eExepWithMsSg niera eae aa e A aR aaae Eta 10 20 OCIEXtProcGet ENV snn aeaa aAa E TE 10 21 Doing Call ckS coi aa it a E 10 22 Restrictions on Callbacks sessista ei ap eee Enie a eR anar e a Eiana 10 23 Debugging External Procedures oooocicinocionnnononncnnononocanananononononananononononononononononananononononananononenos 10 24 Using Package DEBUG_EXTPROC isitishe eisie areeni AE ro eo Kae Ne aE RaR EE Oa 10 24 11 Demo Pro gta an cacon biien vet vst scaveed cases Dada EE EAT ins 10 24 Guidelines for External Procedures cccccccesscsssessesssesseccesc
180. 00 number_processed INTEGER insufficient_funds EXCEPTION END trans_data The package t rans_data needs no body because types constants variables and exceptions do not have an underlying implementation Such packages let you define global variables usable by subprograms and database triggers that persist throughout a session Referencing Package Contents To reference the types items and subprograms declared within a package specification you use dot notation as follows package_name type_nam package_name item_nam package_name subprogram_name You can reference package contents from a database trigger a stored subprogram an Oracle Precompiler application an OCI application or an Oracle tool such as SQL Plus For example you might call the packaged procedure hire_employee from SQL Plus as follows SQL gt EXECUTE emp actions hire employee TATE CLERK 8 6 PL SQL User s Guide and Reference The Package Body In the example below you call the same procedure from an anonymous PL SQL block embedded in a Pro C program The actual parameters name and title are host variables EXEC SQL EXECUTE BEGIN emp_actions hire_employee name title Restrictions You cannot reference remote packaged variables directly or indirectly For example you cannot
181. 11 100 PL SQL User s Guide and Reference LOOP Statements Usage Notes Example Related Topics cu rsor_parameter_name This identifies a cursor parameter that is a variable declared as the formal parameter of a cursor A cursor parameter can appear in a query wherever a constant can appear The formal parameters of a cursor must be IN parameters For the syntax of cursor_parameter_declaration see Cursors on page 11 45 select_statement This is a query associated with an internal cursor unavailable to you Its syntax is like that of select_into_statement without the INTO clause See SELECT INTO Statement on page 11 139 PL SQL automatically declares opens fetches from and closes the internal cursor Because select_statement is not an independent statement the implicit SQL cursor does not apply to it You can use the EXIT WHEN statement to exit any loop prematurely If the Boolean expression in the WHEN clause yields TRUE the loop is exited immediately When you exit a cursor FOR loop the cursor is closed automatically even if you use an EXIT or GOTO statement to exit the loop prematurely The cursor is also closed automatically if an exception is raised inside the loop The following cursor FOR loop calculates a bonus then inserts the result into a database table DECLARE bonus REAL CURSOR cl IS SELECT empno sal comm FROM emp BEGIN FOR clrec IN cl LOOP bonus clrec sal 0 05
182. 11 74 PL SQL User s Guide and Reference External Procedures BEGIN g gcd a b call function IF g IN 2 4 8 THEN The following example uses the PARAMETERS clause to specify properties for the PL SQL formal parameters and function result CREATE FUNCTION parse x IN BINARY_INTEGER Y IN OUT CHAR RETURN CHAR AS EXTERNAL LIBRARY c_utils AME c_parse Hj ANGUAGE C CALLING STANDARD PASCAL PARAMETERS X stores value of x x INDICATOR stores null status of x Y stores value of y y LENGTH stores current length of y y MAXLEN stores maximum length of y RETURN INDICATOR RETURN The corresponding C prototype follows char c_parse int x short x_ind char y int y_len int y_maxlen short retind Related Topics Functions Procedures Language Elements 11 75 FETCH Statement FETCH Statement The FETCH statement retrieves rows of data one at a time from the result set of a multi row query The data is stored in variables or fields that correspond to the columns selected by the query For more information see Managing Cursors on page 5 9 Syntax fetch_statement PE gt variable_name SN gt 6 Keyword and Parameter Description cursor_name This identifies an explicit cursor previously declared within the current
183. 2 40 Syntax assignment_statement 00 collection_name x cursor_variable_name E host_cursor_variable_name 5 indicator_name ES host_variable_name attribute_name expression 3 object_name parameter_name field_name record_name variable_name x Keyword and Parameter Description collection_name This identifies a nested table index by table or varray previously declared within the current scope Language Elements 11 3 Assignment Statement cursor_variable_name This identifies a PL SQL cursor variable previously declared within the current scope Only the value of another cursor variable can be assigned to a cursor variable host_cursor_variable_ name This identifies a cursor variable declared in a PL SQL host environment and passed to PL SQL as a bind variable The datatype of the host cursor variable is compatible with the return type of any PL SQL cursor variable Host variables must be prefixed with a colon host_variable_name This identifies a variable declared in a PL SQL host environment and passed to PL SQL as a bind variable Host variables must be prefixed with a colon object_name This identifies an object instance of an object type previously declared within the current scope indicator_name This identifies an indicator variable declared in a PL SQL host environment and passed to PL SQL Indicator variables must be prefixed with a colon An
184. 2 APR 81 2975 20 7654 MARTIN SALESMAN 7698 28 SEP 81 1250 1400 30 7698 BLAKE MANAGER 7839 01 MAY 81 2850 30 7782 CLARK MANAGER 7839 09 JUN 81 2450 10 7788 SCOTT ANALYST 7566 19 APR 87 3000 20 7839 KING PRESIDENT 17 NOV 81 5000 10 7844 TURNER SALESMAN 7698 08 SEP 81 1500 30 7876 ADAMS CLERK 7788 23 MAY 87 1100 20 7900 JAMES CLERK 7698 03 DEC 81 950 30 7902 FORD ANALYST 7566 03 DEC 81 3000 20 7934 MILLER CLERK 7782 23 JAN 82 1300 10 XX Your Comments Are Welcome We appreciate your comments and suggestions In fact your opinions are the most important feedback we receive We encourage you to use the Reader s Comment Form at the front of this guide You can also send comments to us by email infodev us oracle com fax 650 506 7200 Attn Server Technologies Documentation Manager letter Server Technologies Documentation Manager Oracle Corporation 500 Oracle Parkway Redwood Shores CA 94065 USA xxi xxii 1 Overview The limits of my language mean the limits of my world Ludwig Wittgenstein This chapter surveys the main features of PL SQL and points out the advantages they offer It also acquaints you with the basic concepts behind PL SQL and the general appearance of PL SQL programs You see how PL SQL bridges the gap between database technology and procedural programming languages Major Topics Main Features Architecture Advantages of PL SQL Overview 1 1 Main Features Main Features A good way t
185. 2 are Customer objects a comparison such as cl gt c2 calls method match automatically The method returns a negative number zero or a positive number signifying that SELF is respectively less than equal to or greater than the other parameter CREATE TYPE Customer AS OBJECT id BER name VARCHAR2 20 addr VARCHAR2 30 ORDER MEMBER FUNCTION match c Customer RETURN INTEGER CREATE TYPE BODY Customer AS ORDER MEMBER FUNCTION match c Customer RETURN INTEGER IS BEGI IF id lt c id THEN RETURN 1 any negative number will do id gt c id THEN T any positive number will do a E E ve Da E G ve 0 An object type can contain only one order method which must be a function that returns a numeric result Guidelines A map method acting like a hash function maps object values into scalar values which are easier to compare then compares the scalar values An order method simply compares one object value to another You can declare a map method or an order method but not both If you declare either method you can compare objects in SOL and procedural statements However if you declare neither method you can compare objects only in SQL statements and only for equality or inequality Iwo objects of the same type are equal only if the values of their
186. 3 description VARCHAR2 50 quantity INTEGER price REAL 7 2 item_info StckItem declare record The identifier item_info represents an entire record Like scalar variables user defined records can be declared as the formal parameters of procedures and functions An example follows DECLARE YPE EmpRec IS RECORD emp_id emp empno TYPE last_name VARCHAR2 10 job_title VARCHAR2 15 salary NUMBER 7 2 PROCEDURE raise_salary emp_info EmpRec 4 30 PL SQL User s Guide and Reference Initializing and Referencing Records Initializing and Referencing Records The example below shows that you can initialize a record in its type definition When you declare a record of type TimeRec its three fields assume an initial value of zero DECLARE YPE TimeRec IS RECORD seconds SMALLINT 0 minutes SMALLINT 0 hours SMALLINT 0 The next example shows that you can impose the NOT NULL constraint on any field and so prevent the assigning of nulls to that field Fields declared as NOT NULL must be initialized DECLARE YPE StockItem IS RECORD item_no INTEGER 3 NOT NULL 999 description VARCHAR2 50 quantity INTEGER price REAL 7 2 Referencing Records Unlike elements in a collection which are accessed usin
187. AW variable LONG RAW You use the LONG RAW datatype to store binary data or byte strings LONG RAW data is like LONG data except that LONG RAW data is not interpreted by PL SQL The maximum length of a LONG RAW value is 32760 bytes Fundamentals 2 15 Datatypes You can insert any LONG RAW value into a LONG RAW database column because the maximum width of a LONG RAW column is 2147483647 bytes However you cannot retrieve a value longer than 32760 bytes from a LONG RAW column into a LONG RAW variable ROWID Internally every database table has a ROWID pseudocolumn which stores hexadecimal strings called rowids Each rowid represents the storage address of a row You use the ROWID datatype to store rowids You can compare a ROWID variable with the ROWID pseudocolumn in the WHERE clause of an UPDATE or DELETE statement to identify the latest row fetched from a cursor See Fetching Across Commits on page 5 53 With Oracle8 rowids have been extended to support partitioned tables and indexes Extended rowids include a data object number which identifies the database segment Schema objects in the same segment for example a cluster of tables have the same object number A rowid contains the following information which is needed to locate a row a data object number a data file the first file is 1 a data block in the data file a row in the data block the first row is 0 Rowids provide the f
188. Both loop counters have the same name So to reference the outer loop counter from the inner loop you must use a label and dot notation as follows lt lt outer gt gt FOR step IN 1 25 LOOP FOR step IN 1 10 LOOP IF outer step gt 15 THEN END LOOP END LOOP outer Using the EXIT Statement The EXIT statement allows a FOR loop to complete prematurely For example the following loop normally executes ten times but as soon as the FETCH statement fails to return a row the loop completes no matter how many times it has executed FOR j IN 1 10 LOOP FETCH cl INTO emp_rec EXIT WHEN c1SNOTFOUND END LOOP Suppose you must exit from a nested FOR loop prematurely You can complete not only the current loop but any enclosing loop Simply label the enclosing loop that you want to complete Then use the label in an EXIT statement to specify which FOR loop to exit as follows lt lt outer gt gt FOR i IN 1 5 LOOP FOR j IN 1 10 LOOP FETCH cl INTO emp_rec EXIT outer WHEN c1SNOTFOUND exit both FOR loops END LOOP END LOOP outer control passes here 3 14 PL SQL User s Guide and Reference Sequential Control GOTO and NULL Statements Sequential Control GOTO and NULL Statements Unlike the IF and LOOP statements the GOTO and NULL statements are not crucial to PL SQL programming The structure of PL SQL is such that the GOTO statement is seldom nee
189. Bs through the locators For example when you retrieve a BLOB column value only a locator is returned Locators cannot span transactions or sessions So you cannot save a locator in a PL SQL variable during one transaction or session then use it in another transaction or session To manipulate LOBs you use the supplied package DBMS_LOB For more information about LOBs and package DBMS_LOB see Oracle8 Application Developer s Guide BFILE You use the BFILE datatype to store large binary objects in operating system files outside the database Every BF ILE variable stores a file locator which points to a large binary file on the server The locator includes a directory alias which specifies a full path name logical path names are not supported BFILEs are read only You cannot modify them The maximum number of open BFILEs is set by the Oracle initialization parameter SESSION_MAX_OPEN_FILES which is system dependent Also BFILEs do not participate in transactions The underlying operating system maintains file integrity The size of a BF ILE is system dependent but cannot exceed four gigabytes 2 32 1 bytes Your DBA makes sure that the BF ILE exists and that Oracle has read permissions on it BLOB You use the BLOB datatype to store large binary objects in the database in line or out of line Every BLOB variable stores a locator which points to a large binary object The size of a BLOB cannot exceed four
190. CEPTION WHEN OTHERS THEN ROLLBACK Because the block in which it was declared has no handler for the exception named past_due it propagates to the enclosing block But according to the scope rules enclosing blocks cannot reference exceptions declared in a sub block So only an OTHERS handler can catch the exception Reraising an Exception Sometimes you want to reraise an exception that is handle it locally then pass it to an enclosing block For example you might want to roll back a transaction in the current block then log the error in an enclosing block To reraise an exception simply place a RAISE statement in the local handler as shown in the following example DECLARE out_of_balance EXCEPTION BEGI BEGIN e sub block begins IF THEN RAISE out_of_balance raise th xception END IF 6 14 PL SQL User s Guide and Reference Handling Raised Exceptions EXCEPTION WHEN out_of_balance THEN handle the error RAISE reraise the current exception END sub block ends EXCEPTION WHEN out_of_balance THEN handle the error differently END Omitting the exception name in a RAISE statement allowed only in an exception handler reraises the current exception Handling Raised Exceptions When an exception is raised normal execution of your PL SQL block or subprogram stops and con
191. Course 3010 Course 3720 Course 3760 Course 3822 Course 3870 Expository Writing 3 Film and Literature 4 Modern Science Fiction 3 Discursive Writing 4 Modern English Grammar 3 Introduction to Shakespeare 4 Modern Drama 4 The Short Story 4 The American Novel 5 Collections and Records 4 15 Manipulating Collections In the following example you revise the list of courses offered by the English Department DECLARE new_courses CourseList CourseList Course 1002 Expository Writing 3 BEGIN UPDATE department SET courses new_courses WHERE name English 4 Course 2810 Discursive Writing 4 Course 3010 Modern English Grammar 3 Course 3550 Realism and Naturalism 4 Course 3720 Introduction to Shakespeare 4 Course 2020 Film and Literature Course 3760 Modern Drama 4 Course 3822 The Short Story 4 Course 3870 The American Novel 4 Course 4210 20th Century Poetry 4 Course 4720 Advanced Workshop in Fiction 5 Course 4725 Advanced Workshop in Poetry 5 In the next example you retrieve all the courses offered by the Psychology Department into a local nested table DECLARE BEGIN psyc_courses Courselist SELECT courses INTO psyc_courses FROM department
192. Cursor Variables Syntax To execute a multi row query Oracle opens an unnamed work area that stores processing information To access the information you can use an explicit cursor which names the work area Or you can use a cursor variable which points to the work area Whereas a cursor always refers to the same query work area a cursor variable can refer to different work areas To create cursor variables you define a REF CURSOR type then declare cursor variables of that type Cursor variables are like C or Pascal pointers which hold the memory location address of some item instead of the item itself So declaring a cursor variable creates a pointer not an item For more information see Using Cursor Variables on page 5 18 ref_cursor_type_definition TYPE IS REF CURSOR CD O ROWE CE C OE record_name record_type_name ref_cursor_type_name cursor_variable_declaration cursor_variable_name type_name 5 Keyword and Parameter Description type_name This is a user defined type specifier which is used in subsequent declarations of PL SQL cursor variables 11 38 PL SQL User s Guide and Reference Cursor Variables REF CURSOR In PL SQL pointers have datatype REF X where REF is short for REFERENCE and X stands for a class of objects Therefore cursor variables have datatype REF CURSOR RETURN This keyword introduces the RETURN clause which specifies
193. D IF In the next example you might expect the sequence of statements to execute because a and b seem equal But again that is unknown so the IF condition yields NULL and the sequence of statements is bypassed a NULL b NULL IF a b THEN yields NULL not TRUE sequence_of_statements not executed END IF NOT Operator Recall that applying the logical operator NOT to a null yields NULL Thus the following two statements are not always equivalent IF x gt y THEN IF NOT x gt y THEN high x high y ELSE ELSE high y high x END IF END IF The sequence of statements in the ELSE clause is executed when the IF condition yields FALSE or NULL So if either or both x and y are null the first IF statement assigns the value of y to high but the second IF statement assigns the value of x to high If neither x nor y is null both IF statements assign the same value to high Fundamentals 2 49 Expressions and Comparisons Zero Length Strings PL SQL treats any zero length string like a null This includes values returned by character functions and Boolean expressions For example the following statements assign nulls to the target variables null_string TO_VARCHAR2 zip_code SUBSTR address 25 0 valid name So use the IS NULL operator to test for null strings as follows IF my_string IS NULL THEN
194. DATE RETURN Staff IS BEGIN END BEGIN staffer new_hires 16 OCT 96 3 call function Assigning and Comparing Collections One collection can be assigned to another by an INSERT UPDATE FETCH or SELECT statement an assignment statement or a subprogram call As the example below shows the collections must have the same datatype Having the same element type is not enough DECLARE YPE Clientele IS VARRAY 100 OF Customer YPE Vips IS VARRAY 100 OF Customer groupl Clientele Clientele group2 Clientele Clientele group3 Vips Vips BEGIN group2 groupl group3 group2 illegal different datatypes If you assign an atomically null collection to another collection the other collection becomes atomically null and must be reinitialized Consider the following example DECLARE YPE Clientele IS TABLE OF Customer groupl Clientele Clientele initialized group2 Clientele atomically null BEGIN IF groupl IS NULL THEN condition yields FALSE groupl group2 IF groupl IS NULL THEN condition yields TRUE 4 12 PL SQL User s Guide and Reference Assigning and Comparing Collections Likewise if you assign the non value NULL to a collection the collection becomes atomically null Assigning Collection Elements You can assign the value
195. DATE tbl SET col x 10 illegal UPDATE scott tbl SET scott tbl col x 10 illegal UPDATE tbl t set t col x 1 DE E FROM tbl WHERE tbl col x 10 illegal DE E FROM tbl t WHERE t col x 10 E 10 PL SQL User s Guide and Reference Calling Subprograms and Methods Row expressions must resolve as references to table aliases You can pass row expressions to operators REF and VALUE and you can use row expressions in the SET clause of an UPDATE statement Some examples follow CREATE TYPE t1 AS OBJECT x number CREATE TABLE otl OF t1 SELECT REF ot1 FROM ot1 SELECT REF o FROM otl o SELECT VALUE ot1 FROM ot1 SELECT VALUE o FROM ot1 o DELETE FROM ot1 WHERE VALUE ot1 DELETE FROM ot1 o WHERE VALUE o UPDATE ot1 SET otl UPDATE otl o SET o object table illegal illegal illegal illegal The following ways to insert into an object table are legal and do not require an alias because there is no column list INSERT INTO ot1 VALUI INSERT INTO ot1 VALUI Pa Pa Calling Subprograms and Methods You can call a parameterless subprogram with or without an empty parameter list Likewise within PL SOL scopes the empty parameter list is optional However within SQL scopes it is required Example 1 CREAT
196. DECLARE CURSOR cl IS SELECT ename dname FROM emp dept WHERE emp deptno dept deptno AND job MANAGER FOR UPDATE OF sal You use the CURRENT OF clause in an UPDATE or DELETE statement to refer to the latest row fetched from a cursor as the following example shows DECLARE CURSOR cl IS SELECT empno job sal FROM emp FOR UPDATE BEGIN OPEN cl LOOP FETCH cl INTO UPDATE emp SET sal new_sal WHERE CURRENT OF cl END LOOP Using LOCK TABLE You use the LOCK TABLE statement to lock entire database tables in a specified lock mode so that you can share or deny access to them For example the statement below locks the emp table in row share mode Row share locks allow concurrent access to a table they prevent other users from locking the entire table for exclusive use Table locks are released when your transaction issues a commit or rollback LOCK TABLE emp IN ROW SHARE MODE NOWAIT The lock mode determines what other locks can be placed on the table For example many users can acquire row share locks on a table at the same time but only one user at a time can acquire an exclusive lock While one user has an exclusive lock on a table no other users can insert delete or update rows in that table For more information about lock modes see Oracle8 Application Developer s Gu
197. E NOT done LOOP sequence_of_statements done boolean_expression END LOOP A statement inside the loop must assign a new value to the Boolean variable Otherwise you have an infinite loop For example the following LOOP statements are logically equivalent WHILE TRUE LOOP LOOP cans dees END LOOP END LOOP FOR LOOP Whereas the number of iterations through a WHILE loop is unknown until the loop completes the number of iterations through a FOR loop is known before the loop is entered FOR loops iterate over a specified range of integers Cursor FOR loops which iterate over the result set of a cursor are discussed in Chapter 5 The range is part of an iteration scheme which is enclosed by the keywords FOR and LOOP A double dot serves as the range operator The syntax follows FOR counter IN REVERSE lower_bound higher_bound LOOP sequence _of statements END LOOP The range is evaluated when the FOR loop is first entered and is never re evaluated 3 10 PL SQL User s Guide and Reference Iterative Control LOOP and EXIT Statements As the next example shows the sequence of statements is executed once for each integer in the range After each iteration the loop counter is incremented FOR i IN 1 3 LOOP assign the values 1 2 3 to i sequence_of_statements xecutes thr times END LOOP The following example shows that if the lower bound eq
198. E name Security In the next example you retrieve all the projects for the Accounting Department into a local varray DECLARE my_projects ProjectList BEGIN SELECT projects INTO my_projects FROM department WHERE name Accounting Collection Methods Object Types Records Language Elements 11 25 Comments Commenis Syntax Usage Notes Examples Comments describe the purpose and use of code segments and so promote readability PL SQL supports two comment styles single line and multi line Single line comments begin with a double hyphen anywhere on a line and extend to the end of the line Multi line comments begin with a slash asterisk end with an asterisk slash and can span multiple lines For more information see Comments on page 2 9 comment Comments can appear within a statement at the end of a line However you cannot nest comments You cannot use single line comments in a PL SQL block that will be processed dynamically by an Oracle Precompiler program because end of line characters are ignored As a result single line comments extend to the end of the block not just to the end of a line Instead use multi line comments While testing or debugging a program you might want to disable a line of code The following example shows how you can comment out the line UPDATE dept SET loc my_loc W
199. E statement The EXIT WHEN statement replaces a simple IF statement For example compare the following statements IF count gt 100 THEN EXIT WHEN count gt 100 EXIT END IF These statements are logically equivalent but the EXIT WHEN statement is easier to read and understand Loop Labels Like PL SQL blocks loops can be labeled The label an undeclared identifier enclosed by double angle brackets must appear at the beginning of the LOOP statement as follows lt lt label_name gt gt LOOP sequence_of_statements END LOOP Optionally the label name can also appear at the end of the LOOP statement as the following example shows lt lt my_loop gt gt LOOP END LOOP my_loop When you nest labeled loops you can use ending label names to improve readability 3 8 PL SQL User s Guide and Reference Iterative Control LOOP and EXIT Statements WHILE LOOP With either form of EXIT statement you can complete not only the current loop but any enclosing loop Simply label the enclosing loop that you want to complete Then use the label in an EXIT statement as follows lt lt outer gt gt LOOP LOOP EXIT outer WHEN exit both loops END LOOP END LOOP outer Every enclosing loop up to and including the labeled loop is exited The WHILE LOOP statement associates a condition with a sequence of statements encl
200. EGER Overview 1 15 Main Features ER PROCEDURE close num IN INTEGER amount OUT REAL ER PROCEDURE deposit num IN INTEGER amount IN REAL ER PROCEDURE withdraw num IN INTEGER amount IN REAL ER FUNCTION curr_bal num IN INTEGER RETURN REAL W W W W y At run time when the data structure is filled with values you have created an instance of an abstract bank account You can create as many instances called objects as you need Each object has the number balance and status of an actual bank account Information Hiding With information hiding you see only the details that are relevant at a given level of algorithm and data structure design Information hiding keeps high level design decisions separate from low level design details which are more likely to change Algorithms You implement information hiding for algorithms through top down design Once you define the purpose and interface specifications of a low level procedure you can ignore the implementation details They are hidden at higher levels For example the implementation of a procedure named raise_salary is hidden All you need to know is that the procedure will increase a specific employee salary by a given amount Any changes to the definition of raise_salary are t
201. EGI DELETE FROM department WHERE dept_id 30 Manipulating Individual Elements So far you have manipulated whole collections Within SQL to manipulate the individual elements of a nested table you must use the operator THE However THE cannot operate on varrays So to manipulate the individual elements of a varray you must use PL SQL procedural statements Some Nested Table Examples In the following example you add a row to the History Department nested table stored in column courses BEGIN INSERT INTO THE SELECT courses FROM department WHERE name History VALUES 3340 Modern China 4 The operand of THE is a subquery that returns a single column value for you to manipulate The column value must be a nested table Otherwise you get a runtime error Because the value is a nested table not a scalar value Oracle must be informed which is what operator THE does 4 18 PL SQL User s Guide and Reference Manipulating Collections In the following example you revise the number of credits for two courses offered by the Psychology Department DECLARE adjustment INTEGER DEFAULT 1 BEGIN UPDATE THE SELECT courses FROM department WHERE name Psychology SET credits credits adjustment WHERE course_no IN 2200 3540 In the next example you r
202. EN ROLLBACK TO start_transaction undo changes suffix suffix 1 try to fix Error Handling 6 21 Useful Techniques name name TO_CHAR suffix problem END sub block ends END LOOP END Using Locator Variables Exceptions can mask the statement that caused an error as the following example shows BEGI SELEC SELEC SELEC EXCEPTION WHEN NO_DATA FOUND THEN Which SELECT statement caused th rror END Normally this is not a problem But if the need arises you can use a locator variable to track statement execution as follows DECLARE stmt INTEGER 1 designates lst SELECT statement BEGI tmt 2 designates 2nd SELECT statement tmt 3 designates 3rd SELECT statement ELEC EXCEPTION WHEN NO_DATA FOUND THEN INSERT INTO errors VALUES Error in statement stmt T 6 22 PL SQL User s Guide and Reference Subprograms Civilization advances by extending the number of important operations that we can perform without thinking about them Alfred North Whitehead This chapter shows you how to use subprograms which let you name and encapsulate a sequence of statements Subprograms aid application development by isolating operations They are like bu
203. EN sequence_of_statements END IF The sequence of statements is executed only if the condition yields TRUE If the condition yields FALSE or NULL the IF statement does nothing In either case control passes to the next statement An example follows IF sales gt quota THEN compute_bonus empid UPDATE payroll SET pay pay bonus WHERE empno emp_id END IF You might want to place brief IF statements on a single line as in IF x gt y THEN high x END IF The second form of IF statement adds the keyword ELSE followed by an alternative sequence of statements as follows IF condition THEN sequence_of_statements1 ELSE sequence_of_statements2 END IF The sequence of statements in the ELSE clause is executed only if the condition yields FALSE or NULL Thus the ELSE clause ensures that a sequence of statements is executed In the following example the first or second UPDATE statement is executed when the condition is true or false respectively IF trans_type CR THEN UPDATE accounts SET balance balance credit WHE ELSE UPDATE accounts SET balance balanc debit WHERE END IF Control Structures 3 3 Conditional Control IF Statements T The THEN and ELSE clauses can include IF statements That is be nested as the following example s
204. EN Statementeiconici n iraina iio nodo ac sechied a eases doses Moke dale o cach bed dashes e a o e teed 11 111 OPEN FOR Statement acacia deis aa E es ee Eaa Aaka eaa eae NENE Ea e ona EEA SE 11 113 Packages EOE EE EESE AE il ida 11 117 Procedures mne eaa cesses eden a As 11 121 RAISE Statement erosia o Soe eR vn en a en eo he 11 126 Records ii di ieee 11 128 RETURN Statement aa 11 132 ROLLBACK Statement Aa 11 134 ROW TY PE Attei bute coccion iii eld hone dia ln Ged ee EM I Be 11 136 SAVEPOINT Statements dile ascecacesabecas thes decdescheskesaudaeacs laden casasctadacdbeacesscatvastesenede 11 138 SELECT INTO Statement ainiai eaaa A aA E A Ea RE Ea R 11 139 SET TRANSACTION Statements ancianidad a e E a ak ee 11 142 SOL E E eLo ERE E O E AA E A A AE E T E T 11 144 SOLCODE Function nasiri A i e iei iiaii i iiae 11 146 SOLERRM Fan ction cti ies 11 147 TYPE Attribute ii a a ed Mth di dd 11 149 UPDATE Statement nimesin arnehi ee eare i a iea ea ea 11 151 A New Features External Procedures iii ada saca A 2 Object Ty pes ii iii as A 2 Collect A A GN eed Wah tara eee so A 2 OA AAA vhs bscaad A E A A 3 NESTIYDES viii E AAA Dea AE td Dee Suite Seals Dev ea dE AA AAA A bici A 3 B Sample Programs Running the Prograiis so enea e ainda B 2 Sample T FOR Loop ma e a E E E B 11 Sample 2 CULOS A AA B 12 Sample 3 Scopare a B 13 Sample 4 Batch Transaction Processing cooocicicicinonnonnnnnmmmrarrracere rin rrrraronorincncnno B 15 Sample 5
205. END emp data E When you declare a cursor variable as the formal parameter of a subprogram that opens the cursor variable you must specify the IN OUT mode That way the subprogram can pass an open cursor back to the caller Alternatively you can use a stand alone procedure to open the cursor variable Simply define the REF CURSOR type in a separate package then reference that type in the stand alone procedure For instance if you create the following bodiless package you can create stand alone procedures that reference the types it defines CREATE PACKAGE cv_types AS YPE GenericCurTyp IS REF CURSOR YPE EmpCurTyp IS REF CURSOR RETURN emp ROWTYPE YPE DeptCurTyp IS REF CURSOR RETURN dept SROWTYP GI se END cv_types Interaction with Oracle 5 23 Using Cursor Variables In the following example you create a stand alone procedure that references the REF CURSOR type EmpCurTyp which is defined in the package cv_types CREATE PROCEDURE open_emp_cv emp_cv IN OUT cv_types EmpCurTyp AS BEGIN OPEN emp_cv FOR SELECT FROM emp D open_emp_cv E To centralize data retrieval you can group type compatible queries in a stored procedure In the example below the packaged procedure declares a selector as one of its formal parameters In this context a selector is a variable used to select one of se
206. F variable NULL THEN Instead use the following statement IF variable IS NULL THEN LIKE Operator You use the LIKE operator to compare a character value to a pattern Case is significant LIKE returns the Boolean value TRUI FALSE if they do not match E if the character patterns match or The patterns matched by LIKE can include two special purpose characters called wildcards An underscore _ matches exactly one character a percent sign matches zero or more characters For example if the value of ename is JOHNSON the following expression yields TRUE ename LIKE J SON BETWEEN Operator The BETWEEN operator tests whether a value lies in a specified range It means greater than or equal to low value and less than or equal to high value For example the following expression yields FALSE 45 BETWEEN 38 AND 44 p Ers Fundamentals 2 45 Expressions and Comparisons IN Operator The IN operator tests set membership It means equal to any member of The set can contain nulls but they are ignored For example the following statement does not delete rows in which the ename column is null DELETE FROM emp WHERE ename IN NULL KING FORD Furthermore expressions of the form value NOT IN set yield FALSE if the set contains a null For example instead of deleting rows in which the ena
207. FROM tabl x illegal SELECT x coll f FROM tabl x DECLARE n ER y typel BEGIN In PL SQL scopes an empty parameter list is optional n y f n y f In SQL scopes an empty parameter list is required SELECT x col1 f INTO n FROM tabl x illegal SELECT x coll f INTO n FROM tabl x SELECT y f INTO n FROM tabl x illegal SELECT y f INTO n FROM tabl x 1 E E 12 PL SQL User s Guide and Reference SQL versus PL SQL SQL versus PL SQL The name resolution rules for SOL and PL SQL are similar However there are a few minor differences which are not noticeable if you follow the capture avoidance rules For compatibility the SOL rules are more permissive than the PL SQL rules That is the SQL rules which are mostly context sensitive allow for more legal situations Also the SQL rules recognize as legal more DML statements than the PL SQL rules recognize Name Resolution E 13 SQL versus PL SQL E 14 PL SQL User s Guide and Reference E Reserved Words The words listed in this appendix are reserved by PL SQL that is they have a special syntactic meaning to PL SQL So you should not use them to name program objects such as constants variables or cursors Also some of these words marked by an asterisk are reserved by SQL So you should not use them to name schema objects such as col
208. For more information see Datatypes on page 2 10 db_table_name column_name This identifies a database table and column that must be accessible when the declaration is elaborated variable_name This identifies a program variable 11 30 PL SQL User s Guide and Reference Constants and Variables collection_name This identifies a nested table index by table or varray previously declared within the current scope cursor_name This identifies an explicit cursor previously declared within the current scope cursor_variable_name This identifies a PL SQL cursor variable previously declared within the current scope object_name This identifies an object instance of an object type previously declared within the current scope record name This identifies a user defined record previously declared within the current scope db_table_name This identifies a database table or view that must be accessible when the declaration is elaborated ROWTYPE This attribute provides a record type that represents a row in a database table or a row fetched from a previously declared cursor Fields in the record and corresponding columns in the row have the same names and datatypes TYPE This attribute provides the datatype of a previously declared collection cursor variable field object record database column or variable NOT NULL This constraint prevents the assigning of nulls to a variable or constant At run
209. GIN FOR i IN 1 10 LOOP BER 100 IF MOD i 2 0 THEN INSERT INTO temp F SE INSERT INTO temp END IF x x 100 END LOOP COMMIT END SQL gt SELECT FROM temp ORD COL1 COL2 ESSAGE 1 100 i is odd 2 200 i is even 3 300 i is odd 4 400 i is even 5 500 i is odd 6 600 i is even 7 700 i is odd 8 800 i is even 9 900 i is odd 10 1000 i is even 10 records selected sample1 i is even VALUES i x i is even VALUES i x i is odd ER BY coll Sample Programs B 11 Sample 2 Cursors Sample 2 Cursors The following example uses a cursor to select the five highest paid employees from the emp table Input Table SQL gt SELECT ename empno sal FROM emp ORDER BY sal DESC ENAME EMPNO SAL KING 7839 5000 SCOTT 7788 3000 FORD 7902 3000 JONES 7566 2975 BLAKE 7698 2850 CLARK 7782 2450 ALLEN 7499 1600 TURNER 7844 1500 MILLER 7934 1300 WARD 7521 1250 MARTIN 7654 1250 ADAMS 7876 1100 JAMES 7900 950 SMITH 7369 800 14 records selected PL SQL Block available online in file sample2 DECLARE CURSOR cl is SELECT ename empno sal FROM emp ORDER BY sal DESC start with highest paid employee my_ename CHAR 10 my_empno NUMBER 4
210. HERE deptno my_deptno You can use multi line comment delimiters to comment out whole sections of code The following examples show various comment styles compute the area of a circle area pi radius 2 pi equals 3 14159 Compute the area of a circle area pi radius 2 pi equals 3 14159 11 26 PL SQL User s Guide and Reference COMMIT Statement COMMIT Statement Syntax The COMMIT statement explicitly makes permanent any changes made to the database during the current transaction Changes made to the database are not considered permanent until they are committed A commit also makes the changes visible to other users For more information see Processing Transactions on page 5 44 commit_statement WORK COMMENT SORTS el COMMA AA o Keyword and Parameter Description Usage Notes WORK This keyword is optional and has no effect except to improve readability COMMENT This keyword specifies a comment to be associated with the current transaction and is typically used with distributed transactions The text must be a quoted literal no more than 50 characters long The COMMIT statement releases all row and table locks It also erases any savepoints you marked since the last commit or rollback Until your changes are committed the following conditions hold a You can see the changes when you query the tables you modified but other users cannot see the ch
211. INTO emp VALUES WU we E mgr SYSDATI hire employee ROCEDURE fire employee emp_id NU EGIN DELETE FROM emp WHE ID fire employee END emp_actions ETURN EmpRecTyp SELECT empno sal FROM emp ORDER body IS BY sal DESC empno_seq NEXTVAL ename job E sal comm deptno BER IS RE empno emp_id Packages 8 3 Advantages of Packages Only the declarations in the package specification are visible and accessible to applications Implementation details in the package body are hidden and inaccessible So you can change the body implementation without having to recompile calling programs Advantages of Packages Packages offer several advantages modularity easier application design information hiding added functionality and better performance Modularity Packages let you encapsulate logically related types items and subprograms in a named PL SQL module Each package is easy to understand and the interfaces between packages are simple clear and well defined This aids application development Easier Application Design When designing an application all you need initially is the interface information in the package specifications You can code and compile a specification without its body Then stored subprograms that reference the package can be compiled as well You need not define the package bodies fully until you are read
212. IS OL ici E 13 F Reserved Words Index xii Send Us Your Comments PL SQL User s Guide and Reference Release 8 0 Part No A58236 01 Oracle Corporation welcomes your comments and suggestions on the quality and usefulness of this publication Your input is an important part of the information used for revision Did you find any errors Is the information clearly presented a Do you need more information If so where a Are the examples correct Do you need more examples What features did you like most about this manual If you find any errors or have any other suggestions for improvement please indicate the chapter section and page number if available You can also send comments to us by email infodev us oracle com fax 650 506 7200 Attn Server Technologies Documentation Manager letter Server Technologies Documentation Manager Oracle Corporation 500 Oracle Parkway Redwood Shores CA 94065 USA If you would like a reply please give your name address and telephone number below xiii xiv Preface PL SQL is Oracle s procedural extension to SQL the standard database access language A full fledged programming language PL SQL offers modern software engineering features such as data encapsulation overloading exception handling and information hiding PL SQL also offers seamless SQL access tight integration with the Oracle server and tools portability and security This guide ex
213. ISE_APPLICATION_ERROR 20105 wrong number ELSIF status closed THEN RAISE_APPLICATION_ ERROR 20106 account closed END IF END verify_acct Object Types 9 19 Defining Object Types MEI Bl MEMB i zi z F END close F END deposi given amount BI MEI B ER PROCEDURE close num IN INT G ER amount OUT RI Cc BI lose account and return balance EGIN verify_acct num status closed amount balance BER PROC GIN verify_acct num IF NOT amount gt 0 THEN RAISI END IF balance EDUF E deposit num IN IN balance amount ER PROCEDURE withdraw ls rais E_APPLICATION_ERROR 20104 num IN INT f account has enough funds withdraw T EG ER amount IN RI bad amount EG ER amount IN RI tion A an exc GIN verify_acct num IF amount lt balance THEN balance balance amount SE RAISI IF thdraw E APPLICATION EMBER FUNCTION curr_bal RETURN REAL IS GIN veri RE SI fy_acct num URN balance END curr_bal 9 20 PL SQL User s Guide and Reference ERROR 20107 ELF IN OUT Bank_Account num IN INT p insufficient funds
214. ISOPEN NOTFOUND ROWCOUNT OPEN before exception FALSE exception exception after NULL RUE NULL 0 First FETCH before NULL RUE NULL 0 after RUE RUE FALSE 1 Next FETCH es before RUE RUE FASE 1 after RUE RUE FASE data dependent Last FETCH before RUE RUE FASE data dependent after FALSE RUE RUE data dependent CLOSE before FALSE RUE RUE data dependent Gl after exception FALSE exception exception Notes 1 Referencing FOUND sNOTFOUND or SROWCOUNT before a cursor is opened or after it is closed raises INVALID_CURSOR 2 After the first FETCH if the result set was empty SFOUND yields FALSE SNOTFOUND yields TRUE and ROWCOUNT yields 0 Some Examples Suppose you have a table named dat a_table that holds data collected from laboratory experiments and you want to analyze the data from experiment 1 In the following example you compute the results and store them in a database table named temp available online in file examp5 DECLARE numl data_table nlSTYPE Declare variables num2 data_table n2 TYPE having same types as num3 data_table n3STYPE database columns result temp col1STYPE CURSOR c1 IS SELECT nl n2 n3 FROM data table WHERE exper_num 1 5 40 PL SQL User s Guide and Reference Using Cursor Attributes BEGIN OPEN
215. L 3 14159 last_name VARCHARZ2 20 my_ename mp enamesTYPE Assignment Statement Expressions ROWTYPE Attribute TYPE Attribute 11 32 PL SQL User s Guide and Reference Cursor Attributes Cursor Attributes Syntax Cursors and cursor variables have four attributes that give you useful information about the execution of a data manipulation statement For more information see Using Cursor Attributes on page 5 38 cursor_attribute ma O Keyword and Parameter Description cursor_name This identifies an explicit cursor previously declared within the current scope cursor_variable_name This identifies a PL SQL cursor variable or parameter previously declared within the current scope host_cursor_variable_ name This identifies a cursor variable declared in a PL SQL host environment and passed to PL SQL as a bind variable The datatype of the host cursor variable is compatible with the return type of any PL SQL cursor variable Host variables must be prefixed with a colon SQL This is the name of the implicit SQL cursor For more information see SQL Cursor on page 11 144 Language Elements 11 33 Cursor Attributes Usage Notes FOUND This is a cursor attribute which can be appended to the name of a cursor or cursor variable Before the first fetch from an open cursor cursor_namesFOUND yields NULL Thereafter it yields TRUE if the last fetch returned a row
216. L a tool can do any computation quickly and efficiently without calling on the Oracle server This saves time and reduces network traffic 1 22 PL SQL User s Guide and Reference Advantages of PL SQL Portability Applications written in PL SQL are portable to any operating system and platform on which Oracle runs In other words PL SQL programs can run anywhere Oracle can run you need not tailor them to each new environment That means you can write portable program libraries which can be reused in different environments Higher Productivity PL SQL adds functionality to non procedural tools such as Oracle Forms and Oracle Reports With PL SQL in these tools you can use familiar procedural constructs to build applications For example you can use an entire PL SQL block in an Oracle Forms trigger You need not use multiple trigger steps macros or user exits Thus PL SQL increases productivity by putting better tools in hands of programmers Moreover PL SQL is the same in all environments As soon as you master PL SQL with one Oracle tool you can transfer your knowledge to other tools and so multiply the productivity gains For example scripts written with one tool can be used by other tools Integration with Oracle Both PL SQL and Oracle are based on SQL Moreover PL SQL supports all the SQL datatypes Combined with the direct access that SQL provides these shared datatypes integrate PL SQL with the Oracle data dictionary
217. L FOUND yields TRUE SQL ROWCOUNT yields the number of rows updated If no rows are updated you get these results SQL NOTFOUND yields TRUE Ao SQL FOUND yields FALSE SQL ROWCOUNT yields 0 Examples In the following example a 10 raise is given to all analysts and clerks in department 20 UPDATE emp SET sal sal 1 10 WHERE job ANALYST OR job CLERK AND DEPTNO 20 In the next example an employee named Ford is promoted to the position of Analyst and her salary is raised by 15 UPDATE emp SET job ANALYST sal sal 1 15 WHERE ename FORD In the final example you return values from an updated row and store them in variables UPDATE emp SET sal sal 500 WHERE ename MILLER RETURNING sal ename INTO my_sal my_ename Related Topics DELETE Statement FETCH Statement 11 154 PL SQL User s Guide and Reference A New Features This appendix surveys the new features in release 8 0 of PL SQL Designed to meet your practical needs these features will help you build effective reliable applications Major Topics External Procedures Object Types Collections LOB Types NLS Types New Features A 1 External Procedures External Procedures To support special purpose processing and promote reuse of code PL SQL provides an interface for calling routines written in other lan
218. LAST ignore deleted elements Using PRIOR and NEXT PRIOR n returns the index number that precedes index nin a collection NEXT n returns the index number that succeeds index n If n has no predecessor PRIOR 1 returns NULL Likewise if n has no successor NEXT n returns NULL PRIOR and NEXT do not wrap from one end of a collection to the other For example the following statement assigns NULL to n because the first element in a collection has no predecessor n courses PRIOR courses FIRST assigns NULL to n Collections and Records 4 23 Using Collection Methods Using EXTEND PRIOR is the inverse of NEXT For instance if element i exists the following statement assigns element i to itself projects i projects PRIOR projects NEXT i assigns element i You can use PRIOR or NEXT to traverse collections indexed by any series of subscripts In the following example you use NEXT to traverse a nested table from which some elements have been deleted i courses FIRST get subscript of first elementWhen tallying elements WHILE i IS NOT NULL LOOP do something with courses i END LOOP i courses NEXT i get subscript of next element When traversing elements PRIOR and NEXT ignore deleted elements To increase the size of a collection you use EXTEND This procedure has three forms EXTEND appends one null element
219. LUE 9 32 OR keyword 6 16 Oracle Trusted 2 10 order method 9 10 order of evaluation 2 42 2 43 OTHERS exception handler 6 2 6 15 OUT parameter mode 7 13 overloading 7 18 object method 9 10 packaged subprogram 8 14 restrictions 7 19 using subtypes 7 20 P package 8 1 8 2 advantages 8 4 bodiless 8 6 body 8 2 creating 8 3 DEBUG_EXTPROC 10 24 initializing 8 8 private versus public objects 8 14 referencing 8 6 scope 8 5 serially reusable 5 55 specification 8 2 syntax 11 117 package product specific 8 16 packaged cursor 5 15 packaged subprogram 1 19 7 9 calling 8 6 overloading 8 14 parameter actual versus formal 7 11 cursor 5 11 default values 7 15 modes 7 13 SELF 9 8 parameter passing by reference 7 17 by value 7 17 PARAMETERS clause 10 5 10 12 Index 10 parentheses 2 42 Pascal Calling Standard 10 4 pattern matching 2 45 p code 5 8 performance 1 22 improving 5 54 pipe 8 17 PL SQL advantages 1 21 architecture 1 18 block structure 1 2 execution environments 1 18 new features A 1 performance 1 22 portability 1 23 procedural aspects 1 2 reserved words F 1 sample programs B 1 support forSQL 1 21 PL SQL block anonymous 1 2 7 2 maximum size 5 60 syntax 11 7 PL SQL compiler how calls are resolved 7 21 how it works 5 8 how references are resolved 5 7 PL SQL engine 1 18 in Oracle Server 1 19 in Oracle tools 1 20 PL SQL syntax 11 1 PL SQL W
220. MBER PROCEDURE purchase movie INTEGER amount REAL out of stock change OUT REAL IS BEGIN IF qty_on hand 0 THEN RAISE_APPLICATION_ERROR 20103 END IF IF amount gt price THEN aty_on hand qty_on_hand 1 receipts movie receipts movie price change amount price ELSE amount is not enough change amount so return full amount END IF END purchase BEGIN aty_on hand END inventory EMBER FUNCTION inventory RETURN INTEGER IS EMBER PROCEDUF IS BEGIN aty_on hand END replenish agty_on hand quantity dE MEMBER PROCEDURE collect BEGIN amount receipts movie E replenish quantity INTEG movie INTEGER amount OUT REAL receipts movie 0 END collect 7 g 9 18 PL SQL User s Guide and Reference ER IS get receipts for a given movie reset receipts for that movie to zero Defining Object Types Object Type Bank_Account Before defining an object type that represents a bank account we must consider the data and operations needed For a simple bank account the object type needs attributes for an account number balance and status It also needs methods for the following operations open account verify account number close account deposit
221. Major Topics What Is Name Resolution Various Forms of References Name Resolution Algorithm Understanding Capture Avoiding Capture Accessing Attributes and Methods Calling Subprograms and Methods Name Resolution E 1 What Is Name Resolution What Is Name Resolution During compilation the PL SQL compiler associates identifiers such as the name of a variable with an address memory location datatype or actual value This process is called binding The association lasts through all subsequent executions until a recompilation occurs which might cause a rebinding Before binding the names PL SQL must resolve all references to them in the compilation unit This process is called name resolution PL SQL considers all names to be in the same namespace So one declaration or definition in an inner scope can hide another in an outer scope In the following example the declaration of variable client hides the definition of datatype Client because PL SQL is not case sensitive except within string literals BEGI lt lt block1 gt gt DECLARE YPE Client IS RECORD YPE Customer IS RECORD BEGIN DECLARE client Customer hides definition of type Client in outer scop leadl Client illegal Client resolves to th variable client lead2 block1 Client OK refers to type Client BEGIN NULL END END END However you can still refer to dat
222. NDARD coacciones a 8 16 ACACIA A A EAEE ETE RA i aE 8 16 DBMS PIPE cuina tin 8 17 AAA pon aane a e E a E E a deanna 8 17 UTE HTTP 0 AE E ST 8 17 DEMSSOL td al Deas Ne Poveda A A A AI 8 17 DEMS ALER E rieccoena gien ea a E S tabasco cee aistecriecaut asides atioa T 8 18 Guidelines msie riren eira ieia e aeea alive a Ee 8 18 9 Object Types viii The Role of Abstraction nessis ia a a e e e eE ai aa 9 2 What Is an Object Ty pe iii noni a rca ia 9 3 Why Use Object Types iii aia 9 5 Structure of an Object Type iii is 9 5 Components of an Object Type cscs sdei E Tee ORE E ES Ebar a nE R 9 7 ATID NN 9 7 MICH AAA A SE NN 9 8 Pragma RESTRICT REFERENCES wi sicsccsccictssesfesteacsntSicesiceetsssesdeceddhatecesedsrsccnbsatebsdstsvarsaeestos tts 9 12 Defining Object Ty pes icon edi dc ca botas 9 14 Object ly pe Stack dd id pi id daa 9 14 Object Type Ticket x BOOM icoioiiivincnco easket eripe a ind Sache redee daci n cbc 9 17 Object Type Bartk_ACCOUNE cocnononcnconononenenanannnnnnnnnnarnnnenonanannnnnnarnranannn nn nnn orar nn nanananon nara ternera na nanananns 9 19 Object Type Rational si desaire E eiii tev saves iii biocidas 9 21 Declaring and Initializing ObjectS cicinociciniononnnnonconononnnenconononinconinnononin cn nncnono ronca ninnanarincnanono 9 23 Declaring Objects ia das e e iii Siebert eas 9 23 Initializing Objects mi toiscesietivin anuales 9 24 How PL SQL Treats Uninitialized Object ocococinicinonononnnnnnnnm
223. NIT exception_name Oracle_error_number where except ion_name is the name of a previously declared exception The pragma must appear somewhere after the exception declaration in the same declarative part as shown in the following example DECLARE deadlock_detected EXCEPTION PRAGMA EXCEPTION_INIT deadlock_detected 60 BEGIN EXCEPTION WHEN deadlock_detected THEN handle the error 6 8 PL SQL User s Guide and Reference User Defined Exceptions Using raise_application_error Package DBMS_STANDARD which is supplied with Oracle provides language facilities that help your application interact with Oracle For example 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 avoid returning unhandled exceptions To call raise_application_error you use the syntax raise_application_error error_number message TRUE FALSE where error_number is a negative integer in the range 20000 20999 and message is a character string up to 2048 bytes long If the optional third parameter is TRUE the error is placed on the stack of previous errors If the parameter is FALSE the default the error replaces all previous errors Package DBMS_STANDARD is an extension of package STANDARD so you need not qualify references to it An applica
224. NSERT statement and for which you must have INSERT privileges For the syntax of table_reference see DELETE Statement on page 11 49 column_name column_name This identifies a list of columns in a database table or view Column names need not appear in the order in which they were defined by the CREATE TABLE or CREATE VIEW statement However no column name can appear more than once in the list If the list does not include all the columns in a table the missing columns are set to NULL or to a default value specified in the CREATE TABLE statement 11 88 PL SQL User s Guide and Reference INSERT Statement sql_expression This is any expression valid in SOL For more information see Oracle8 SQL Reference VALUES This clause assigns the values of expressions to corresponding columns in the column list If there is no column list the first value is inserted into the first column defined by the CREATE TABLE statement the second value is inserted into the second column and so on There must be only one value for each column in the column list The first value is associated with the first column the second value is associated with the second column and so on If there is no column list you must supply a value for each column in the table The datatypes of the values being inserted must be compatible with the datatypes of corresponding columns in the
225. NT undoes part of a transaction SET TRANSACTION establishes a read only transaction 5 2 PL SQL User s Guide and Reference SQL Support SQL Functions PL SQL lets you use all the SQL functions including the following group functions which summarize entire columns of Oracle data AVG COUNT MAX MIN STDDEV SUM and VARIANCE The group functions GLB and LUB are available only with Trusted Oracle GLB and LUB return the greatest lower bound and least upper bound of two or more operating system labels respectively For more information see your Trusted Oracle documentation You can use the group functions in SQL statements but not in procedural statements Group functions operate on entire columns unless you use the SELECT GROUP BY statement to sort returned rows into subgroups If you omit the GROUP BY clause the group function treats all returned rows as a single group You call a group function using the syntax function_name ALL DISTINCT expr where expr is an expression that refers to one or more database columns If you specify the ALL option the default the group function considers all column values including duplicates For example the following statement returns the sample standard deviation s of all values in the comm column SELECT STDDEV comm INTO comm_sigma FROM emp If you specify the DISTINCT option the group function considers only distinct values For
226. NTO_NULL THEN END Calls to methods of an uninitialized object are allowed in which case SELF is bound to NULL When passed as arguments to IN parameters attributes of an uninitialized object evaluate to NULL When passed as arguments to OUT or IN OUT parameters they raise an exception if you try to write to them Accessing Attributes You can refer to an attribute only by name not by its position in the object type To access or change the value of an attribute you use dot notation In the example below you assign the value of attribute den to variable denominator Then you assign the value stored in variable numerator to attribute num DECLARE r Rational Rational NULL NULL numerator INTEGER denominator INTEGER BEGIN denominator r den r num numerator Object Types 9 25 Calling Constructors and Methods Attribute names can be chained which allows you to access the attributes of a nested object type For example suppose we define object types Address and Student as follows CREATE TYPE Address AS OBJECT street VARCHAR2 30 city VARCHAR2 20 state CHAR 2 zip code VARCHAR2 5 CREATE TYPE Student AS OBJECT name VARCHARZ2 20 home_address Address phone_number VARCHAR2 10 status VARCAHR2 10 advisor_name VARCHAR2 20 7 Notice that zip_code is an attribute of object type Address and
227. OLERRM 1 70 ET balance new_balance SELECT balance INTO old_balance FROM accounts WHERE acct_id acct FOR UPDATE OF balance to lock the row PROCEDURE debit_account acct NUMBER debit REAL Debit account unless accoun account has insufficient funds old_balance NU new_balance NU BER BER insufficient_funds EXCEPTION new_balance IF new_balance old_balance debit gt minimum_balance THEN t number is bad or SELECT balance INTO old_balance FROM accounts WHERE acct_id acct FOR UPDATE OF balance to lock the row UPDATE accounts SET balance new_balance WHERE acct_id acct do_journal_entry acct D new_balance ELSE 2 END IF EXCEPTION RAISE insufficient_funds WHEN NO_DATA FOUND THEN new_status new_status WHEN OTHERS THE new_status END debit_account SUBSTR SQ Bad account number WHEN insufficient_funds THEN Insufficient funds N ERRM 1 70 END bank_transactions In this package the initialization part is not used IS Packages 8 13 Private versus Public Items Private versus Public Items Look again at the package emp_actions The package body declares a variable named number_hired which is initialized to zero Unlike items declared i
228. OM accounts ORDER BY account_id ACCOUNT_ID BAL 399 2000 599 6500 20099 1599 YA BWNE 6 records selected SQL gt SELECT FROM action ORDER BY time_tag ACCOUNT_ID O NEW VALUE STATUS IME TAG 3 u 599 Update Success 18 NOV 88 6 i 20099 Insert Success 18 NOV 88 Sal Delete Success 18 NOV 88 7 u 1599 Update ID not found 18 NOV 88 Value inserted a A 399 Insert Acct exists 18 NOV 88 Updated instead 9 q Delete ID not found 18 NOV 88 10 x Invalid operation 18 NOV 88 7 records selected B 18 PL SQL User s Guide and Reference Oa ction taken Sample 5 Embedded PL SQL Sample 5 Embedded PL SQL The following example shows how you can embed PL SQL in a high level host language such as C and demonstrates how a banking debit transaction might be done Input Table SQL gt SELECT FROM accounts ORDER BY account_id ACCOUNT_ID BAL 1 1000 2 2000 3 1500 4 6500 5 500 PL SQL Block in a C Program available online in file sample5 include lt stdio h gt char buf 20 EXEC SOL BEGIN DECLARE SECTION int acct double debit double new_bal VARCHAR status 65 VARCHAR uid 20 VARCHAR pwd 20 EXEC SOL END DECLARE SECTION EC SQL INCLUDE SQLCA main extern double atof strcpy uid arr scott uid len strlen uid arr
229. ON set operator 5 6 UPDATE statement RETURNING clause 5 55 syntax 11 151 URL universal resource locator 8 17 user session 5 44 user defined exception 6 6 user defined record 4 28 declaring 4 30 referencing 4 31 user defined subtype 2 22 UTL_FILE package 8 17 UTL_HTTP package 8 17 V VALUE operator 9 32 VALUE_ERROR exception 6 6 VARCHAR subtype 2 17 VARCHARZ2 datatype 2 16 VARCHAR2 semantics C 1 variable assigning values 2 40 declaring 2 28 initializing 2 40 session specific 8 11 syntax 11 29 VARIANCE group function 5 3 varray size limit 4 5 VARRAY datatype 4 4 visibility of package contents 8 2 versus scope 2 37 WwW WHEN clause 3 7 6 15 WHILE loop 3 9 wildcard 2 45 WITH CONTEXT clause 10 5 10 16 words reserved F 1 work area query 5 19 Z ZERO_DIVIDE exception 6 6 Index 15 Index 16
230. ONNECT username IDENTIFIED BY password printf nConnected to Oracle as user s n n username printf Enter department number scanf Sd amp dept_no fflush stdin Print column headers printf n n printf 10 10s 10 10s s n Employee Job Salary printf 10 10s 10 10s s n eae ONE Eg B 24 PL SQL User s Guide and Reference Sample 6 Calling a Stored Procedure Set the array size array_size 10 done_flag 0 num_ret 0 Array fetch loop ends when NOT FOUND becomes true for EXEC SQL EXECUTE emp_name job salary END END E EC print_rows num_ret if done_flag break Disconnect from Oracle EXEC SQL COMMIT WORK RELEASE exit 0 print_rows n int n int i if n 0 printf No rows retrieved n return for i 0 i lt n i printf 10 10s 10 10s 6 2f n emp_name i job i salary i BEGIN personnel get_employees dept_no array_size num_ret done_flag Sample Programs B 25 Sample 6 Calling a Stored Procedure sqlerror EC SQL WHENEVER SOLERROR CONTINUE printf nOracle error detected printf n 70s An sqlca sqlerrm sqlerrmc EXEC SQL ROLLBACK WORK RELEASE exit 1
231. OP and EXIT Statements What happens if the lower bound of a loop range evaluates to a larger integer than the upper bound As the next example shows the sequence of statements within the loop is not executed and control passes to the next statement limit becomes 1 FOR i IN 2 limit LOOP sequence_of_statements xecutes zero times END LOOP control passes here Scope Rules The loop counter is defined only within the loop You cannot reference it outside the loop After the loop is exited the loop counter is undefined as the following example shows FOR ctr IN 1 10 LOOP END LOOP sum ctr 1 illegal You need not explicitly declare the loop counter because it is implicitly declared as a local variable of type INTEGER The next example shows that the local declaration hides any global declaration DECLARE ctr INTEGER BEGIN FOR ctr IN 1 25 LOOP IF ctr gt 10 THEN refers to loop counter END LOOP END To reference the global variable in this example you must use a label and dot notation as follows lt lt main gt gt DECLARE ctr INTEGER BEGIN FOR ctr IN 1 25 LOOP Control Structures 3 13 Iterative Control LOOP and EXIT Statements IF main ctr gt 10 THEN refers to global variable END LOOP END main The same scope rules apply to nested FOR loops Consider the example below
232. ORD emp_id BER 4 emp_name CHAR 10 job_title CHAR 9 1 1 dept_name CHAR 14 dept_loc CHAR 13 TYPE EmpCurTyp IS REF CURSOR RETURN EmpRecTyp PROCEDURE get_staff dept_no IN NUMBER emp_cv IN OUT EmpCurTyp END CREATE PACKAGE BODY emp_data AS PROCEDURE get_staff dept_no IN NUMBER emp_cv IN OUT EmpCurTyp IS BEGIN OPEN emp_cv FOR SELECT empno ename job dname loc FROM emp dept WHERE emp deptno dept_no AND mp deptno dept deptno R BY empno ORD ESI COLUMN EMPNO HEADING Number COLUMN ENAME HEADING Name COLUMN JOB HEADING JobTitle COLUMN DNAME HEADING Department COLUMN LOC HEADING Location SET AUTOPRINT ON VARIABLE cv REFCURSOR EXECUTE emp_data get_staff 20 cv 5 32 PL SQL User s Guide and Reference Using Cursor Variables Reducing Network Traffic When passing host cursor variables to PL SQL you can reduce network traffic by grouping OPEN FOR statements For example the following PL SQL block opens five cursor variables in a single round trip anonymous PL SQL block in host environment BEGIN OPEN emp_cv FOR SELECT FROM emp OPEN dept_cv FOR SELECT FROM dept OPEN grade_cv FOR SELECT FROM salgrade OPEN pay_cv FO
233. PE my_rowid ROWID BEGIN OPEN cl LOOP FETCH cl INTO my_ename my_job my_rowid EXIT WHEN c1SNOTFOUND UPDATE emp SET sal sal 1 05 WHERE rowid my_rowid this mimics WHERE CURRENT OF cl COMMIT END LOOP CLOSE cl END Interaction with Oracle 5 53 Processing Transactions Be careful In the last example the fetched rows are not locked because no FOR UPDATE clause is used So other users might unintentionally overwrite your changes Also the cursor must have a read consistent view of the data so rollback segments used in the update are not released until the cursor is closed This can slow down processing when many rows are updated The next example shows that you can use the SROWTYPE attribute with cursors that reference the ROWID pseudocolumn DECLARE CURSOR cl IS SELECT ename sal rowid FROM emp emp_rec c1 ROWTYPE BEGIN OPEN cl LOOP FETCH cl INTO emp_rec EXIT WHEN cl NOTFOUND IF THEN DELETE FROM emp WHERE rowid emp_rec rowid END IF END LOOP CLOSE cl Improving Performance This section gives several techniques for improving performance and explains how your applications can use them Use Object Types and Collections Collection types see Chapter 4 and object types see Chapter 9 increase your productivit
234. PL SQL User s Guide and Reference Release 8 0 December 1997 Part No A58236 01 ORACLE Enabling the Information Age PL SQL User s Guide and Reference Part No A58236 01 Release 8 0 Copyright 1997 Oracle Corporation All rights reserved Author Tom Portfolio Graphics Designer Val Moore Contributors Dave Alpern Cailein Barclay Gray Clossman Ervan Darnell Jacco Draaijer John Frazzini Radhakrishna Hari Ken Jacobs Kannan Muthukkaruppan Dmitry Nizhegorodov Olga Peschansky Dave Posner Shirish Puranik Ken Rudin Tim Smith Usha Sangam Peter Vasterd The programs are not intended for use in any nuclear aviation mass transit medical or other inherently dangerous applications It shall be licensee s responsibility to take all appropriate fail safe back up redundancy and other measures to ensure the safe use of such applications if the Programs are used for such purposes and Oracle disclaims liability for any damages caused by such use of the Programs This Program contains proprietary information of Oracle Corporation it is provided under a license agreement containing restrictions on use and disclosure and is also protected by copyright patent and other intellectual property law Reverse engineering of the software is prohibited The information contained in this document is subject to change without notice If you find any problems in the documentation please report them to us in writing Oracle C
235. PL SQL subprogram that registered the external procedure Such calls which you code in the usual way can appear in anonymous blocks a stand alone and packaged subprograms a methods of an object type External Procedures 10 5 Calling an External Procedure a database triggers a SOL statements calls to packaged functions only Note To call a packaged function from SQL statements you must use the pragma RESTRICT_REFERENCES which asserts the purity level of the function the extent to which the function is free of side effects PL SQL cannot check the purity level of the corresponding external routine So make sure the routine does not violate the pragma Otherwise you might get unexpected results For more information about the pragma see Oracle8 Application Developer s Guide Any PL SQL block or subprogram executing on the server side or on the client side for example in a Developer 2000 tool such as Oracle Forms can call an external procedure The only requirement is that you call the external procedure from C code On the server side the external procedure runs in a separate process address space which safeguards your database Figure 10 1 shows how Oracle8 and an external procedure interact Figure 10 1 Oracle8 Interacting with an External Procedure 1 PL SQL 1 _ gt Code C Code Oracle Database i i External Process Oracle Address Spac
236. PTION WHEN past_due THEN does not handle RAISEd exception END Error Handling 6 7 User Defined Exceptions The enclosing block does not handle the raised exception because the declaration of past_due in the sub block prevails Though they share the same name the two past_due exceptions are different just as the two acct_num variables share the same name but are different variables Therefore the RAISE statement and the WHEN clause refer to different exceptions To have the enclosing block handle the raised exception you must remove its declaration from the sub block or define an OTHERS handler Using EXCEPTION_INIT To handle unnamed internal exceptions you must use the OTHERS handler or the pragma EXCEPTION_INIT A pragma is a compiler directive which can be thought of as a parenthetical remark to the compiler Pragmas also called pseudoinstructions are processed at compile time not at run time For example in the language Ada the following pragma tells the compiler to optimize the use of storage space pragma OPTIMIZE SPACE In PL SQL the pragma EXCEPTION_INIT tells the compiler to associate an exception name with an Oracle error number That allows you to refer to any internal exception by name and to write a specific handler for it You code the pragma EXCEPTION_INIT in the declarative part of a PL SQL block subprogram or package using the syntax PRAGMA EXCEPTION_I
237. Passing Parameters to an External Procedure Passing parameters to an external procedure is complicated by several circumstances a The set of PL SQL datatypes does not correspond one to one with the set of C datatypes a PL SQL parameters can be NULL whereas C parameters cannot Unlike C PL SQL includes the RDBMS concept of nullity a The external procedure might need the current length or maximum length of CHAR LONG RAW RAW and VARCHAR2 parameters a The external procedure might need character set information about CHAR VARCHAR2 and CLOB parameters a PL SQL might need the current length maximum length or null status of values returned by the external procedure In the following sections you learn how to specify a parameter list that deals with these circumstances Specifying Datatypes You do not pass parameters to an external procedure directly Instead you pass them to the PL SQL subprogram that registered the external procedure So you must specify PL SQL datatypes for the parameters For guidance see Table 10 1 Each PL SQL datatype maps to a default external datatype In turn each external datatype maps to a C datatype PL SQL does all the datatype conversions for you Table 10 1 Parameter Datatype Mappings PL SQL Type Supported External Types Default External Type BINARY_INTEGER UNSIGNED CHAR INT BOOLEAN UNSIGNED SHORT PLS_INTEGER UNSIGNED INT UNSIGNED LONG
238. R SELECT FROM payroll OPEN ins_cv FOR SE FROM insurance END Q This might be useful in Oracle Forms for instance when you want to populate a multi block form When you pass host cursor variables to a PL SQL block for opening the query work areas to which they point remain accessible after the block completes That allows your OCI or Pro C program to use these work areas for ordinary cursor operations In the following example you open several such work areas in a single round trip BEGIN OPEN c1 FOR SELECT 1 FROM dual OPEN c2 FOR SELECT 1 FROM dual OPEN c3 FOR SELECT 1 FROM dual OPEN c4 FOR SELECT 1 FROM dual OPEN c5 FOR SELECT 1 FROM dual END The cursors assigned to c1 c2 c3 c4 and c5 behave normally and you can use them for any purpose When finished simply release the cursors as follows BEGI CLOSE cl CLOSE c2 CLOSE c3 CLOSE c4 CLOSE c5 END Interaction with Oracle 5 33 Using Cursor Variables Avoiding Exceptions If both cursor variables involved in an assignment are strongly typed they must have the same datatype In the following example even though the cursor variables have the same return type the assignment raises an exception because they have different datatypes DECLARE YPE EmpCurTyp IS REF CURSOR RI YPE TmpCurTyp IS REF CURSOR RI
239. R STATEMENT POSITIVE STDDEV POSITIVEN SUBTYPE PRAGMA SUCCESSFUL PRIOR SUM PRIVATE SYNONYM PRIVILEGES SYSDATE PROCEDURE TABAUTH PUBLIC TABLE RAISE TABLES RANGE TASK RAW TERMINATE REAL THEN RECORD TO REF TRIGGER RELEASE TRUE REMR TYPE RENAME UID RESOURCE UNION RETURI UNIQUE REVERSE UPDATE REVOKE USE ROLLBACK USER ROW VALIDATE ROWID VALUES ROWLABEL VARCHAR ROWNUM VARCHAR2 ROWS VARIANCE ROWTYPE VIEW RUN VIEWS SAVEPOINT WHEN SCHEMA WHENEVER SELECT WHERE SEPERATE WHILE SESSION WITH SET WORK SHARE WRITE SIGNTYPE XOR SMALLINT SPACE Symbols lt lt gt gt E addition identity operator 2 3 assignment operator 1 4 2 4 association operator 2 4 7 12 attribute indicator 1 7 2 3 character string delimiter 2 3 component selector 1 6 2 3 concatenation operator 2 4 2 46 division operator 2 3 exponentiation operator 2 4 expression or list delimiter 2 3 expression or list delimiter 2 3 host variable indicator 2 3 item separator 2 3 label delimiter 2 4 label delimiter 2 4 multi line comment delimiter 2 4 multi line comment delimiter 2 4 multiplication operator 2 3 quoted identifier delimiter 2 3 range operator 2 4 3 10 relational operator 2 3 2 45 relational operator 2 3 2 45 relational operator 2 3 2 45 relational operator 2 4 2 45 relational operator 2 4 2 45 relational operator 2 4 2 45 relational operator
240. R and NVARCHAR2 which store NLS data With NLS number and date formats adapt automatically to the language conventions specified for a user session So users around the world can interact with Oracle in their native languages NLS is discussed in Oracle8 Reference Besides the database character set which is used for identifiers and source code PL SQL now supports a second character set called the national character set which is used for NLS data The PL SQL datatypes NCHAR and NVARCHAR2 allow you to store character strings formed from the national character set For more information see Datatypes on page 2 10 New Features A 3 NLS Types A 4 PL SQL User s Guide and Reference B Sample Programs This appendix provides several PL SQL programs to guide you in writing your own The sample programs illustrate several important PL SQL concepts and features Major Topics Running the Programs Sample 1 FOR Loop Sample 2 Cursors Sample 3 Scoping Sample 4 Batch Transaction Processing Sample 5 Embedded PL SQL Sample 6 Calling a Stored Procedure Sample Programs B 1 Running the Programs Running the Programs All the sample programs in this appendix and several others throughout this guide are available online So they are preceded by the following comment available online in file lt filename gt You can find the online files in the PL SOL demo directory For the location of the
241. R2 PROCEDURE journalize amount NUMBER trans_date BER END journal_entries CREATE PACKAGE BODY journal_entries AS PROCEDURE journalize amount NUMBER trans_date VARCHAR2 IS BEGI INSI RT INTO journal UES amount TO_DATE trans_date DD MON YYYY END journalize PROCEDURE journalize amount NUMBER trans_date BER IS E E 8 14 PL SQL User s Guide and Reference Package STANDARD BEGIN INSERT INTO journal VALUES amount TO_DATE trans_date J END journalize END journal_entries The first procedure accepts t rans_date as a character string while the second procedure accepts it as a number the Julian day Yet each procedure handles the data appropriately Package STANDARD A package named STANDARD defines the PL SQL environment The package specification globally declares types exceptions and subprograms which are available automatically to every PL SQL program For example package STANDARD declares the following built in function named ABS which returns the absolute value of its argument FUNCTION ABS n BER RETURN BER The contents of package STANDARD are directly visible to applications So you can call ABS from a database trigger a stored subprogram an Oracle Precompiler a
242. REF Person taxpayer_id VARCHAR2 9 BEGI SELECT REF p p ss_number INTO p_ref taxpayer_id FROM persons p WHERE p last_name Parker must return one row In the final example you update the attributes of a Person object DECLARE p_ref REF Person my_last_name VARCHAR2 15 BEGIN Object Types 9 33 Manipulating Objects SELECT REF p INTO p_ref FROM persons p WHERE p last_name my_last_name UPDATE persons p SET p Person Jill Anders 11 NOV 67 WHERE REF p p ref Testing for Dangling Refs If the object to which a ref points is deleted the ref is left dangling pointing to a nonexistent object To test for this condition you can use the SQL predicate IS DANGLING For example suppose column manager in relational table department holds refs to Employee objects stored in an object table You can use the following UPDATE statement to convert any dangling refs into nulls BEGIN UPDATE department SET manager NULL WHERE manager IS DANGLING Using Operator DEREF You cannot navigate through refs within PL SQL procedural statements Instead you must use the operator DEREF in a SQL statement DEREF is short for dereference When you dereference a pointer you get the value to which it points DEREF takes as its argument a reference to an object then returns the valu
243. RN t1 IS n ER BEGIN n m 1 unqualified name n packl m 2 dot separated chain of identifiers package name used as scope qualifier followed by variable name n pack1 f1 pl 3 dot separated chain of identifiers package name used as scope GE qualifier followed by function name oo also used as scope qualifier S followed by parameter name n vl a 4 dot separated chain of identifiers variable name followed by component selector n packl vl a 5 dot separated chain of identifiers E package name used as scope gt qualifier followed by EE variable name followed by component selector n v2 10 a 6 indexed name followed by component selector n f1 10 a 7 function call followed by component selector n 2 10 10 a 8 function call followed by indexing followed by component selector Name Resolution E 3 Various Forms of References n scott pack1 f2 10 10 a 9 function call which is a dot gt separated chain of identifiers including schema name used as E scope qualifier followed by package name used as scope qualifier followed by function name followed by component selector od of the returned result followed by indexing followed by component selector END FUNCTION f2 ql NUMBER RETURN t2 IS BEGIN NULL END END CREATE OR REPLACE PACKAGE BODY pack1
244. SOR type you can declare cursor variables of that type Yu can use TYPE to provide the datatype of a record variable Also in the RETURN clause of a REF CURSOR type definition you can use SROWTYPE to specify a record type that represents a row returned by a strongly not weakly typed cursor variable You use three statements to control a cursor variable OPEN FOR FETCH and CLOSE First you OPEN a cursor variable FOR a multi row query Then you FETCH rows from the result set one at a time When all the rows are processed you CLOSE the cursor variable Other OPEN FOR statements can open the same cursor variable for different queries You need not close a cursor variable before reopening it When you reopen a cursor variable for a different query the previous query is lost 11 40 PL SQL User s Guide and Reference Cursor Variables PL SQL makes sure the return type of the cursor variable is compatible with the INTO clause of the FETCH statement For each column value returned by the query associated with the cursor variable there must be a corresponding type compatible field or variable in the INTO clause Also the number of fields or variables must equal the number of column values Otherwise you get an error If both cursor variables involved in an assignment are strongly typed they must have the same datatype However if one or both cursor variables are weakly typed they need not h
245. SUBSTR 750 dollars 1 3 valid FALSE The second way to assign values to a variable is to select or fetch database values into it In the following example you have Oracle compute a 10 bonus when you select the salary of an employee SELECT sal 0 10 INTO bonus FROM emp WHERE empno emp_id Then you can use the variable bonus in another computation or insert its value into a database table Declaring Constants Declaring a constant is like declaring a variable except that you must add the keyword CONSTANT and immediately assign a value to the constant Thereafter no more assignments to the constant are allowed In the following example you declare a constant named credit_limit credit_limit CONSTANT REAL 5000 00 1 4 PL SQL User s Guide and Reference Main Features Cursors Oracle uses work areas to execute SQL statements and store processing information A PL SQL construct called a cursor lets you name a work area and access its stored information There are two kinds of cursors implicit and explicit PL SQL implicitly declares a cursor for all SQL data manipulation statements including queries that return only one row For queries that return more than one row you can explicitly declare a cursor to process the rows individually An example follows DECLARE CURSOR c1 IS SELECT empno ename job FROM emp WHERE deptno 20 The set of r
246. Second if you start a transaction that you cannot finish because an exception is raised or a SOL statement fails a rollback lets you return to the starting point to take corrective action and perhaps try again Consider the example below in which you insert information about an employee into three different database tables All three tables have a column that holds employee numbers and is constrained by a unique index If an INSERT statement tries to store a duplicate employee number the predefined exception DUP_VAL_ON_INDExX is raised In that case you want to undo all changes So you issue a rollback in the exception handler DECLARE emp_id INTEGER BEGI SELECT empno INTO emp_id FROM new_emp WHERE INSERT INTO emp VALUES emp_id INSERT INTO tax VALUES emp_id INSERT INTO pay VALUES emp_id EXCEPTION WHEN DUP_VAL ON_INDEX THEN ROLLBACK END Statement Level Rollbacks Before executing a SQL statement Oracle marks an implicit savepoint Then if the statement fails Oracle rolls it back automatically For example if an INSERT statement raises an exception by trying to insert a duplicate value in a unique index the statement is rolled back Only work started by the failed SQL statement is lost Work done before that statement in the current transaction is kept Oracle can also roll back sin
247. T uid EPT record BONUS record EXEC SQL WHENEVER SQLERROR DO sql_error El El Interaction with Oracle 5 29 Using Cursor Variables Initialize cursor variable ALLOCAT EXEC SQ if EX Exit EC SQL WH generic_cv loop when done fetching T ENI Gir for printf printf gets temp table_num table_num lt 0 break if n1 Ani r atoi EMP 2 D Enter table number 0 to quit R NOT FOUND DO break EPT 3 BONUS temp Open cursor variable EXEC SQL EXECUTE BEGIN IF table_num 1 THEN OPEN generic_cv FOR SELECT FROM emp ELSIF table_num 2 THEN OPEN generic_cv FOR SELECT FROM dept ELSIF table_num 3 THEN OPEN generic_cv FOR SELECT FROM bonus END IF END END E EC for 55 switch table_num case 1 Fetch row into EMP record EXEC SQL FETCH generic_cv INTO emp_rec break case 2 Fetch row into DEPT record EXEC SQL FETCH generic_cv INTO dept_rec break case 3 Fetch row into BONUS record EXEC SQL FETCH generic_cv INTO bonus_rec break Process data record here Close cursor variable EXEC SQL CLOSE generic_cv 5 30 PL SQL
248. T sal comm FROM emp WHERE deptno dnum total_wages NUMBER 11 2 0 high paid NUMBER 4 0 higher_comm NUMBER 4 0 BEGIN The number of iterations will equal the number of rows returned by emp_cursor FOR emp record IN emp cursor 20 LOOP emp_record comm NVL emp_record comm 0 total_wages total_wages emp_record sal emp_record comm IF emp_record sal gt 2000 00 THEN high_paid high_paid 1 END IF IF emp_record comm gt emp_record sal THEN higher_comm higher_comm 1 END IF END LOOP INSERT INTO temp VALUES high_paid higher_comm Total Wages TO CHAR total_wages COMMIT END Using Cursor Variables Like a cursor a cursor variable points to the current row in the result set of a multi row query But cursors differ from cursor variables the way constants differ from variables Whereas a cursor is static a cursor variable is dynamic because it is not tied to a specific query You can open a cursor variable for any type compatible query This gives you more flexibility Also you can assign new values to a cursor variable and pass it as a parameter to subprograms including subprograms stored in an Oracle database This gives you an easy way to centralize data retrieval 5 18 PL SQL User s Guide and Reference Using Cursor Variables Cursor variables are
249. THERS THEN NULL 11 102 PL SQL User s Guide and Reference Object Types Object Types Syntax An object type is a user defined composite datatype that encapsulates a data structure along with the functions and procedures needed to manipulate the data The variables that form the data structure are called attributes The functions and procedures that characterize the behavior of the object type are called methods Currently you cannot define object types within PL SQL They must be CREATEd and stored in an Oracle database where they can be shared by many programs When you define an object type in SQL Plus for example using the CREATE TYPE statement you create an abstract template for some real world object The template specifies only those attributes and behaviors the object will need in the application environment The data structure formed by the set of attributes is public visible to client programs However well behaved programs do not manipulate it directly Instead they use the set of methods provided That way the data is kept ina proper state At run time when the data structure is filled with values you have created an instance of an object type You can create as many instances usually called objects as you need For more information see Chapter 9 object_type attribute_type MEMBER restrict_references_pragma Language Elements 11 103
250. UNCTION full RETURN BOOLEAN EMBER PROCEDURE push n IN INTEGER CREATE TYPE BODY Stack AS MEMBER PROCEDURE push n IN INTEGER IS EGI IF NOT full THEN top top 1 w END push END Parameter SELF All methods in an object type accept an instance of that type as their first parameter The name of this built in parameter is SELF Whether declared implicitly or explicitly SELF is always the first parameter passed to a method For example method transform declares SELF as an IN OUT parameter CREATE TYPE Complex AS OBJECT MEMBER FUNCTION transform SELF IN OUT Complex UY 9 8 PL SQL User s Guide and Reference Components of an Object Type In member functions if SELF is not declared its parameter mode defaults to IN However in member procedures if SELF is not declared its parameter mode defaults to IN OUT You cannot specify a different datatype for SELF In a method body S1 ELF denotes the object whose method was called As the following example shows methods can reference the attributes of SELF without a qualifier CREATE FUNCTION gcd ans INTEGER BEGI IF y lt x AND SIF x lt y THEN T END IF RETURN ans
251. URE push n IN INTEGER IS push integer onto stack IF NOT full THEN top top 1 position top n ELSE stack is full RAISE_APPLICATION ERROR 20101 stack overflow END IF END push EMBER PROCEDURE pop n OUT INTEGER IS pop integer off stack and return its value BEGIN IF NOT empty THEN n position top top top 1 ELSE stack is empty RAISE_APPLICATION_ERROR 20102 stack underflow END IF END pop END Notice that in member procedures push and pop we use the built in procedure raise_application_error to issue user defined error messages That way we can report errors to the client program and avoid returning unhandled exceptions to the host environment The following example shows that you can nest object types CREATE TYPE Address AS OBJ city VARCHAR2 15 state CHAR 2 zip_code INTEGER Language Elements 11 109 Object Types CREATE TYPE Person AS OBJECT first_name VARCHARZ2 15 last_name VARCHAR2 15 birthday DATE home_address Address nested object typ phone_number VARCHAR2 15 ss_number INTEGER Related Topics Functions Packages Procedures 11 110 PL SQL User s Guide and Reference OPEN Statement OPEN Statement Syntax The OPEN statement executes the multi row q
252. URSOR emp_cur my_ename CHAR my_comm NUMBER DEFAULT 0 IS SELECT FROM emp WHERE any of the following statements opens the cursor EE OPEN emp cur L OPEN emp_cur BLAKE 300 OPEN emp_cur employee_name 150 CLOSE Statement Cursors FETCH Statement LOOP Statements 11 112 PL SQL User s Guide and Reference OPEN FOR Statement OPEN FOR Statement Syntax The OPEN FOR statement executes the multi row query associated with a cursor variable It also allocates resources used by Oracle to process the query and identifies the result set which consists of all rows that meet the query search criteria The cursor variable is positioned before the first row in the result set For more information see Using Cursor Variables on page 5 18 open_for_statement OPEN o select_statement C host_cursor_variable_name Keyword and Parameter Description cursor_variable_name This identifies a cursor variable or parameter previously declared within the current scope host_cursor_variable_ name This identifies a cursor variable previously declared in a PL SQL host environment and passed to PL SQL as a bind variable The datatype of the host cursor variable is compatible with the return type of any PL SQL cursor variable Host variables must be prefixed with a colon select_statement This is a query associated with cursor_variable which returns a set
253. User s Guide and Reference Using Cursor Variables Example 4 exit 0 void sql_error Handle SQL error here A host variable is a variable you declare in a host environment then pass to one or more PL SQL programs which can use it like any other variable In the SQL Plus environment to declare a host variable you use the command VARIABLE For example you declare a variable of type NUMBER as follows VARIABLE return_code NUMBER Both SOL Plus and PL SQL can reference the host variable and SOL Plus can display its value Note If you declare a host variable with the same name as a PL SQL program variable the latter takes precedence To reference a host variable in PL SQL you must prefix its name with a colon as the following example shows return_code 0 IF credit_check_ok acct_no THEN return_code 1 END IF To display the value of a host variable in SQL Plus you use the PRINT command as follows SQL gt PRINT return_code Interaction with Oracle 5 31 Using Cursor Variables In the script below you declare a host variable of type REFCURSOR The SQL Plus datatype REFCURSOR lets you declare cursor variables which you can use to return query results from stored subprograms You use the SOL Plus command SET AUTOPRINT ON to display the query results automatically CREATE PACKAGE emp_data AS TYPE EmpRecTyp IS REC
254. WHERE CURRENT OF trans cursor END LOOP END apply _transactions 1 PROCEDURE enter transaction Add a transaction to transactions table acct ER kind CHAR amount BER IS BEGIN INSERT INTO transactions VALUES acct kind amount Pending SYSDATE END enter transaction Define local procedures available only in package PROCEDURE do_journal_entry Record transaction in journal acct UMBER kind CHAR new_bal NUMBER IS BEGIN INSERT INTO journal VALUES acct kind new_bal sysdate IF kind D THEN new_status Debit applied ELSE new_status Credit applied END IF END do_journal_entry PROCEDURE credit_account acct NUMBER credit REAL IS Credit account unless account number is bad old_balance NUMBER 8 12 PL SQL User s Guide and Reference Some Examples new_balance NU new_balance UPDATE accounts S WHERE acct_id acct ER old_balance credit do_journal_entry acct C new_balance EXCEPTIO WHEN new_status O_DATA FOUND THEN Bad account number WHEN OTHERS THEN new_status END credit_account SUBSTR S
255. When it includes deleted elements the internal size of a nested table differs from the values returned by COUNT and LAST For instance if you initialize a nested table with five elements then delete elements 2 and 5 the internal size is 5 COUNT returns 3 and LAST returns 4 All deleted elements whether leading medial or trailing are treated alike This procedure has two forms TRIM removes one element from the end of a collection TRIM n removes n elements from the end of a collection For example the following statement removes the last three elements from nested table courses courses TRIM 3 If nis greater than COUNT TRIM n raises SUBSCRIPT_BEYOND_COUNT TRIM operates on the internal size of a collection So if TRIM encounters deleted elements it includes them in its tally Consider the following example DECLARE YPE CourseList IS TABLE OF VARCHAR2 10 courses CourseList BEGIN courses CourseList Biol 4412 Psyc 3112 Anth 3001 courses DELETE courses LAST delete element 3 At this point COUNT equals 2 the number of valid elements remaining So you might expect the next statement to empty the nested table by trimming elements 1 and 2 Instead it trims valid element 2 and deleted element 3 because TRIM includes deleted elements in its tally courses TRIM courses COUNT DBMS_OUTPUT PUT_LINE courses 1 prints Biol 4412
256. When you select a RAW or LONG RAW column value into a CHAR or VARCHAR2 variable PL SQL must convert the internal binary value to a character value In this case PL SQL returns each binary byte of RAW or LONG RAW data as a pair of characters Each character represents the hexadecimal equivalent of a nibble half a byte For example PL SQL returns the binary byte 11111111 as the pair of characters FF The function RAWTOHEX does the same conversion A conversion is also necessary when you insert a CHAR or VARCHAR2 value into a RAW or LONG RAW column Each pair of characters in the variable must represent the hexadecimal equivalent of a binary byte If either character does not represent the hexadecimal equivalent of a nibble PL SQL raises an exception NLS Values When passed an uppercase character set name the built in function NLS_CHARSET_ID returns the corresponding character set ID number Conversely when passed a character set ID number the function NLS_CHARSET_NAME returns the corresponding character set name If you pass the value CHAR_CS or NCHAR_CS to NLS_CHARSET_ 1D it returns the database or national character set ID number respectively For a list of character set names see Oracle8 Reference Declarations Your program stores values in variables and constants As the program executes the values of variables can change but the values of constants cannot You can declare variables and constant
257. When you use a SELECT INTO statement to assign values to variables it should return only one row If it returns more than one row you get the following results PL SQL raises the predefined exception TOO_MANY_ROWS SQLCODE returns 1422 Oracle error code ORA 01422 SQLERRM returns the Oracle error message single row query returns more than one row E SOL NOTFOUND yields FALS SOL FOUND yields TRUE SQLSROWCOUNT yields 1 If no rows are returned you get these results PL SQL raises the predefined exception NO_DATA_FOUND unless the SELECT statement called a SOL group function such as AVG or SUM SQL group functions always return a value or a null So a SELECT INTO statement that calls a group function never raises NO_DATA_FOUND SQLCODE returns 100 Oracle error code ORA 01403 SOLERRM returns the Oracle error message no data found SQLSNOTFOUND yields TRUE SQLSFOUND yields FALSE SOLSROWCOUNT yields 0 The following SELECT statement returns an employee s name job title and salary from the emp database table SELECT ename job sal INTO my_ename my_job my_sal FROM emp WHERE empno my_empno Assignment Statement FETCH Statement ROWTYPE Attribute Language Elements 11 141 SET TRANSACTION Statement SET TRANSACTION Statement Syntax The SET TRANSACTION statement begins a read only or read write transaction establishes an isolation level
258. XLEN CHARSETID CHARSETFORM Understanding the EXTERNAL Clause The EXTERNAL clause is the interface between PL SQL and an external procedure The following subclauses tell PL SQL where to find the procedure how to call it and what to pass it Only the LIBRARY subclause is required LIBRARY Specifies a local alias library You cannot use a database link to specify a remote library The library name is a PL SQL identifier So if you enclose the name in double quotes it becomes case sensitive By default the name is stored in upper case You must have EXECUTE privileges on the alias library NAME Specifies the external procedure to be called If you enclose the procedure name in double quotes it becomes case sensitive By default the name is stored in upper case If you omit this subclause the procedure name defaults to the upper case name of the PL SQL subprogram LANGUAGE Specifies the third generation language in which the external procedure was written Currently only the language name C is allowed If you omit this subclause the language name defaults to C CALLING STANDARD Specifies the Windows NT calling standard C or Pascal under which the external procedure was compiled Under the Pascal Calling Standard arguments are reversed on the stack and the called function must pop the stack If you omit this subclause the calling standard defaults to C 10 4 PL SQL User s Guid
259. _messageto pack a message into a pipe then send it to another session in the same instance At the other end of the pipe you can use the procedures receive_message and unpack_message to receive and unpack read the message Named pipes are useful in many ways For example you can write routines in C that allow external servers to collect information then send it through pipes to procedures stored in an Oracle database Package UTL_FILE allows your PL SQL programs to read and write operating system OS text files It provides a restricted version of standard OS stream file I O including open put get and close operations When you want to read or write a text file you call the function fopen which returns a file handle for use in subsequent procedure calls For example the procedure put_line writes a text string and line terminator to an open file The procedure get_Jine reads a line of text from an open file into an output buffer PL SQL file I O is available on both the client and server sides However on the server side file access is restricted to those directories explicitly listed in the accessible directories list which is stored in the Oracle initialization file Package UTL_HTTP allows your PL SQL programs to make hypertext transfer protocol HTTP callouts You can use it to retrieve data from the internet or to call Oracle Web Server cartidges The package has two entry points each of which accepts a URL unive
260. a is found Input Table SQL gt SELECT ename empno sal FROM emp ORDER BY sal DESC ENAME EMPNO SAL KING 7839 5000 SCOTT 7788 3000 FORD 7902 3000 JONES 7566 2975 BLAKE 7698 2850 CLARK 7782 2450 ALLE 7499 1600 TURNER 7844 1500 MILLER 7934 1300 WARD 7521 1250 MARTIN 7654 1250 ADAMS 7876 1100 JAMES 7900 950 SMITH 7369 800 14 records selected Stored Procedure available online in file sample6 include lt stdio h gt include lt string h gt typedef char asciz Sample Programs B 23 Sample 6 Calling a Stored Procedure EXEC SQL BEGIN DECLARE SECTION Define type for null terminated strings EXEC SQL TYPE asciz IS STRING 20 asciz username 20 asciz password 20 int dept_no which department to query char emp_name 10 21 char job 10 21 float salary 10 int done_flag int array_size int num_ret number of rows returned int SQLCODE EXEC SQL END DECLARE SECTION EXEC SQL INCLUDE sqlca int print_rows produces program output E int sqlerror handles unrecoverabl rrors main dint 15 Connect to Oracle strcpy username SCOTT strcpy password TIGER T EXEC SOL WHENE R SOLERROR DO sqlerror EXEC SQL C
261. a new instance of the FOR loop is created and another cursor is opened but prior cursors stay positioned on the next row in their result sets When a fetch fails to return a row the cursor is closed automatically and the FOR loop is exited Since the recursive call is inside the FOR loop the recursion stops PROCEDURE find_staff mgr_no NUMBER tier BER 1 IS boss_name CHAR 10 CURSOR cl boss_no BER IS SELECT empno ename FROM emp WHERE mgr boss_no Get manager s name SELECT ename INTO boss_name FROM emp WHERE empno mgr_no IF tier 1 THEN INSERT INTO staff single column output table VALUES boss_name manages the staff END IF Find staff members who report directly to manager FOR ee IN cl mgr_no LOOP INSERT INTO staff VALUES boss_name manages enam on tier to char tier Drop to next tier in organization find_staff ee empno tier 1 recursive call END LOOP COMMIT END Unlike the initial call each recursive call passes a second actual parameter the next tier to the procedure Subprograms 7 25 Recursion The last example illustrates recursion not the efficient use of set oriented SQL statements You might want to compare the performance of the recursive procedure to that of the follow
262. a sequence you can specify its initial value and an increment CURRVAL returns the current value in a specified sequence Before you can reference CURRVAL in a session you must use NEXTVAL to generate a number A reference to NEXTVAL stores the current sequence number in CURRVAL NEXTVAL increments the sequence and returns the next value To obtain the current or next value in a sequence you must use dot notation as follows sequence_name CURRVAL sequence_name NEXTVAL After creating a sequence you can use it to generate unique sequence numbers for transaction processing However you can use CURRVAL and NEXTVAL only ina select list the VALUES clause and the SET clause In the following example you use a sequence to insert the same employee number into two tables INSERT INTO emp VALUES empno_seq NEXTVAL my_ename INSERT INTO sals VALUES empno_seq CURRVAL my_sal If a transaction generates a sequence number the sequence is incremented immediately whether you commit or roll back the transaction 5 4 PL SQL User s Guide and Reference SQL Support LEVEL You use LEVEL with the SELECT CONNECT BY statement to organize rows from a database table into a tree structure LEVEL returns the level number of a node ina tree structure The root is level 1 children of the root are level 2 grandchildren are level 3 and so on You specify th
263. a Package You can debug enhance or replace a package body without changing the interface package specification to the package body To create packages and store them permanently in an Oracle database you use the CRI EAT E PACKAG E and CRI EATI E PACKAGI E BODY statements which you can execute interactively from SQL Plus or Enterprise Manager For more information see Oracle8 Application Developer s Guide In the example below you package a record type a cursor and two employment procedures Notice that the procedure hire_employee uses the database sequence empno_seqand the function SYSDATE to insert a new employee number and hire date respectively CREATE E Z PACKAGE emp actions AS TYPE EmpRecTyp IS RI CURSOR desc_salary RETURN PROCEDURE hire_employee ename VARCHAR2 job VARCHAR2 mgr BER sal BER comm BER deptno BER PROCEDURE fire_employee emp_id NU D emp_actions CREATE CURSOR des specification ECORD emp_id INTEGER salary REAL EmpRecTyp BER 7 PACKAGE BODY emp_actions AS c_salary RI PROCEDURE hire_employee ename VARCHAR2 job VARCHAR2 mgr BER sal BER comm BER deptno BER IS BEGIN INSERT
264. abase table DECLARE bonus REAL BEGIN FOR emp_rec IN SELECT empno sal comm FROM emp LOOP bonus emp_rec sal 0 05 emp_rec comm 0 25 INSERT INTO bonuses VALUES emp_rec empno bonus END LOOP COMMIT END Fields in the implicitly declared record hold column values from the most recently fetched row The fields have the same names as corresponding columns in the query select list But what happens if a select item is an expression Consider the following example CURSOR cl IS SELECT empno sal NVL comm 0 job FROM In such cases you must include an alias for the select item In the next example wages is an alias for the select item sal NVL comm 0 CURSOR c1 IS SELECT empno sal NVL comm 0 wages job FROM To reference the corresponding field you use the alias instead of a column name as follows IF emp_rec wages lt 1000 THEN Interaction with Oracle 5 17 Using Cursor Variables Passing Parameters You can pass parameters to the cursor used in a cursor FOR loop In the following example you pass a department number Then you compute the total wages paid to employees in that department Also you determine how many employees have salaries higher than 2000 and how many have commissions larger than their salaries available online in file examp8 DECLARE CURSOR emp_cursor dnum NUMBER IS SELEC
265. able One of the many uses for database triggers is to audit data modifications For example the following database trigger fires whenever salaries in the emp table are updated CREATE TRIGGER audit_sal AFTER UPDATE OF sal ON emp FOR EACH ROW BEGI INSERT INTO emp_audit VALUE END v You can use all the SQL data manipulation statements and any procedural statement in the executable part of a database trigger When it contains the PL SQL engine an application development tool can process PL SQL blocks The tool passes the blocks to its local PL SQL engine The engine executes all procedural statements at the application site and sends only SQL statements to Oracle Thus most of the work is done at the application site not at the server site Furthermore if the block contains no SQL statements the engine executes the entire block at the application site This is useful if your application can benefit from conditional and iterative control Frequently Oracle Forms applications use SQL statements merely to test the value of field entries or to do simple computations By using PL SQL instead you can avoid calls to the Oracle server Moreover you can use PL SQL functions to manipulate field entries 1 20 PL SQL User s Guide and Reference Advantages of PL SQL Advantages of PL SQL PL SQL is a completely portable high performance transaction processing language tha
266. able here a CHAR b d END identifiers available here a CHAR b END Recall that global identifiers can be redeclared in a sub block in which case the local declaration prevails and the sub block cannot reference the global identifier unless you use a qualified name The qualifier can be the label of an enclosing block as the following example shows lt lt outer gt gt DECLARE birthdate DATI BEGI DECLARE birthdate DATE BEGIN El se IF birthdate outer birthdate THEN As the next example shows the qualifier can also be the name of an enclosing subprogram PROCEDURE check_credit IS rating NUMBER FUNCTION valid RETURN BOOLEAN IS rating NUMBER BEGIN IF check_credit rating lt 3 THEN However within the same scope a label and a subprogram cannot have the same name Fundamentals 2 39 Assignments Assignments Variables and constants are initialized every time a block or subprogram is entered By default variables are initialized to NULL So unless you expressly initialize a variable its value is undefined as the following example shows DECLARE count INTEGER BEGIN count count 1 assigns a null to count The expression on the right of the assignment operator yields NULL because count is null To avoid unexpected results never reference a variab
267. ables that the current block can reference Example The following PL SQL block has two exception handlers DELARE bad_emp_id EXCEPTION bad_acct_no EXCEPTION BEGIN EXCEPTION WHEN bad_emp_id OR bad_acct_no THEN user defined ROLLBACK WHEN ZERO_DIVIDE THEN predefined INSERT INTO inventory VALUES part_number quantity COMMIT END Related Topics Blocks EXCEPTION_INIT Pragma RAISE Statement 11 56 PL SQL User s Guide and Reference EXIT Statement EXIT Statement Syntax You use the EXIT statement to exit a loop The EXIT statement has two forms the unconditional EXIT and the conditional EXIT WHEN With either form you can name the loop to be exited For more information see Iterative Control LOOP and EXIT Statements on page 3 6 exit_statement Keyword and Parameter Description Usage Notes EXIT An unconditional EXIT statement that is one without a WHEN clause exits the current loop immediately Execution resumes with the statement following the loop label_name This identifies the loop to be exited You can exit not only the current loop but any enclosing labeled loop boolean_expression This is an expression that yields the Boolean value TRUE FALSE or NULL It is evaluated with each iteration of the loop in which the EXIT WHEN statement appears If the expression
268. acle error messages FOR err_num IN 1 9999 LOOP err_msg SQLERRM err_num wrong should be err_num INSERT INTO errors VALUES err_msg END LOOP END Passing a positive number to SOLERRM always returns the message User Defined Exception 6 18 PL SQL User s Guide and Reference Handling Raised Exceptions unless you pass 100 in which case SQLERRM returns this message ORA 01403 no data found Passing a zero to SOLERRM always returns the following message ORA 0000 normal successful completion You cannot use SOLCODE or SOLERRM directly in a SQL statement Instead you must assign their values to local variables then use the variables in the SOL statement as the following example shows DECLARE err_num BER err_msg VARCHAR2 100 BEGIN EXCEPTION WHEN OTHERS THEN err_ num SQLCODE err_msg SUBSTR SQLERRM 1 100 INSERT INTO errors VALUES err_num err msg The string function SUBSTR ensures that a VALUE_ERROR exception for truncation is not raised when you assign the value of SOLERRM to err_msg SQLCODE and SQLERRM are especially useful in the OTHERS exception handler because they tell you which internal exception was raised Unhandled Exceptions Remember if it cannot find a handler for a raised exception PL SQL returns an unhandled exception erro
269. aged subprograms methods are called using dot notation In the example below you call method normalize which divides attributes num and den by their greatest common divisor DECLARE r Rational BEGIN r Rational 6 8 r normalize DBMS_OUTPUT PUT_LINE r num prints 3 As the example below shows you can chain method calls Execution proceeds from left to right First member function reciprocal is called then member procedure normalize is called DECLARE r Rational Rational 6 8 BEGIN r reciprocal normalize DBMS_OUTPUT PUT_LINE r num prints 4 Object Types 9 27 Sharing Objects In SQL statements calls to a parameterless method require an empty parameter list In procedural statements an empty parameter list is optional unless you chain calls in which case it is required for all but the last call You cannot chain additional method calls to the right of a procedure call because procedures are called as statements not as part of an expression For example the following statement is illegal r normalize reciprocal illegal Also if you chain two function calls the first function must return an object that can be passed to the second function Sharing Objects Most real world objects are considerably larger and more complex than objects of type Rational Consider the following object types CREATE TYPE Address AS OBJECT street_address VARCHAR2
270. ail For example to drive a car you need not know how its engine works A simple interface consisting of a gearshift steering wheel accelerator and brake lets you use the car effectively The details of what happens under the hood are not important for day to day driving Abstractions are central to the discipline of programming For example you use procedural abstraction when you suppress the details of a complex algorithm by writing a procedure and passing it parameters A single procedure call hides the details of your implementation To try a different implementation you simply replace the procedure with another having the same name and parameters Thanks to abstraction programs that call the procedure need not be modified You use data abstraction when you specify the datatype of a variable The datatype stipulates a set of values and a set of operations appropriate for those values For instance a variable of type POSITIVE can hold only positive integers and can only be added subtracted multiplied and so on To use the variable you need not know how PL SQL stores integers or implements arithmetic operations you simply accept the programming interface Object types are a generalization of the built in datatypes found in most programming languages PL SQL provides a variety of built in scalar and composite datatypes each of which is associated with a set of predefined operations A scalar type such as CHAR has no internal com
271. ake parameters which can appear in the associated query wherever constants can appear The formal parameters of a cursor must be IN parameters Therefore they cannot return values to actual parameters Also you cannot impose the NOT NULL constraint on a cursor parameter As the example below shows you can initialize cursor parameters to default values That way you can pass different numbers of actual parameters to a cursor accepting or overriding the default values as you please Also you can add new formal parameters without having to change every reference to the cursor DECLARE CURSOR cl low INTEGER DEFAULT 0 high INTEGER DEFAULT 99 IS SELECT The scope of cursor parameters is local to the cursor meaning that they can be referenced only within the query specified in the cursor declaration The values of cursor parameters are used by the associated query when the cursor is opened 5 10 PL SQL User s Guide and Reference Managing Cursors Opening a Cursor Opening the cursor executes the query and identifies the result set which consists of all rows that meet the query search criteria For cursors declared using the FOR UPDATE clause the OPEN statement also locks those rows An example of the OP statement follows GI N DECLARE CURSOR cl IS SELECT ename job FROM emp WHERE sal lt 3000 BEGIN OPEN cl END
272. al Exception handlers must come at the end of the block They are introduced by the keyword EXCEPTION The exception handling part of the block is terminated by the same keyword END that terminates the entire block An exception should be raised only when an error occurs that makes it impossible or undesirable to continue processing If there is no exception handler in the current block for a raised exception the exception propagates according to the following rules a If there is an enclosing block for the current block the exception is passed on to that block The enclosing block then becomes the current block If a handler for the raised exception is not found the process repeats If there is no enclosing block for the current block an unhandled exception error is passed back to the host environment However exceptions cannot propagate across remote procedure calls RPCs Therefore a PL SQL block cannot catch an exception raised by a remote subprogram For a workaround see Using raise_application_error on page 6 9 Language Elements 11 55 Exceptions Only one exception at a time can be active in the exception handling part of a block Therefore if an exception is raised inside a handler the block that encloses the current block is the first block searched to find a handler for the newly raised exception From there on the exception propagates normally An exception handler can reference only those vari
273. ame VARCHAR2 job VARCHAR2 mgr NUMBER sal NUMBER comm NUMBER deptno NUMBER R new_empno INTEG BEGIN 5 SELECT empno_seq NEXTVAL INTO new_empno FROM dual INSERT INTO emp VALUES new_empno ename job mgr SYSDATE umber_hired sal comm deptno Pal number_hired 1 ETURN new_empno hire employee Packages 8 9 Some Examples PROCEDURE fire_employee emp_id INTEGER IS BEGIN DELETE FROM emp WHERE empno emp_id ND fire employee E PROCEDURE raise_salary emp_id INTEGER increase NUMBER IS current_salary NUMBER BEGIN n Eg ECT sal INTO current_salary FROM emp WHERE empno emp_id IF current_salary IS NULL THEN RAISE salary_missing ELSE UPDATE emp SET sal sal increase WHERE empno emp_id END IF END raise_salary FUNCTION nth_highest_salary n INTEGER RETURN EmpRecTyp IS emp _ rec EmpRecTyp BEGIN OPEN desc_salary FOR i IN 1 n LOOP FETCH desc_salary INTO emp rec END LOOP CLOSE desc_salary RETURN emp_rec END nth_highest_salary Define local function available only in package FUNCTION rank emp id INTEGER job title VARCHAR2 RETURN INTEGER IS Return rank highest 1 of employee in a given job classification based on performance rat
274. amily PROCEDURE charge_back amount INTEGER IS BEGI PROCEDURE charge_back amount REAL IS Likewise you cannot overload two subprograms if their formal parameters differ only in subtype and the different subtypes are based on types in the same family For example you cannot overload the following procedures because the base types CHAR and LONG are in the same family DECLARE SUBTYPE Delimiter IS CHAR SUBTYPE Text IS LONG PROCEDURE scan x Delimiter IS PROCEDURE scan x Text IS 7 20 PL SQL User s Guide and Reference Overloading Finally you cannot overload two functions that differ only in return type the datatype of the result value even if the types are in different families For example you cannot overload the following functions FUNCTION acct_ok acct_id INTEGER RETURN BOOLEAN IS BEGIN END FUNCTION acct_ok acct_id INTEGER RETURN INTEGER IS BEGIN END How Calls Are Resolved Figure 7 1 shows how the PL SQL compiler resolves subprogram calls When the compiler encounters a procedure or function call it tries to find a declaration that matches the call The compiler searches first in the current scope and then if necessary in successive enclosing scopes The compiler stops searching if it finds one or more subpro
275. and Variables on page 11 29 11 128 PL SQL User s Guide and Reference Records Usage Notes DEFAULT This operator or keyword allows you to initialize fields to default values expression This is an arbitrarily complex combination of variables constants literals operators and function calls The simplest expression consists of a single variable For the syntax of expression see Expressions on page 11 59 When the declaration is elaborated the value of expression is assigned to the field The value and the field must have compatible datatypes You can define RECORD types and declare user defined records in the declarative part of any block subprogram or package Also a record can be initialized in its declaration as the following example shows DECLARE YPE TimeTyp IS RECORD second SMALLINT 0 minute SMALLINT 0 hour SMALLINT 0 The next example shows that you can use the TYPE attribute to specify a field datatype It also shows that you can add the NOT NULL constraint to any field declaration and so prevent the assigning of nulls to that field DECLARE YPE DeptRecTyp IS RECORD deptno BER 2 NOT NULL dname dept dnameSTYPE loc dept locSTYPE dept_rec DeptRecTyp To reference individual fields in a record you use dot notation For example you might assign a value to the dname field in the dept_rec record
276. andling Raised Exceptions Using SQLCODE and SQLERRM In an exception handler you can use the functions SQLCODE and SQLERRM to find out which error occurred and to get the associated error message For internal exceptions SOLCODE returns the number of the Oracle error The number that SQLCODE returns is negative unless the Oracle error is no data found in which case SOLCODE returns 100 SOLERRM returns the corresponding error message The message begins with the Oracle error code For user defined exceptions SOLCODE returns 1 and SOLERRM returns the message User Defined Exception unless you used the pragma EXCEPTION_INIT to associate the exception name with an Oracle error number in which case SQLCODE returns that error number and SOLERRM returns the corresponding error message The maximum length of an Oracle error message is 512 characters including the error code nested messages and message inserts such as table and column names If no exception has been raised SOLCODE returns zero and SQLERRM returns the message ORA 0000 normal successful completion You can pass an error number to SQLERRM in which case SQLERRM returns the message associated with that error number Make sure you pass negative error numbers to SQLERRM In the following example you pass positive numbers and so get unwanted results DECLARE err_msg VARCHAR2 100 BEGIN Get all Or
277. anges If you change your mind or need to correct a mistake you can use the ROLLBACK statement to roll back undo the changes Language Elements 11 27 COMMIT Statement If you commit while a cursor that was declared using FOR UPDATE is open a subsequent fetch on that cursor raises an exception The cursor remains open however so you should close it For more information see Using FOR UPDATE on page 5 51 When a distributed transaction fails the text specified by COMMENT helps you diagnose the problem If a distributed transaction is ever in doubt Oracle stores the text in the data dictionary along with the transaction ID For more information about distributed transactions see Oracle8 Concepts PL SQL does not support the FORCE clause which in SQL manually commits an in doubt distributed transaction For example the following COMMIT statement is illegal COMMIT FORCE 23 51 54 illegal With embedded SQL the optional RELEASE parameter is allowed after COMMIT WORK The keyword RELEASE acts like a disconnect statement which logs you off the database once your transaction is committed PL SQL does not support data control statements such as CONNECT GRANT or REVOKE Therefore it does not support the RELEASE parameter Related Topics ROLLBACK Statement SAVEPOINT Statement 11 28 PL SQL User s Guide and Reference Constants and Variables
278. annot declare cursor variables in a package Unlike packaged variables cursor variables do not have persistent state Remember declaring a cursor variable creates a pointer not an item So cursor variables cannot be saved in the database Cursor variables follow the usual scoping and instantiation rules Local PL SQL cursor variables are instantiated when you enter a block or subprogram and cease to exist when you exit In the RETURN clause of a REF CURSOR type definition you can use SROWTYPE to specify a record type that represents a row returned by a strongly not weakly typed cursor variable as follows DECLARE YPE TmpCurTyp IS REF CURSOR RETURN empSROWTYPE tmo_cv TmpCurTyp declare cursor variable YPE EmpCurTyp IS REF CURSOR RETURN tmp_cv ROWTYPE emp_cv EmpCurTyp declare cursor variable se e Likewise you can use STYPE to provide the datatype of a record variable as the following example shows DECLARE dept_rec deptSROWTYPE declare record variable YPE DeptCurTyp IS REF CURSOR RETURN dept_rec TYPE dept_cv DeptCurTyp declare cursor variable In the final example you specify a user defined RECORD type in the RETURN clause DECLARE YPE EmpRecTyp IS RECORD empno NUMBER 4 ename VARCHAR2 10 sal NUMBER 7 2 TYPE EmpCurTyp IS REF CURSOR RETURN EmpRecTyp emp_cv EmpC
279. applications without exposing your source code Major Topics Advantages of Wrapping Running the PL SQL Wrapper PL SQL Wrapper D 1 Advantages of Wrapping Advantages of Wrapping The PL SQL Wrapper converts PL SQL source code into an intermediate form of object code By hiding application internals the Wrapper prevents misuse of your application by other developers exposure of your algorithms to business competitors Wrapped code is as portable as source code The PL SQL compiler recognizes and loads wrapped compilation units automatically Other advantages include platform independence you need not deliver multiple versions of the same compilation unit a dynamic loading users need not shut down and relink to add a new feature dynamic binding external references are resolved at load time a strict dependency checking invalidated program units are recompiled automatically normal importing and exporting the Import Export utility accepts wrapped files Running the PL SQL Wrapper To run the PL SQL Wrapper enter the WRAP command at your system prompt using the following syntax WRAP INAME input_file ONAME output_file You can use uppercase or lowercase Leave no space around the equal signs because spaces delimit individual arguments The WRAP command requires only one argument which is INAME input_file where input_file is the path and name of the Wrapper input file You need
280. apter 8 Packages This chapter shows you how to bundle related PL SQL types items and subprograms into a package Once written your general purpose package is compiled then stored in an Oracle database where its contents can be shared by many applications Chapter 9 Object Types This chapter introduces you to object oriented programming based on object types which provide abstract templates for real world objects You learn how to define object types and manipulate objects Chapter 10 External Procedures This chapter presents a new PL SQL interface for calling routines written in other languages It shows you how dynamic link libraries DLLs already written and available in another language can be called directly from PL SQL programs Chapter 11 Language Elements This chapter uses syntax diagrams to show how commands parameters and other language elements are sequenced to form PL SQL statements Also it provides usage notes and short examples to help you become fluent in PL SQL quickly Appendix A New Features This appendix surveys the major new features in Release 8 0 of PL SQL Appendix B Sample Programs This appendix provides several PL SQL programs to guide you in writing your own The sample programs illustrate important concepts and features Appendix C CHAR versus VARCHAR2 Semantics This appendix explains the subtle but important semantic differences between the CHAR and VARCHAR2 base types Appendix D PL SQL Wrapp
281. arameter SELF and another object of the same type If 01 and o2 are objects a comparison such as o1 gt 02 automatically calls the order method with parameters o1 and o2 The method returns a negative number zero or a positive number signifying that SELF is less than equal to or greater than the other parameter respectively Language Elements 11 105 Object Types An object type can contain only one order method which must be a function that returns a numeric result member_function_specification This construct declares the interface to a member function Its syntax is like that of function_specification without the terminator See Functions on page 11 79 member_procedure_specification This construct declares the interface to a member procedure Its syntax is like that of procedure_specification without the terminator See Procedures on page 11 121 member_function_body This construct defines the underlying implementation of a member function Its syntax is like that of Funct ion_body without the terminator See Functions on page 11 79 member_procedure_body This construct defines the underlying implementation of a member procedure Its syntax is like that of procedure_body without the terminator See Procedures on page 11 121 restrict_references_pragma You use this pragma compiler directive to enforce rules that control side effects The pragma tells the PL SQL compiler to deny the membe
282. aration m DEFAULT parameter_name Keyword and Parameter Description function_name This identifies a user defined function parameter_name This identifies a formal parameter which is a variable declared in a function specification and referenced in the function body IN OUT IN OUT These parameter modes define the behavior of formal parameters An IN parameter lets you pass values to the subprogram being called An OUT parameter lets you return values to the caller of the subprogram An IN OUT parameter lets you pass initial values to the subprogram being called and return updated values to the caller datatype This is a type specifier For the syntax of datatype see Constants and Variables on page 11 29 Y DEFAULT This operator or keyword allows you to initialize IN parameters to default values 11 80 PL SQL User s Guide and Reference Functions Usage Notes expression This is an arbitrarily complex combination of variables constants literals operators and function calls The simplest expression consists of a single variable When the declaration is elaborated the value of expression is assigned to the parameter The value and the parameter must have compatible datatypes RETURN This keyword introduces the RETURN clause which specifies the datatype of the result value type_definition This specifies a user defined datatype For the syntax of type_definition see
283. arative part as its associated exception somewhere after the exception declaration Be sure to assign only one exception name to an error number 11 52 PL SQL User s Guide and Reference EXCEPTION_INIT Pragma Example The following pragma associates the exception deadlock_det ected with Oracle error 60 DECLARE deadlock_detected EXCEPTION PRAGMA EXCEPTION_INIT deadlock_detected 60 BEGIN EXCEPTION WHEN deadlock_detected THEN handle the error END Related Topics Exceptions SQLCODE Function Language Elements 11 53 Exceptions Exceptions Syntax An exception is a runtime error or warning condition which can be predefined or user defined Predefined exceptions are raised implicitly automatically by the runtime system User defined exceptions must be raised explicitly by RAISE statements To handle raised exceptions you write separate routines called exception handlers For more information see Chapter 6 exception_declaration O exception_handler OTHERS lt OR exception_name Gare Keyword and Parameter Description WHEN This keyword introduces an exception handler You can have multiple exceptions execute the same sequence of statements by following the keyword WHEN with a list of the exceptions separating them by the keyword or If any exception in the list is raised the associated statements are exe
284. arison operator 5 6 spaces where allowed 2 2 spaghetti code 3 15 sparse collection 4 3 specification cursor 5 15 function 7 5 method 9 8 object 9 5 package 8 5 procedure 7 4 SQL comparison operators 5 6 data manipulation statements 5 2 pseudocolumn 5 4 row operators 5 7 set operators 5 6 support in PL SQL 1 21 SQL cursor syntax 11 144 SQL standards conformance 5 7 SQL92 conformance 5 7 SQLCODE function 6 18 syntax 11 146 SQLERRM function 6 18 syntax 11 147 stack 9 14 standalone subprogram 1 19 START WITH clause 5 5 statement assignment 11 3 CLOSE 5 13 5 27 11 14 COMMIT 11 27 CREATE LIBRARY 10 3 DELETE 11 49 EXIT 11 57 FETCH 5 12 5 26 11 76 GOTO 11 83 IF 11 85 INSERT 11 88 LOCK TABLE 11 94 LOOP 11 96 NULL 11 102 OPEN 5 11 11 111 OPEN FOR 5 22 11 113 RAISE 11 126 RETURN 11 132 ROLLBACK 11 134 SAVEPOINT 11 138 SELECT INTO 11 139 SET TRANSACTION 11 142 UPDATE 11 151 statement terminator 11 12 statement level rollback 5 47 STDDEV group function 5 3 Index 13 STEP clause mimicking 3 12 stepwise refinement 1 2 STORAGE_ERROR exception 6 6 when raised 7 24 store table 4 5 stored subprogram 1 19 7 10 string comparison semantics C 2 string literal 2 8 STRING subtype 2 17 structure theorem 3 2 stub 3 19 7 3 subprogram 7 2 advantages 7 3 declaring 7 8 how calls are resolved 7 21 local 1 19 overloading 7 18 packaged 1 19 7 9 parts 7
285. arriage returns and indent lines using spaces or tabs Compare these IF statements for readability IF x gt y THEN max x ELSE max y END IF IF x gt y THEN max x ELSE max y END IF A delimiter is a simple or compound symbol that has a special meaning to PL SQL For example you use delimiters to represent arithmetic operations such as addition and subtraction Simple Symbols Simple symbols consist of one character a list follows addition operator attribute indicator character string delimiter component selector division operator expression or list delimiter expression or list delimiter host variable indicator item separator multiplication operator quoted identifier delimiter relational operator relational operator relational operator remote access indicator statement terminator subtraction negation operator oe Fundamentals 2 3 Lexical Units Compound Symbols Compound symbols consist of one character a list follows exponentiation operator lt gt relational operator relational operator relational operator lt relational operator gt relational operator assignment operator gt association operator range operator concatenation operator lt lt beginning label delimiter gt gt ending label delimiter single line comment indicator beginning multi line comment delimit
286. as follows dept_rec dname PURCHASING Instead of assigning values separately to each field in a record you can assign values to all fields at once This can be done in two ways First you can assign one user defined record to another if they have the same datatype Having fields that match exactly is not enough You can assign a ROWTYPE record to a user defined record if their fields match in number and order and corresponding fields have compatible datatypes Language Elements 11 129 Records Second you can use the SELECT or FETCH statement to fetch column values into a record The columns in the select list must appear in the same order as the fields in your record You can declare and reference nested records That is a record can be the component of another record as the following example shows DECLARE YPE TimeTyp IS RECORD minute SMALLINT hour SMALLINT YPE MeetingTyp IS RECORD day DATE time TimeTyp nested record place CHAR 20 purpose CHAR 50 TYPE PartyTyp IS RECORD day DATE time TimeTyp nested record loc CHAR 15 meeting MeetingTyp seminar MeetingTyp party PartyTyp The next example shows that you can assign one nested record to another if they have the same datatype seminar time meeting time Such assignments are allowed even if the containing records have different datatype
287. as the following example shows DECLARE YPE Clientele IS VARRAY 100 OF Customer vips Clientele Clientele initialize empty varray BEGIN IF vips IS NOT NULL THEN condition yields TRUE Except for index by tables PL SQL never calls a constructor implicitly so you must call it explicitly Constructor calls are allowed wherever function calls are allowed That includes the SELECT VALUES and SET clauses In the example below you insert a Student object into object table sophomores The table constructor CourseList provides a value for attribute courses BEGIN INSERT INTO sophomores VALUES Student 5035 Janet Alvarez 122 Brighton St FT CourseList Econ 2010 Acct 3401 Mgmt 3100 In the final example you insert a row into database table department The varray constructor ProjectList provides a value for column projects BEGIN INSERT INTO department VALUES 60 Security 750400 ProjectList Project 1 Issue New Employee Badges 13500 Project 2 Find Missing Computer Chips 2750 Project 3 Inspect Emergency Exits 1900 4 10 PL SQL User s Guide and Reference Initializing and Referencing Collections Referencing Collection Elements Every element reference includes a collection name and a subscript enclosed in parentheses The subscript determines which element is processed To refere
288. ase tables For example the following UPDATE statement fails because PL SQL assumes that emp refers to the loop counter FOR emp IN 1 5 LOOP UPDATE emp SET bonus 500 WHERE END LOOP Fundamentals 2 35 Naming Conventions Likewise the following SELECT statement fails because PL SQL assumes that emp refers to the formal parameter PROCEDURE calc_bonus emp NUMBER bonus OUT REAL IS avg_sal REAL BEGI SELECT AVG sal INTO avg_sal FROM emp WHERE In such cases you can prefix the table name with a username as follows but a better programming practice is to rename the variable or formal parameter PROCEDURE calc_bonus emp NUMBER bonus OUT REAL IS avg_sal REAL BEGI SELECT AVG sal INTO avg_sal FROM scott emp WHERE Unlike the names of tables the names of columns take precedence over the names of local variables and formal parameters For example the following DELETE statement removes all employees from the emp table not just KING because Oracle assumes that both enames in the WHERE clause refer to the database column DECLARE ename VARCHAR2 10 KING BEGIN DELETE FROM emp WHERE ename ename In such cases to avoid ambiguity prefix the names of local variables and formal parameters with my_ as follows
289. astest way to access particular rows Normally a rowid uniquely identifies a row However rows in different tables stored in the same cluster can have the same rowid To manipulate rowids you use the supplied package DBMS_ROWID which is described in Oracle8 Application Developer s Guide VARCHAR2 You use the VARCHAR2 datatype to store variable length character data How the data is represented internally depends on the database character set which might be 7 bit ASCII or EBCDIC Code Page 500 for example The VARCHAR2 datatype takes a required parameter that specifies a maximum length up to 32767 bytes The syntax follows VARCHAR2 maximum_length 2 16 PL SQL User s Guide and Reference Datatypes You cannot use a constant or variable to specify the maximum length you must use an integer literal in the range 1 32767 Remember you specify the maximum length of a VARCHAR2 n variable in bytes not characters So if a VARCHAR2 n variable stores multi byte characters its maximum length is less than n characters The maximum width of a VARCHAR2 database column is 4000 bytes Therefore you cannot insert VARCHAR2 values longer than 4000 bytes into a VARCHAR2 column You can insert any VARCHAR2 n value into a LONG database column because the maximum width of a LONG column is 2147483647 bytes However you cannot retrieve a value longer than 32767 bytes from a LONG column into a VARCHAR2 n variable Semantic differ
290. atabase column is 4000 bytes Therefore you cannot insert NVARCHAR2 values longer than 4000 bytes into a NVARCHAR2 column Remember for fixed width multi byte character sets you cannot insert NVARCHAR2 values longer than the number of characters that fit in 4000 bytes You cannot insert VARCHAR2 values into an NVARCHAR2 column Likewise you cannot insert NVARCHAR2 values into a VARCHAR2 column The LOB large object datatypes BF ILE BLOB CLOB and NCLOB let you store blocks of unstructured data such as text graphic images video clips and sound waveforms up to four gigabytes in size And they allow efficient random piece wise access to the data The LOB types differ from the LONG and LONG RAW types in several ways For example LOBs except NCLOB can be attributes of an object type but LONGs cannot The maximum size of a LOB is four gigabytes but the maximum size of a LONG is two gigabytes Also LOBs support random access to data but LONGs support only sequential access LOB types store values called locators that specify the location of large objects stored in an external file in line inside the row or out of line outside the row Fundamentals 2 19 Datatypes Database columns of type BLOB CLOB NCLOB or BF ILE store the locators BLOB CLOB and NCLOB data is stored in the database in or outside the row BFILE data is stored in operating system files outside the database PL SQL operates on LO
291. ater marked since the last commit or rollback The optional keyword WORK has no effect other than to improve readability The keyword END signals the end of a PL SQL block not the end of a transaction Just as a block can span multiple transactions a transaction can span multiple blocks The COMMENT clause lets you specify a Comment to be associated with a distributed transaction When you issue a commit changes to each database affected by a distributed transaction are made permanent However if a network or machine fails during the commit the state of the distributed transaction might be unknown or in doubt In that case Oracle stores the text specified by COMMENT in the data dictionary along with the transaction ID The text must be a quoted literal up to 50 characters long An example follows COMMIT COMMENT In doubt order transaction notify Order Entry PL SQL does not support the FORCE clause which in SQL manually commits an in doubt distributed transaction For example the following COMMIT statement is illegal COMMIT FORCE 23 51 54 illegal 5 46 PL SQL User s Guide and Reference Processing Transactions Using ROLLBACK The ROLLBACK statement ends the current transaction and undoes any changes made during that transaction Rolling back is useful for two reasons First if you make a mistake like deleting the wrong row from a table a rollback restores the original data
292. atically sr_pkg print_pkg_state prints 0 END For more information see Oracle8 Application Developer s Guide Use External Procedures External procedures see Chapter 10 extend the functionality of the Oracle server by providing an interface for calling routines written in other languages Standard libraries already written and available in other languages can be called from PL SQL programs This promotes reusability efficiency and modularity To speed up execution you can rewrite computation bound programs in C for example Also you can move such programs from client to server where they will execute faster thanks to more computing power and less across network communication For example you can write methods for an image object type in C store them in a dynamic link library DLL register the library with PL SQL then call it from your applications At run time the library loads dynamically and for safety runs in a separate address space implemented as a separate process Use the DBMS_SQL Array Interface The PL SQL package DBMS_SOL supports an array interface that gives you OCI like array bind functionality You can fetch multiple rows from a database table into a PL SQL index by table in one call to the server Conversely you can insert all rows from an index by table into a database table in one call This reduces server CPU use significantly because fewer calls are made to the SQL engine For client
293. ation collection 4 9 object 9 24 package 8 8 record 4 31 using DEFAULT 2 29 variable 2 40 when required 2 30 INSERT statement RETURNING clause 5 55 syntax 11 88 instance 9 4 INT subtype 2 13 INTEGER subtype 2 13 interoperability cursor 5 19 INTERSECT set operator 5 6 INTO clause 5 26 INTO list 5 12 INVALID_CURSOR exception 6 5 INVALID_NUMBER exception 6 5 IS DANGLING predicate 9 34 IS NULL comparison operator 2 45 5 6 ISOPEN cursor attribute 5 38 5 42 iteration scheme 3 10 versus recursion 7 27 iterative control 3 6 J join 7 26 L label block 2 39 GOTO statement 3 15 loop 3 8 LANGUAGE clause 10 4 large object LOB datatypes 2 19 LAST collection method 4 23 LENGTH property 10 14 LEVEL pseudocolumn 5 5 lexical unit 2 2 library 8 1 LIBRARY clause 10 4 library alias 10 3 Index 7 LIKE comparison operator 2 45 5 6 LIMIT collection method 4 22 literal 2 7 Boolean 2 8 character 2 7 numeric 2 7 string 2 8 syntax 11 91 LOB large object datatypes 2 19 local subprogram 1 19 locator 2 19 lock 5 45 modes 5 45 overriding 5 51 using FOR UPDATE clause 5 51 LOCK TABLE statement 5 52 syntax 11 94 LOGIN_DENIED exception 6 5 LONG datatype 2 15 maximum length 2 15 restrictions 2 15 LONG RAW datatype 2 15 converting 2 28 maximum length 2 15 loop counter 3 10 kinds 3 6 label 3 8 LOOP statement 3 6 forms 3 6 sy
294. atype 2 16 ROWID pseudocolumn 5 5 ROWIDTOCHAR function 5 5 ROWNUM pseudocolumn 5 5 ROWTYPE attribute 2 31 syntax 11 136 ROWTYPE_MISMATCH exception 6 6 RPC remote procedure call 6 12 RTRIM function using to insert data C 4 runtime error 6 1 S sample database table DEPT table xx EMP table xx sample programs B 1 savepoint name reusing 5 48 SAVEPOINT statement 5 48 syntax 11 138 scalar type 2 10 scale specifying 2 13 scheme iteration 3 10 scientific notation 2 7 scope 2 37 collection 4 9 cursor 5 10 cursor parameter 5 10 definition 2 37 exception 6 7 identifier 2 37 loop counter 3 13 package 8 5 SELECT INTO statement syntax 11 139 selector 5 24 SELF parameter 9 8 semantics assignment C 2 blank padding C 3 CHAR versus VARCHAR2 C 1 non blank padding C 3 string comparison C 2 Send Us Your Comments boilerplate xiii separator 2 3 sequence 5 4 sequential control 3 15 serially reusable package 5 55 SERIALLY_REUSABLE pragma 5 55 server integration with PL SQL 1 23 service routine 10 17 examples 10 17 session 5 44 session specific variables 8 11 set operator 5 6 SET TRANSACTION statement 5 50 syntax 11 142 short circuit evaluation 2 44 side effects 7 13 9 12 significant characters 2 5 SIGNTYPE subtype 2 12 simple symbol 2 3 single line comment 2 9 size constraint subtype 2 23 size limit varray 4 5 SMALLINT subtype 2 13 snapshot 5 45 SOME comp
295. atype Client by qualifying the reference with block label block1 In the CREATE TYPE person1 statement below the compiler resolves the second reference to manager as the name of the attribute you are trying to declare In the CREATE TYPE person2 statement the compiler resolves the second reference to manager as the name of the attribute you just declared In both cases the reference to manager generates an error because the compiler expects a type name CREATE TYPE manager AS OBJECT dept NUMBER CREATE TYPE personl AS OBJECT manager manager CREATE TYPE person2 AS OBJECT manager NUMBER mgr manager E 2 PL SQL User s Guide and Reference Various Forms of References Various Forms of References During name resolution the compiler can encounter various forms of references including simple unqualified names dot separated chains of identifiers indexed components of a collection and so on Some examples of legal references follow CREATE PACKAGE packl AS m BER YPE t1 IS RECORD a NUMBER vl tl YPE t2 IS TABLE OF t1 INDEX BY BINARY_INTEGER v2 t2 FUNCTION f1 pl BER RETURN t1 FUNCTION f2 ql BER RETURN t2 END CREATE PACKAGE BODY packl1 AS FUNCTION f1 pl BER RETU
296. available to every PL SQL client For example you can declare a cursor variable in a PL SQL host environment such as an OCI or Pro C program then pass it as input host variable bind variable to PL SQL Moreover application development tools such as Oracle Forms and Oracle Reports which have a PL SQL engine can use cursor variables entirely on the client side The Oracle server also has a PL SQL engine So you can pass cursor variables back and forth between an application and server via remote procedure calls RPCs What Are Cursor Variables Cursor variables are like C or Pascal pointers which hold the memory location address of some item instead of the item itself So declaring a cursor variable creates a pointer not an item In PL SQL a pointer has datatype REF X where REF is short for REFERENCE and X stands for a class of objects Therefore a cursor variable has datatype REF CURSOR To execute a multi row query Oracle opens an unnamed work area that stores processing information To access the information you can use an explicit cursor which names the work area Or you can use a cursor variable which points to the work area Whereas a cursor always refers to the same query work area a cursor variable can refer to different work areas So cursors and cursor variables are not interoperable that is you cannot use one where the other is expected Why Use Cursor Variables Mainly you use c
297. ave the same datatype When declaring a cursor variable as the formal parameter of a subprogram that fetches from or closes the cursor variable you must specify the IN or IN OUT mode If the subprogram opens the cursor variable you must specify the IN OUT mode Be careful when passing cursor variables as parameters At run time PL SQL raises ROWTYPE_MISMATCH if the return types of the actual and formal parameters are incompatible You can apply the cursor attributes S FOUND SNOTFOUND S ISOPEN and SROWCOUNT to a cursor variable For more information see Using Cursor Attributes on page 5 38 If you try to fetch from close or apply cursor attributes to a cursor variable that does not point to a query work area PL SQL raises the predefined exception INVALID_CURSOR You can make a cursor variable or parameter point to a query work area in two ways OPEN the cursor variable FOR the query a Assign to the cursor variable the value of an already OPENed host cursor variable or PL SQL cursor variable A query work area remains accessible as long as any cursor variable points to it Therefore you can pass the value of a cursor variable freely from one scope to another For example if you pass a host cursor variable to a PL SQL block embedded in a Pro C program the work area to which the cursor variable points remains accessible after the block completes Currently cursor variables are subject to the following rest
298. ble into a SROWTYPE record DECLARE emp_rec empSROWIYPE e BEGI SELECT INTO emp_rec FROM emp WHERE empno my_empno IF emp_rec deptno 20 AND emp_rec sal gt 2000 THEN END 1F Constants and Variables Cursors Cursor Variables FETCH Statement Language Elements 11 137 SAVEPOINT Statement SAVEPOINT Statement Syntax The SAVEPOINT statement names and marks the current point in the processing of a transaction With the ROLLBACK TO statement savepoints let you undo parts of a transaction instead of the whole transaction For more information see Processing Transactions on page 5 44 savepoint_statement SEO e Keyword and Parameter Description Usage Notes Related Topics savepoint_name This is an undeclared identifier which marks the current point in the processing of a transaction When you roll back to a savepoint any savepoints marked after that savepoint are erased However the savepoint to which you roll back is not erased A simple rollback or commit erases all savepoints Savepoint names can be reused within a transaction This moves the savepoint from its old position to the current point in the transaction If you mark a savepoint within a recursive subprogram new instances of the SAVEPOINT statement are executed at each level in the recursive descent However you can only roll back to the most recently marked savepoint
299. bprogram The result is indeterminate because it depends on the method of parameter passing chosen by the compiler In the example below procedure add_entry refers to varray lexicon in two different ways as a parameter and as a global variable So when add_ent ry is called the identifiers word_list and lexicon name the same varray DECLARE YPE Definition IS RECORD word VARCHAR2 20 meaning VARCHAR2 200 YPE Dictionary IS VARRAY 2000 OF Definition lexicon Dictionary Dictionary PROCEDURE add_entry word_list IN OUT Dictionary IS BEGI At this point 1f the varray was passed by reference it has two names Hence the term aliasing word_list 1 word aardvark lexicon 1 word aardwolf END Subprograms 7 17 Overloading Overloading BEGIN lexicon EXTEND add_entry lexicon DBMS_OUTPUT PUT_LINE lexicon 1 word prints aardvark if parameter was passed by value prints aardwolf if parameter was passed by reference END The result depends on the method of parameter passing chosen by the compiler If the compiler chooses the by value method word_list and lexicon are separate copies of the same varray So changing one does not affect the other But if the compiler chooses the by reference method word_list and lexicon are just different names for the same varray So changing the
300. but the compiler cannot find a basis for it in that scope the compiler tries to find the basis by searching all PL SQL scopes local to the compilation unit starting with the current scope and moving outward If the name is found the length of the basis is 1 If the name is not found the compiler tries to find the basis by searching for schema objects using the following rules a First the compiler tries to find a basis of length 1 by searching the current schema for a schema object whose name matches the first identifier in the chain of identifiers The schema object found might be a package specification function procedure table view sequence synonym or schema level datatype If it is a synonym the basis will be resolved as the base object designated by the synonym a Ifthe previous search fails the compiler tries to find a basis of length 1 by searching for a public synonym whose name matches the first identifier in the chain If this succeeds the basis will be resolved as the base object designated by the synonym a Ifthe previous search fails and there are at least two identifiers in the chain the compiler tries to find a basis of length 2 by searching for a schema object whose name matches the second identifier in the chain and which is owned by a schema whose name matches the first identifier in the chain a Ifthe compiler finds a basis as a schema object it checks the privileges on the base object If the base object is not
301. bytes into an NCHAR column Remember for fixed width multi byte character sets you cannot insert NCHAR values longer than the number of characters that fit in 2000 bytes If the NCHAR value is shorter than the defined width of the NCHAR column Oracle blank pads the value to the defined width You cannot insert CHAR values into an NCHAR column Likewise you cannot insert NCHAR values into a CHAR column 2 18 PL SQL User s Guide and Reference Datatypes LOB Types NVARCHAR2 You use the NVARCHAR2 datatype to store variable length NLS character data How the data is represented internally depends on the national character set which might use a fixed width encoding such as WE8EBCDIC37C or a variable width encoding such as JA16DBCS The NVARCHAR2 datatype takes a required parameter that specifies a maximum length up to 32767 bytes The syntax follows NVARCHAR2 maximum_length You cannot use a constant or variable to specify the maximum length you must use an integer literal in the range 1 32767 How you specify the maximum length depends on the national character set For fixed width character sets you specify the maximum length in characters For variable width character sets you specify it in bytes In the following example the character set is JA16SJIS which is variable width so you specify the maximum length in bytes my_string NVARCHAR2 200 maximum length is 200 bytes The maximum width of a NVARCHAR2 d
302. call the following procedure remotely because it references a packaged variable in a parameter initialization clause CREATE PACKAGE random AS seed BER PROCEDURE initialize starter IN BER seed Also you cannot reference variables declared in a host environment bind variables inside a package The Package Body The package body implements the package specification That is the package body contains the definition of every cursor and subprogram declared in the package specification Keep in mind that subprograms defined in a package body are accessible outside the package only if their specifications also appear in the package specification To match subprogram specifications and bodies PL SQL does a token by token comparison of their headers So except for white space the headers must match word for word Otherwise PL SQL raises an exception as the following example shows CREATE PACKAGE emp_actions AS PROCEDURE calc bonus date_hired emp hiredatesTYPE END emp_actions x se CREATE PACKAGE BODY emp_actions AS PROCEDURE calc_bunus date _hired DATE IS parameter declaration raises an exception because DATE does not match emp hiredatesTYPE word for word Packages 8 7 Some Examples BEGIN END calc_bonus END emp_actions The pac
303. can be used with confidence in any number of applications Furthermore only the subprogram is affected if its definition changes This simplifies maintenance and enhancement Finally subprograms aid abstraction the mental separation from particulars To use subprograms you must know what they do not how they work Therefore you can design applications from the top down without worrying about implementation details Dummy subprograms stubs allow you to defer the definition of procedures and functions until you test and debug the main program A procedure is a subprogram that performs a specific action You write procedures using the syntax PROCEDURE name parameter parameter IS local declarations BEGI xecutable statements EXCEPTION exception handlers END name where parameter stands for the following syntax parameter_name IN OUT IN OUT datatype DEFAULT expression You cannot impose the NOT NULL constraint on a parameter Subprograms 7 3 Procedures Also you cannot specify a constraint on the datatype For example the following declaration of emp_idis illegal because it imposes a size constraint PROCEDURE raise_salary emp_id BER 4 IS illegal should be NU Y e A procedure has two parts the specification and the body The procedure specification begins with the keyword PROCEDURE and ends with the p
304. cation and exponentiation operators respectively character_constant_name This identifies a previously declared constant that stores a character value It must be initialized to a character value or a value implicitly convertible to a character value character_function_call This is a function call that returns a character value or a value implicitly convertible to a character value character_literal This is a literal that represents a character value or a value implicitly convertible to a character value character_variable_name This identifies a previously declared variable that stores a character value 11 66 PL SQL User s Guide and Reference Expressions Usage Notes This is the concatenation operator As the following example shows the result of concatenating string with string2 is a character string that contains string1 followed by string2 Good morning Good morning The next example shows that nulls have no effect on the result of a concatenation suit NULL case suitcase A string zero characters in length is called a null string and is treated like a null date_constant_name This identifies a previously declared constant that stores a date value It must be initialized to a date value or a value implicitly convertible to a date value date_function_call This is a function call that returns a date value or a value implicitly convertibl
305. ch are represented internally as 22 byte Oracle numbers Also PLS_INTEGER operations use machine arithmetic so they are faster than BINARY_INTEGER INTEGER or NUMBER operations which use library arithmetic Furthermore INTEGER NATURAL NATURALN POSITIVE POSITIVEN and SIGNTYPE are constrained subtypes So their variables require precision checking at run time which can affect performance Avoid the NOT NULL Constraint In PL SQL using the NOT NULL constraint incurs a performance cost Consider the following example PROCEDURE calc_m IS m BER NOT NULL a BER b BER BEGIN m a b 5 58 PL SQL User s Guide and Reference Processing Transactions Because m is constrained by NOT NULL the result of expression a bis assigned to a temporary variable which is then tested for nullity If the variable is not null its value is assigned to m Otherwise an exception is raised However if m were not constrained the expression result would be assigned to m directly A more efficient way to write the last example follows PROCEDURE calc m IS m BER no constraint a BER b BER BEGIN m at b IF m IS NULL THEN enforce constraint programmatically Note that the subtypes NATURALN and POSTIVEN are defined as NOT NULL So using them incurs the same performance cost Avoid Im
306. cifier must be followed by an initialization clause Otherwise you get a compilation error For example the following declaration is illegal line_items POSITIVEN illegal not initialized Using TYPE The 3TY PE attribute provides the datatype of a variable or database column In the following example TYPE provides the datatype of a variable credit RI debit credit STYPE EAL 7 2 Variables declared using STYPE are treated like those declared using a datatype specifier For example given the previous declarations PL SQL treats debit likea REAL 7 2 variable The next example shows that a TYPE declaration can include an initialization clause balance NUMBER 7 2 minimum_balance balanceSTYPE 10 00 2 30 PL SQL User s Guide and Reference Declarations The TYPE attribute is particularly useful when declaring variables that refer to database columns You can reference a table and column or you can reference an owner table and column as in my_dname scott dept dnameSTYPE Using STYPE to declare my_dname has two advantages First you need not know the exact datatype of dname Second if the database definition of dname changes the datatype of my_dname changes accordingly at run time Note however that a NOT NULL column constraint does not apply to variables declared using sTYPE In the next example even though the da
307. cks in a Pro C program ECLARE SECTION EXEC SQL BEGIN D int my_empn o float my_sal my_comm short comm_in EC SQL END DEC d LARE SECTION EC SQL EXECUTE BEGI SELECT sal comm INTO my_sal my_comm comm_ind FROM emp WHERE empno my_empno IF my_comm comm_ind IS NULL THEN END IF END END EXEC EC SQL EXECUTE BEGIN IF my_comm comm_ind gt 1000 THEN my_sal my_sal 1 10 UPDATE END IF END END E EC emp S Ensuring Backward Compatibility PL SQL Version 2 allows some abnormal behavior that Version 8 disallows Specifically Version 2 allows you to ET sal my_sal WHERE empno my_empno make forward references to RECORD and TABLE types when declaring variables specify the name of a variable not a datatype in the RETURN clause of a function specification assign values to the elements of an index by table IN parameter pass the fields of a record IN parameter to another subprogram as OUT parameters Interaction with Oracle 5 61 Processing Transactions a use the fields of a record OUT parameter on the right hand side of an assignment statement use OUT parameters in the FROM list of a SELECT statement For backward compatibility you might want to keep thi
308. clared in a PL SQL host environment and passed to PL SQL as a bind variable Host cursor variables must be prefixed with a colon SQL This identifies a cursor opened implicitly by Oracle to process a SQL data manipulation statement The implicit SOL cursor always refers to the most recently executed SQL statement 11 64 PL SQL User s Guide and Reference Expressions FOUND ISOPEN NOTFOUND ROWCOUNT These are cursor attributes When appended to the name of a cursor or cursor variable these attributes return useful information about the execution of a multi row query You can also append them to the implicit SOL cursor For more information see Using Cursor Attributes on page 5 38 EXISTS COUNT FIRST LAST LIMIT NEXT PRIOR These are collection methods When appended to the name of a collection these methods return useful information For example EXISTS n returns TRUE if the nth element of a collection exists Otherwise EXISTS n returns FALSE For more information see Collection Methods on page 11 16 index This is a numeric expression that must yield a value of type BINARY_INTEGER ora value implicitly convertible to that datatype host_variable_name This identifies a variable declared in a PL SQL host environment and passed to PL SQL as a bind variable The datatype of the host variable must be implicitly convertible to the appropriate PL SQL datatype Also host variab
309. claring Subprograms A forward declaration consists of a subprogram specification terminated by a semicolon In the following example the forward declaration advises PL SQL that the body of procedure calc_rating can be found later in the block DECLARE PROCEDURE calc_rating forward declaration Define subprograms in alphabetical order PROCEDURE award_bonus IS BEGI calc_rating END PROCEDURE calc_rating IS BEGI END Although the formal parameter list appears in the forward declaration it must also appear in the subprogram body You can place the subprogram body anywhere after the forward declaration but they must appear in the same program unit In Packages Forward declarations also let you group logically related subprograms in a package The subprogram specifications go in the package specification and the subprogram bodies go in the package body where they are invisible to applications Thus packages allow you to hide implementation details An example follows CREATE PACKAGE emp actions AS package specification PROCEDURE hire_employee emp_id INTGER name VARCHAR2 PROCEDURE fire employee emp_id INTEGER PROCEDURE raise _salary emp id INTEGER increase REAL END emp_actions CREATE PACKAGE BODY emp_ actions AS
310. closing block resumes with the next statement If there is no enclosing block control returns to the host environment In the example below you calculate and store a price to earnings ratio for a company with ticker symbol XYZ If the company has zero earnings the predefined exception ZERO_DIVIDE is raised This stops normal execution of the block and transfers control to the exception handlers The optional OTHERS handler catches all exceptions that the block does not name specifically DECLARE pe_ratio NUMBER 3 1 BEGI SELECT price earnings INTO pe_ratio FROM stocks WHERE symbol XYZ might cause division by zero error INSERT INTO stats symbol ratio VALUES XYZ pe ratio COMMIT EXCEPTION exception handlers begin WHEN ZERO DIVIDE THEN handles division by zero error INSERT INTO stats symbol ratio VALUES XYZ NULL COMMIT WHEN OTHERS THEN handles all other errors ROLLBACK END exception handlers and block end here 6 2 PL SQL User s Guide and Reference Advantages of Exceptions The last example illustrates exception handling not the effective use of INSERT statements For example a better way to do the insert follows INSERT INTO stats symbol ratio SELECT symbol DECODE earnings 0 NULL price earnings FROM stocks WHERE
311. compatible queries in a stored procedure When called the following packaged procedure opens the cursor variable emp_cv for the chosen query CREATE PACKAGE emp_data AS YPE GenericCurTyp 1S REF CURSOR YPE EmpCurTyp IS REF CURSOR RETURN empSROWTYP PROCEDURE open_emp_cv emp_cv IN OUT EmpCurTyp choice IN BER 5 El ND emp_data CREATE PACKAGE BODY emp_data AS PROCEDURE open_emp_cv emp_cv IN OUT EmpCurTyp choice IN NUMBER IS BEGIN IF choice 1 THEN OPEN emp_cv FOR SELECT FROM emp WHERE comm IS NOT NULL SIF choice 2 THE OPEN emp_cv FOR SELECT FROM emp WHERE sal gt 2500 ELSIF choice 3 THE OPEN emp_cv FOR SELECT FROM emp WHERE deptno 20 ND IF END open_emp_cv END emp_data 1 E Language Elements 11 115 OPEN FOR Statement For more flexibility you can pass a cursor variable to a stored procedure that executes queries with different return types as follows CREATE PACKAGE BODY emp_data AS PROCEDURE open_cv generic_cv IN OUT GenericCurTyp choice IN BER IS BEGI IF choice 1 THEN OPEN generic_cv FOR SELECT FROM emp ELSIF choice 2 THEN OPEN generic_cv FOR SELECT FROM dept ELSIF choice 3 THEN OPEN generic_cv FOR SELECT
312. corresponding attributes are equal Object Types 9 11 Components of an Object Type When sorting or merging a large number of objects use a map method One call maps all the objects into scalars then sorts the scalars An order method is less efficient because it must be called repeatedly it can compare only two objects at a time You must use a map method for hash joins because PL SQL hashes on the object value Constructor Methods Every object type has a constructor method constructor for short which is a system defined function with the same name as the object type You use the constructor to initialize and return an instance of that object type Oracle generates a default constructor for every object type The formal parameters of the constructor match the attributes of the object type That is the parameters and attributes are declared in the same order and have the same names and datatypes PL SQL never calls a constructor implicitly so you must call it explicitly Constructor calls are allowed wherever function calls are allowed For more information see Calling Constructors and Methods on page 9 26 Pragma RESTRICT_REFERENCES To execute a SOL statement that calls a member function Oracle must know the purity level of the function that is the extent to which the function is free of side effects In this context side effects are references to database tables or packaged variables Side effects can pre
313. csesssneseseseesesescscecesesssesnansneseseseeseseseecenesesssnaanenees 4 2 Understanding Varray Sisi ainia dianas 4 4 Varrays versus Nested TableS ooicoconconoonnnnnmmmrrmmrrnnncererarnnnnnnrn SKa N EEKE NEEE ERa 4 4 Defining and Declaring Collections 0 0 cccc cece cece ceeseseecececsesnseececscesensnesecesssensneseseeenes 4 5 Declaring Collect Ons siskon td A A A a ces 4 7 Initializing and Referencing CollectioNS oonincicinnnninnninnnnonncncrrrmccnrrnrnrncrraro ro rorncrornrornnns 4 9 Referencing Collection Elements inune a e ENEE 4 11 Assigning and Comparing CollectiONS ooncinnicinnnnnnnonnncnoncnnnncncnnncnroracnrorocnnanorn coro conorarnrncnoos 4 12 Comparing Whole Collections ccccccscsesesseseescececesesesnsnsnssesesneesesescecesescsesnansnesesesneneneseeeeees 4 13 Manipulating Collections 0 0 ccc ccc ccc eseescscscsesesescecscssseseececscsssnseececscsssnseeceescensnsneseeeces 4 14 Some Nested Table Examples ei disisit ietie eiet inet aE NR na RENAE ERE KEARE Re 4 14 Some Varray Examples aoni e eE eE aS casas coda A EAEE EE S 4 16 Manipulating Individual Elements c cccccecccecesescsseneneseseseeneeseececesescscsnasnesesesneneneseeeeees 4 18 Using Collection Methods 0 cccccccccc cece cs cesesescscscseseseececscsssesescscscsssnseececscsssnsnesececessnsneseeees 4 21 Using EXISTS peroo ee ati acota li id asii tesis 4 22 Using COUNT tirado eli Ltd e sal cs 4 22 LS O 4 22 Using FIRSTand LAS
314. ctor for object type Rational to initialize the object The call assigns the values 6 and 8 to attributes numand den respectively DECLARE r Rational BEGIN r Rational 6 8 DBMS_OUTPUT PUT_LINE r num prints 6 Object Types 9 23 Declaring and Initializing Objects You can declare objects as the formal parameters of functions and procedures That way you can pass objects to stored subprograms and from one subprogram to another In the next example you use object type Account to specify the datatype of a formal parameter DECLARE PROCEDURE open_acct new_acct IN OUT Account IS In the following example you use object type Account to specify the return type of a function DECLARE FUNCTION get_acct acct_id IN INTEGER RETURN Account IS Initializing Objects Until you initialize an object by calling the constructor for its object type the object is atomically null That is the object itself is null not just its attributes Consider the following example DECLARE r Rational r becomes atomically null BEGIN r Rational 2 3 r becomes 2 3 A null object is never equal to another object In fact comparing a null object with any other object always yields NULL Also if you assign an atomically null object to another object the other object becomes atomically null and must be reinitialized Likewise if
315. cts WHERE acct_no acct_id new_balance old balance amount IF new_balance lt 0 THEN RAISE overdrawn ELSE UPDATE accts SET bal new_balance WHERE acct_no acct_id END IF EXCEPTION WHEN overdrawn THEN END debit_account When invoked or called this procedure accepts an account number and a debit amount It uses the account number to select the account balance from the accts database table Then it uses the debit amount to compute a new balance If the new balance is less than zero an exception is raised otherwise the bank account is updated 7 2 PL SQL User s Guide and Reference Procedures Advantages of Subprograms Procedures Subprograms provide extensibility that is they let you tailor the PL SQL language to suit your needs For example if you need a procedure that creates new departments you can easily write one as follows PROCEDURE create_dept new_dname CHAR new_loc CHAR IS BEGI INSERT INTO dept VALUES deptno_seq NEXTVAL new_dname new_loc END create_dept Subprograms also provide modularity that is they let you break a program down into manageable well defined logic modules This supports top down design and the stepwise refinement approach to problem solving Also subprograms promote reusability and maintainability Once validated a subprogram
316. cutable part function 7 6 PL SQL block 1 3 procedure 7 4 execution environment 1 18 EXISTS collection method 4 22 EXISTS comparison operator 5 6 EXIT statement 3 6 3 14 syntax 11 57 WHEN clause 3 7 where allowed 3 6 explicit cursor 5 9 expression Boolean 2 46 how evaluated 2 41 parentheses in 2 42 syntax 11 59 EXTEND collection method 4 24 extensibility 7 3 Index 5 EXTERNAL clause 10 3 components 10 4 syntax 11 70 external procedure 10 2 calling 10 5 DEBUG_EXTPROC package 10 24 debugging 10 24 demo program 10 24 environment variables 10 8 guidelines 10 25 how PL SOL calls 10 7 maximum number of parameters 10 26 passing parameters to 10 9 registering 10 3 restrictions 10 25 specifying datatypes 10 9 specifying properties 10 12 extproc process 10 7 F FALSE value 2 8 features new A 1 FETCH statement 5 12 5 26 syntax 11 76 fetching across commits 5 53 Fibonacci sequence 7 23 field 4 28 field type 4 29 fileI O 8 17 FIRST collection method 4 23 flag PLSQL_V2_COMPATIBILITY 5 62 FLOAT subtype 2 13 FOR loop 3 10 dynamic range 3 12 iteration scheme 3 10 loop counter 3 10 nested 3 14 FOR loop cursor 5 16 FOR UPDATE clause 5 11 restriction on 5 22 when to use 5 51 formal parameter 5 11 Index 6 format function 7 5 package 8 2 packaged procedure 7 9 procedure 7 3 format mask when needed 2 27 forward declaration 7 8 when needed 7 8 7 26
317. cuted exception_name This identifies a predefined exception such as ZERO_DIVIDE or a user defined exception previously declared within the current scope OTHERS This keyword stands for all the exceptions not explicitly named in the exception handling part of the block The use of OTHERS is optional and is allowed only as the last exception handler You cannot include OTHERS in a list of exceptions following the keyword WHEN 11 54 PL SQL User s Guide and Reference Exceptions Usage Notes statement This is an executable statement For the syntax of statement see Blocks on page 11 7 An exception declaration can appear only in the declarative part of a block subprogram or package The scope rules for exceptions and variables are the same But unlike variables exceptions cannot be passed as parameters to subprograms Some exceptions are predefined by PL SQL For a list of these exceptions see Predefined Exceptions on page 6 4 PL SQL declares predefined exceptions globally in package STANDARD so you need not declare them yourself Redeclaring predefined exceptions is error prone because your local declaration overrides the global declaration In such cases you must use dot notation to specify the predefined exception as follows EXCEPTION WHEN invalid_number OR STANDARD INVALID_NUMBER THEN The exception handling part of a PL SQL block is option
318. cy 5 45 READ ONLY parameter 5 50 readability 2 2 3 19 read only transaction 5 50 REAL subtype 2 13 record 4 28 ROWTYPE 5 16 assigning 4 33 comparing 4 35 declaring 4 30 defining 4 29 implicit declaration 5 16 initializing 4 31 manipulating 4 35 nesting 4 29 referencing 4 31 syntax 11 128 RECORD datatype 4 28 recursion 7 23 infinite 7 24 mutual 7 26 terminating condition 7 24 versus iteration 7 27 Index 11 ref 9 28 dangling 9 34 declaring 9 29 dereferencing 9 34 REF CURSOR datatype 5 19 defining 5 20 REF operator 9 33 REF type modifier 9 29 reference type 2 10 relational operator 2 45 remote access indicator 2 34 REPEAT UNTIL structure mimicking 3 10 REPLACE function treatment of nulls 2 51 reraising an exception 6 14 reserved words F 1 misuse of 2 5 using as quoted identifier 2 6 resolution name 2 35 E 1 RESTRICT_REFERENCES pragma 9 12 result set 1 5 5 11 result value function 7 5 RETURN clause cursor 5 15 function 7 5 RETURN statement 7 7 syntax 11 132 return type 5 20 7 21 RETURNING clause 5 55 9 37 reusability 7 3 reusable packages 5 55 REVERSE reserved word 3 11 rollback implicit 5 49 statement level 5 47 rollback segment 5 45 ROLLBACK statement 5 47 effect on savepoints 5 48 syntax 11 134 routine external 10 2 service 10 17 row lock 5 51 Index 12 row Operator 5 7 ROWCOUNT cursor attribute 5 39 5 43 rowid 2 16 ROWID dat
319. d INTEGER END emp_actions CREATE PACKAGE BODY emp_actions AS BEGIN number_hired 0 END emp_actions You can code and compile a specification without its body Once the specification has been compiled stored subprograms that reference the package can be compiled as well You need not define the package bodies fully until you are ready to complete the application Furthermore you can debug enhance or replace a package body without changing the interface package specification to the package body That means you need not recompile calling programs Cursors and subprograms declared in a package specification must be defined in the package body Other program items declared in the package specification cannot be redeclared in the package body To match subprogram specifications and bodies PL SQL does a token by token comparison of their headers So except for white space the headers must match word for word Otherwise PL SQL raises an exception Collections Cursors Exceptions Functions Procedures Records 11 120 PL SQL User s Guide and Reference Procedures Procedures Syntax A procedure is a subprogram which can take parameters and be invoked Generally you use a procedure to perform an action A procedure has two parts the specification and the body The procedure specification begins with the keyword PROCEDURE and ends with the procedure name or a parameter list Pa
320. d a value actual parameter can be a constant initialized variable literal or expression actual parameter is passed by reference a pointer to the value is passed in Parameter Default Values must be specified returns values to the caller formal parameter acts like an uninitialized variable formal parameter cannot be used in an expression and must be assigned a value actual parameter must be a variable actual parameter is passed by value a copy of the value is passed out must be specified passes initial values to a subprogram and returns updated values to the caller formal parameter acts like an initialized variable formal parameter should be assigned a value actual parameter must be a variable actual parameter is passed by value a copy of the value is passed in and out As the example below shows you can initialize IN parameters to default values That way you can pass different numbers of actual parameters to a subprogram accepting or overriding the default values as you please Moreover you can add new formal parameters without having to change every call to the subprogram PROCEDURE create_dept new_dname CHAR DEFAUL 1 TEMP IS new_loc CHAR DEFAUL BEGI INSERT INTO dept VALUES deptno_seq Ni EXTVAL new_dname TEMP new_loc Subprograms 7 15 Parameter Default Values If an actual paramet
321. d can store an entire row of data selected from the table or fetched from a cursor or cursor variable Columns in a row and corresponding fields in a record have the same names and datatypes In the example below you declare a record named dept_rec Its fields have the same names and datatypes as the columns in the dept table DECLARE dept_rec deptSROWTYPE declare record variable You use dot notation to reference fields as the following example shows my_deptno dept_rec deptno Overview 1 7 Main Features If you declare a cursor that retrieves the last name salary hire date and job title of an employee you can use ROWTYPE to declare a record that stores the same information as follows DECLARE CURSOR cl IS SELECT ename sal hiredate job FROM emp emp_rec c1 ROWTYPE declare record variable that represents a row in the emp table When you execute the statement FETCH cl INTO emp_rec the value in the ename column of the emp table is assigned to the ename field of emp_rec the value in the sal column is assigned to the sal field and so on Figure 1 3 shows how the result might appear Figure 1 3 ROWTYPE Record emp_rec mp_rec enam emp_rec sal mp_rec hiredat emp_rec job Control Structures Control structures are the most important PL SQL extension to SQL Not only does PL SQL let you manipulate Oracle data it lets you process the
322. d moving outward either abasis of length 3 using the three identifiers as a column name qualified by a table name qualified by a schema name or abasis of length 2 using the first two identifiers as a column name of some user defined type qualified by a table alias Given a chain of four identifiers the compiler tries to find a basis of length 2 using the first two identifiers as a column name of some user defined type qualified by a table alias starting with the current scope and moving outward Once the compiler finds the basis as a column name it tries to resolve the complete reference by finding a component of the basis and so on depending upon the type of the column name Here are the rules for finding the basis in SOL scope when the compiler expects to find a row expression which is a table alias that can appear by itself it can be used only with an object table and operator REF or VALUE or inan INSERT or UPDATE statement for an object table Given one identifier the compiler tries to find a basis of length 1 as a table alias starting with the current scope and moving outward If the table alias does not correspond to an object table the compiler generates an error Given a chain of two or more identifiers the compiler generates an error E 6 PL SQL User s Guide and Reference Name Resolution Algorithm If the name being resolved either a does not appear in SQL scope or appears in SQL scope
323. d need not be 1 However the loop counter increment or decrement must be 1 Some languages provide a STEP clause which lets you specify a different increment An example written in BASIC follows FOR J 5 TO 15 STEP 5 REM assign values 5 10 15 to J sequence_of_statements J has values 5 10 15 NEXT J PL SQL has no such structure but you can easily build one Consider the following example FOR j IN 5 15 LOOP assign values 5 6 7 to j IF MOD j 5 0 THEN pass multiples of 5 sequence_of_statements j has values 5 10 15 END IF END LOOP This loop is logically equivalent to the previous BASIC loop Within the sequence of statements the loop counter has only the values 5 10 and 15 You might prefer the less elegant but more efficient method shown in the example below Within the sequence of statements each reference to the loop counter is multiplied by the increment FOR j IN 1 3 LOOP assign values 1 2 3 to j sequence_of_statements ach j becomes 3 5 END LOOP Dynamic Ranges PL SQL lets you determine the loop range dynamically at run time as the following example shows SELECT COUNT empno INTO emp_count FROM emp FOR i IN 1 emp_count LOOP END LOOP The value of emp_count is unknown at compile time the SELECT statement returns the value at run time 3 12 PL SQL User s Guide and Reference Iterative Control LO
324. d that several arithmetic operations are defined for complex numbers CREATE TYPE Complex AS OBJECT rpart REAL ipart REAL EMBER FUNCTION plus x Complex RETURN Complex EMBER FUNCTION less x Complex RETURN Complex EMBER FUNCTION times x Complex RETURN Complex EMBER FUNCTION divby x Complex RETURN Complex CREATE TYPE BODY Complex AS EMBER FUNCTION plus x Complex RETURN Complex IS BEGI RETURN Complex rpart x rpart ipart x ipart END plus EMBER FUNCTION less x Complex RETURN Complex IS BEGIN RETURN Complex rpart x rpart ipart x ipart END less EMBER FUNCTION times x Complex RETURN Complex IS BEGI RETURN Complex rpart x rpart ipart x ipart rpart x ipart ipart x rpart El d ct E D EMBER FUNCTION divby x Complex RETURN Complex IS z REAL x rpart 2 x ipart 2 RETURN Complex rpart x rpart ipart x ipart z ipart x rpart rpart x ipart z END divby z 9 6 PL SQL User s Guide and Reference Components of an Object Type Components of an Object Type Attributes An object type encapsulates data and operations So you can declare attributes and methods in an object type specification but not constants exceptions cursors or types At least one a
325. data using conditional iterative and sequential flow of control statements such as IF THEN ELSE FOR LOOP WHILE LOOP EXIT WHEN and GOTO Collectively these statements can handle any situation Conditional Control Often it is necessary to take alternative actions depending on circumstances The IF THEN ELSE statement lets you execute a sequence of statements conditionally The IF clause checks a condition the THEN clause defines what to do if the condition is true the ELSE clause defines what to do if the condition is false or null 1 8 PL SQL User s Guide and Reference Main Features Consider the program below which processes a bank transaction Before allowing you to withdraw 500 from account 3 it makes sure the account has sufficient funds to cover the withdrawal If the funds are available the program debits the account otherwise the program inserts a record into an audit table available online in file examp2 DECLARE acct_balance BER 11 2 acct CONSTAN BER 4 3 debit_amt CONSTAN BER 5 2 500 00 BEGI SELECT bal INTO acct_balance FROM accounts WHERE account_id acct FOR UPDATE OF bal IF acct_balance gt debit_amt THEN UPDATE accounts SET bal bal debit_amt WHERE account_id acct ELSE INSERT INTO temp VALUES acct acct_balanc
326. ded Occasionally it can simplify logic enough to warrant its use The NULL statement can make the meaning and action of conditional statements clear and so improve readability Overuse of GOTO statements can result in complex unstructured code sometimes called spaghetti code that is hard to understand and maintain So use GOTO statements sparingly For example to branch from a deeply nested structure to an error handling routine raise an exception rather than use a GOTO statement GOTO Statement The GOTO statement branches to a label unconditionally The label must be unique within its scope and must precede an executable statement or a PL SQL block When executed the GOTO statement transfers control to the labeled statement or block In the following example you go to an executable statement farther down in a sequence of statements BEGIN GOTO insert_row lt lt insert_row gt gt INSERT INTO emp VALUES END In the next example you go to a PL SQL block farther up in a sequence of statements BEGI lt lt update_row gt gt BEGIN UPDATE emp SET END GOTO update_row END Control Structures 3 15 Sequential Control GOTO and NULL Statements The label lt lt end_loop gt gt in the following example is illegal because it does not precede an executable statement DECLARE done BOOLEAN BEGIN FOR i IN 1 50 LOOP IF done THEN GOTO end_loop
327. default the loop index is assigned the value of lower_bound If that value is not greater than the value of upper_bound the sequence of statements in the loop is executed then the index is incremented If the value of the index is still not greater than the value of upper_bound the sequence of statements is executed again This process repeats until the value of the index is greater than the value of upper_bound At that point the loop completes REVERSE By default iteration proceeds upward from the lower bound to the upper bound However if you use the keyword REVERSE iteration proceeds downward from the upper bound to the lower bound An example follows FOR i IN REVERSE 1 10 LOOP i starts at 10 ends at 1 statements her xecute 10 times END LOOP Language Elements 11 99 LOOP Statements The loop index is assigned the value of upper_bound If that value is not less than the value of lower_bound the sequence of statements in the loop is executed then the index is decremented If the value of the index is still not less than the value of lower_bound the sequence of statements is executed again This process repeats until the value of the index is less than the value of lower_bound At that point the loop completes cursor_for_loop_ statement A cursor FOR loop implicitly declares its loop index as a SROWTYPE record opens a cursor repeatedly fetches rows of values from the result set in
328. duration TimeRec FUNCTION item n INTEGER RETURN Agendaltem IS item_info Agendaltem BEGIN RETURN item_info return record END BEGIN IF item 3 duration minutes gt 30 THEN call function You also use extended dot notation to reference the attributes of an object stored in a field as the following example shows DECLARE YPE FlightRec IS RECORD flight_no INTEGER plane_id VARCHAR2 10 4 32 PL SQL User s Guide and Reference Assigning and Comparing Records captain Employee declare object passengers PassengerList declare varray depart_tim TimeRec declare nested record airport_code VARCHAR2 10 flight FlightRec BEGIN IF flight captain name H Rawlins THEN Assigning and Comparing Records You can assign the value of an expression to a specific field in a record using the following syntax record_name field_name expression In the following example you convert an employee name to upper case emp_info ename UPPER emp_info ename Instead of assigning values separately to each field in a record you can assign values to all fields at once This can be done in two ways First you can assign one user defined record to another if they have the same datatype Having fields that match exactly is not enough Consider the following
329. dynamically registered with PL SQL and called by you to do special purpose processing At run time PL SQL loads the library dynamically then calls the routine as if it were a PL SQL subprogram To safeguard your database the routine runs in a separate address space A dynamic link library DLL is an operating system file that stores external procedures For safety your DBA controls access to the DLL Using the CREATE LIBRARY statement the DBA creates a schema object called an alias library which represents the DLL Then if you are an authorized user the DBA grants you EXECUTE privileges on the alias library After registering an external procedure you can call it from any PL SQL program It executes with the privileges granted to your userid For more information see Chapter 10 external_clause NAME external_procedure_name EXTERNAL LIBRARY gt C Em A PARAMETERS rom external_parameter Lo BY REF external_datatype ii WITH CONTEXT B external_parameter CONTEXT parameter_name RETURN 11 70 PL SQL User s Guide and Reference External Procedures property Tm paar Keyword and Parameter Description LIBRARY This clause specifies the name of the alias library The name is a PL SQL identifier So if you enclose the name in double quotes it becomes case sensitive You must have EXECUTE privileges on the alias library
330. e Avoiding Capture You can avoid inner capture in DML statements by following these rules Specify an alias for each table in the DML statement Keep table aliases unique throughout the DML statement a Avoid table aliases that match schema names used in the query Qualify each column reference with the table alias Qualifying a reference with lt schema name gt lt table name gt does not prevent inner capture if the DML statement references tables that have columns of a user defined object type Accessing Attributes and Methods Columns of a user defined object type allow for more inner capture situations To minimize problems the following new rules were added to the name resolution algorithm a All references to attributes and methods must be qualified by a table alias So when referencing a table if you reference the attributes or methods of an object stored in that table the table name must be accompanied by an alias As the following examples show column qualified references to an attribute or method are illegal if they are prefixed with a table name or schema and table name CREATE TYPE t1 AS OBJECT x BER CREATE TABLE tbl col t1 SELECT col x FROM tbl illegal SELECT tb1 col x FROM tbl illegal SELECT scott tbl col x FROM scott tbl illegal SELECT t col x FROM tbl t UP
331. e Insufficient funds insert account current balance and message END IF COMMIT END A sequence of statements that uses query results to select alternative actions is common in database applications Another common sequence inserts or deletes a row only if an associated entry is found in another table You can bundle these common sequences into a PL SQL block using conditional logic This can improve performance and simplify the integrity checks built into Oracle Forms applications Iterative Control LOOP statements let you execute a sequence of statements multiple times You place the keyword LOOP before the first statement in the sequence and the keywords END LOOP after the last statement in the sequence The following example shows the simplest kind of loop which repeats a sequence of statements continually LOOP sequence of statements END LOOP Overview 1 9 Main Features The FOR LOOP statement lets you specify a range of integers then execute a sequence of statements once for each integer in the range For example suppose that you are a manufacturer of custom made cars and that each car has a serial number To keep track of which customer buys each car you might use the following FOR loop FOR i IN 1 order_gqty LOOP UPDATE sales SET custno customer_id WHERE serial_num serial_num_seq NEXTVAL END LOOP The WHILE LOOP statement associates a cond
332. e declaration is elaborated The SROWTYPE attribute lets you declare records structured like a row of data ina database table 11 136 PL SQL User s Guide and Reference ROWTYPE Attribute Examples Related Topics To reference a field you use dot notation For example you might reference the dept no field as follows IF emp_rec deptno 20 THEN You can assign the value of an expression to a specific field as the following example shows mp_rec sal average 1 15 There are two ways to assign values to all fields in a record at once First PL SQL allows aggregate assignment between entire records if their declarations refer to the same table or cursor Second you can assign a list of column values to a record by using the SELECT or FETCH statement The column names must appear in the order in which they were defined by the CREATE TABLE or CREATE VIEW statement Select items fetched from a cursor associated with SROWTYPE must have simple names or if they are expressions must have aliases In the example below you use SROWTYPE to declare two records The first record stores a row selected from the emp table The second record stores a row fetched from the c1 cursor DECLARE emp rec empSROWTYPE CURSOR c1 IS SELECT deptno dname loc FROM dept dept_rec c1 ROWTYPE In the next example you select a row from the emp ta
333. e previously declared within the current scope Language Elements 11 149 TYPE Attribute Usage Notes Related Topics record_name This identifies a user defined or SROWTYPE record previously declared within the current scope record_name field_name This identifies a field in a user defined or SROWTYPE record previously declared within the current scope table_name column_name This refers to a table and column that must be accessible when the declaration is elaborated variable_name This is the name of a variable previously declared in the same scope The STYPE attribute is particularly useful when declaring variables fields and parameters that refer to database columns However the NOT NULL column constraint does not apply to items declared using STYPE Constants and Variables X ROWTYPE Attribute 11 150 PL SQL User s Guide and Reference UPDATE Statement UPDATE Statement The UPDATE statement changes the values of specified columns in one or more rows in a table or view For a full description of the UPDATE statement see Oracle8 SQL Reference Syntax update_statement table_reference es CURRENT OF RETURNING l variable_name E E host_variable_name gt row_expression Keyword and Parameter Description table_reference This identifies a table or view that must be accessible when you execute the UPDATE statement and
334. e you use LIMIT to determine if you can add 20 more elements to varray projects IF projects COUNT 20 lt projects LIMIT THEN add 20 more elements Related Topics Collections 11 20 PL SQL User s Guide and Reference Collections Collections Syntax A collection is an ordered group of elements all of the same type for example the grades for a class of students Each element has a unique subscript that determines its position in the collection PL SQL offers two kinds of collections nested tables and varrays short for variable size arrays Collections work like the arrays found in most third generation programming languages However collections can have only one dimension and must be indexed by integers In some languages such as Ada and Pascal arrays can have multiple dimensions and can be indexed by enumeration types Collections can store instances of an object type and conversely can be attributes of an object type Also collections can be passed as parameters So you can use them to move columns of data into and out of database tables or between client side applications and stored subprograms For more information see Defining and Declaring Collections on page 4 5 table_type_definition NOT NULL TYPE IS TABLE OF b element_type IZS INDEX BY BINARY_INTEGER varray_type_definition VARRAY em OEO NOT NULL NULL AD collection_declaration collection_name type_name Lan
335. e Bs a ed EE Bt een as 2 41 Expressions and Comparisons occcocncononncononanononinononanononononononononononononononon oran ononononononanononononananonononos 2 41 Operator Precedence eiii illa aaa 2 42 Logical Operators cuicos 2 43 Comparison Operator osnan a o a AEA EE A S AE TERA 2 44 Concatenation Operator i0 ccissesescecassevestecssseses nenie eeii a E aa ie 2 46 Boolean Expressions cmcitiocnci n irreal tai e a a a a a a To 2 46 Handling Nullsio ion dell a e e a ari 2 48 Built In FunictoNS ucraniana tartera dra dad 2 51 3 Control Structures OVErVIEW brn asen tias 3 2 Conditional Control IF Statements oononncnncnocnconcoonconnnononnnoonono non conocen ccoo non ccoo non nnnnncn nano ncn nano nannnnns 3 2 TE THEN Ss a Raat a cde eh e gos elas AE a Be q rl oie 3 3 IESTHEN SELSE st on A So OT Dee UIT tac tea DOTA 3 3 IE FH EN ELS DB iii tsetse A died 3 4 Guidelines cu A a ciao 3 5 Iterative Control LOOP and EXIT Statements oooooncnnocinonionononoononononnconnonncconon non onco non onconanoncnnnnos 3 6 LODO Pus adi naa 3 6 WHILETOO Por aid dada 3 9 FORTEOO Pitt o o o a dl Ed Sel Bh dd 3 10 Sequential Control GOTO and NULL Statements cooccococononinononnnnnnnnnnonnnnnorannnonnanararannnnannnans 3 15 GOTO Statement A ive eee 3 15 NULL Statement A Sen ee ences th heehee tn oe E ee net E eee E 3 19 4 Collections and Records What Isa Collection comcel EEEE 4 2 Understanding Nested Tables ccccccecccssssss
336. e FETCH statement to retrieve the first row You can execute FETCH repeatedly until all rows have been retrieved When the last row has been processed you release the cursor with the CLOSE statement You can process several queries in parallel by declaring and opening multiple cursors Interaction with Oracle 5 9 Managing Cursors Declaring a Cursor Forward references are not allowed in PL SQL So you must declare a cursor before referencing it in other statements When you declare a cursor you name it and associate it with a specific query using the syntax CURSOR cursor_name parameter parameter RETURN return_type IS select_statement where return_type must represent a record or a row in a database table and parameter stands for the following syntax cursor_parameter_name IN datatype DEFAULT expr For example you might declare cursors named c1 and c2 as follows DECLARE CURSOR cl IS SELECT empno ename job sal FROM emp WHERE sal gt 2000 CURSOR c2 RETURN dept ROWTYPE IS SELECT FROM dept WHERE deptno 10 The cursor name is an undeclared identifier not the name of a PL SQL variable You cannot assign values to a cursor name or use it in an expression However cursors and variables follow the same scoping rules Naming cursors after database tables is allowed but not recommended A cursor can t
337. e IF statement does nothing In either case control passes to the next statement The second form of IF statement adds the keyword ELSE followed by an alternative sequence of statements The sequence of statements in the ELSE clause is executed only if the Boolean expression yields FALSE or NULL Thus the ELSE clause ensures that a sequence of statements is executed The third form of IF statement uses the keyword ELSIF to introduce additional Boolean expressions If the first expression yields FALSE or NULL the ELSIF clause evaluates another expression An IF statement can have any number of ELSIF clauses the final ELSE clause is optional Boolean expressions are evaluated one by one from top to bottom If any expression yields TRUE its associated sequence of statements is executed and control passes to the next statement If all expressions yield FALSE or NULL the sequence in the ELSE clause is executed An IF statement never executes more than one sequence of statements because processing is complete after any sequence of statements is executed However the THEN and ELSE clauses can include more IF statements That is IF statements can be nested Examples In the example below if shoe_count has a value of 10 both the first and second Boolean expressions yield TRUE Nevertheless order_quantity is assigned the p
338. e Separate Address Space 10 6 PL SQL User s Guide and Reference How PL SQL Calls an External Procedure An Example In the last example you wrote PL SQL function gcd which registered external procedure c_gcd as follows CREATE FUNCTION gcd find greatest common divisor of x and y x BINARY_INTEGER y BINARY INTEGER RETURN BINARY_INTEGER AS EXTERNAL LIBRARY c_utils AME c_gcd quotes preserve lower cas ANGUAGE C In the example below you call PL SQL function gcd from an anonymous block PL SQL passes the two integer parameters to external function c_gcd which returns their greatest common divisor DECLARE g BINARY_INTEGER a BINARY_INTEGER b BINARY_INTEGER Q BEGIN g gcd a b call function IF g IN 2 4 8 THEN How PL SQL Calls an External Procedure To call an external procedure PL SQL must know in which DLL it resides So PL SQL looks up the alias library in the EXTERNAL clause of the subprogram that registered the external procedure then has Oracle look up the DLL in the data dictionary Next PL SQL alerts a Listener process which in turn spawns launches a session specific agent named extproc Then the Listener hands over the connection to extproc PL SQL passes to extproc the name of the DLL the name of the external procedure and any parameters
339. e and Reference Calling an External Procedure An Example WITH CONTEXT Specifies that a context pointer will be passed to the external procedure The context data structure is opaque to the external procedure but is available to service routines called by the external procedure For more information see Using the WITH CONTEXT Clause on page 10 16 PARAMETERS Specifies the positions and datatypes of parameters passed to the external procedure It can also specify parameter properties such as current length and maximum length and the preferred parameter passing method by value or by reference For more information see Using the PARAMETERS Clause on page 10 12 Assume that C routine c_gcd which finds the greatest common divisor of two numbers is stored in DLL ut ils soand that you have EXECUTE privileges on alias library c_utils The C prototype for c_gcd follows int c_gcd int x_val int y_val In the following example you write a PL SQL stand alone function named gcd that registers C routine c_gcdas an external function CREATE FUNCTION gcd find greatest common divisor of x and y x BINARY _INTEGER y BINARY_INTEGER RETURN BINARY_INTEGER AS EXTERNAL LIBRARY c_utils AME Cc_gcd quotes preserve lower cas ANGUAGE C Calling an External Procedure You do not call an external procedure directly Instead you call the
340. e direction in which the query walks the tree down from the root or up from the branches with the PRIOR operator In the START WITH clause you specify a condition that identifies the root of the tree ROWID ROWID returns the rowid binary address of a row in a database table Recall that PL SQL provides a datatype also named ROWID You can use variables of type ROWID to store rowids in a readable format In the following example you declare a variable named row_id for that purpose DECLARE row_id ROWID When you select or fetch a rowid into a ROWID variable you can use the function ROWIDTOCHAR which converts the binary value to an 18 byte character string Then you can compare the ROWID variable to the ROWID pseudocolumn in the WHERE clause of an UPDATE or DELETE statement to identify the latest row fetched from a cursor For an example see Fetching Across Commits on page 5 53 ROWNUM ROWNUM returns a number indicating the order in which a row was selected from a table The first row selected has a ROWNUM of 1 the second row has a ROWNUM of 2 and so on If a SELECT statement includes an ORDER BY clause ROWNUMs are assigned to the retrieved rows before the sort is done You can use ROWNUM in an UPDATE statement to assign unique values to each row in a table Also you can use ROWNUM in the WHERE clause of a SELECT statement to limit the number of rows retrieved as fo
341. e in the list record_name This identifies a user defined or ROWTYPE record into which rows of values are fetched For each select_item value returned by the query there must be a corresponding type compatible field in the record table_reference This identifies a table or view that must be accessible when you execute the SELECT statement and for which you must have SELECT privileges For the syntax of table_reference see DELETE Statement on page 11 49 H THE The operand of THE is a subquery that returns a single column value to the SELECT statement The column value must be a nested table Operator THE informs Oracle that the value is a nested table not a scalar value subquery This is query that provides a value or set of values to the SELECT statement Its syntax is like that of select_into_statement without the INTO clause See SELECT INTO Statement on page 11 139 alias This is another usually short name for the referenced column table or view rest_of_statement This is anything that can legally follow the FROM clause in a SELECT statement 11 140 PL SQL User s Guide and Reference SELECT INTO Statement Usage Notes Example Related Topics The implicit SOL cursor and the cursor attributes SNOTFOUND FOUND ROWCOUNT and ISOPEN let you access useful information about the execution of as ELECT INTO statement
342. e of that object If the ref is dangling DEREF returns a null object In the example below you dereference a ref to a Person object Notice that you select the ref from dummy table dua1 You need not specify an object table and search criteria because each object stored in an object table has a unique immutable object identifier which is part of every ref to that object DECLARE pl Person p_ref REF Person name VARCHAR2 15 BEGIN Assume that p_ref holds a valid reference to an object stored in an object table SELECT DEREF p_ref INTO pl FROM dual name pl last_name 9 34 PL SQL User s Guide and Reference Manipulating Objects You can use DEREF in successive SQL statements to dereference refs as the following example shows CREATE TYPE PersonRef AS OBJECT p_ref REF Person DECLARE name VARCHAR2 15 pr_ref REF PersonRef pr PersonRef p Person BEGI Assume pr_ref holds a valid reference SELECT DEREF pr_ref INTO pr FROM dual SELECT DEREF pr p_ref INTO p FROM dual name p last_name END The next example shows that you cannot use operator DEREF within procedural statements BEGIN pl DEREF p_ref illegal Within SQL statements you can use dot notation to navigate through object columns to ref attributes and th
343. e old column values are used on the right side of the equal sign In the following example you increase every employee s salary by 10 The original value of the sal column is multiplied by 1 1 then the result is assigned to the sal column UPDATE emp SET sal sal 1 1 SET column_name subquery2 This clause assigns the value retrieved from the database by subquery2 to the column identified by column_name The subquery must return exactly one row and one column 11 152 PL SQL User s Guide and Reference UPDATE Statement Usage Notes SET column_name column_name subquery3 This clause assigns the values retrieved from the database by subquery3 to the columns in the column_name list The subquery must return exactly one row that includes all the columns listed The column values returned by the subquery are assigned to the columns in the column list in order Thus the first value is assigned to the first column in the list the second value is assigned to the second column in the list and so on In the following correlated query the column item_idis assigned the value stored in item_num and the column price is assigned the value stored in item_price UPDATE inventory inv alias SET item_id price SELECT item_num item_price FROM item_table WHERE item_name inv item_name WHERE search_condition This clause chooses which rows to update in the databa
344. e specification All the information a client program needs to use the methods is in the specification Think of the specification as an operational interface and of the body as a black box You can debug enhance or replace the body without changing the specification An object type encapsulates data and operations So you can declare attributes and methods in an object type specification but not constants exceptions cursors or types At least one attribute is required methods are optional In an object type specification all attributes must be declared before any methods Only subprograms have an underlying implementation So if an object type specification declares only attributes the object type body is unnecessary You cannot declare attributes in the body All declarations in the object type specification are public visible outside the object type However the object type body can contain private declarations which define methods necessary for the internal workings of the object type The scope of private declarations is local to the object type body You can refer to an attribute only by name not by its position in the object type To access or change the value of an attribute you use dot notation Attribute names can be chained which allows you to access the attributes of a nested object type In an object type methods can reference attributes and other methods without a qualifier In SQL statements calls to a parame
345. e the RETURN statement with the RETURN clause which specifies the datatype of the result value in a function specification A subprogram can contain several RETURN statements none of which need be the last lexical statement Executing any of them completes the subprogram immediately However to have multiple exit points in a subprogram is a poor programming practice In procedures a RETURN statement cannot contain an expression The statement simply returns control to the caller before the normal end of the procedure is reached 11 132 PL SQL User s Guide and Reference RETURN Statement Example Related Topics However in functions a RETURN statement must contain an expression which is evaluated when the RI ETURN statement is executed The resulting value is assigned to the function identifier Therefore a function must contain at least one RETURN statement Otherwise PL SQL raises the predefined exception PROGRAM_ERROR at run time The RI ETURN statement can also be used in an anonymous block to exit the block and all enclosing blocks immediately but the RETURN statement cannot contain an expression In the following example the function balance RETURNs the balance of a specified bank account BEGIN y SE FUNCTION balance acct_id INTE acct_bal REAL RETURN acct_bal ID balance Functions Procedures GER R ETURN RE
346. e the behavior of formal parameters The three parameter modes IN the default OUT and IN OUT can be used with any subprogram However avoid using the OUT and IN OUT modes with functions The purpose of a function is to take zero or more arguments actual parameters and return a single value To have a function return multiple values is a poor programming practice Also functions should be free from side effects which change the values of variables not local to the subprogram An IN parameter lets you pass values to the subprogram being called Inside the subprogram an IN parameter acts like a constant Therefore it cannot be assigned a value For example the following assignment statement causes a compilation error PROCEDURE debit_account acct_id IN INTEGER amount IN REAL IS minimum_purchase CONSTAN FAL 10 0 service_charge CONSTANT REAL 0 50 BEGI Y IF amount lt minimum purchase THEN amount amount service_charge causes syntax error END IF The actual parameter that corresponds to an IN formal parameter can be a constant literal initialized variable or expression Unlike OUT and IN OUT parameters IN parameters can be initialized to default values For more information see Parameter Default Values on page 7 15 An OUT parameter lets you return values to the caller of a subprogram Inside the subprogram an OUT parameter acts like an uninitia
347. e to a date value date _literal This is a literal that represents a date value or a value implicitly convertible to a date value date_variable_name This identifies a previously declared variable that stores a date value In a Boolean expression you can only compare values that have compatible datatypes For more information see Datatype Conversion on page 2 25 In conditional control statements if a Boolean expression yields TRUE its associated sequence of statements is executed But if the expression yields FALS or NULL its associated sequence of statements is not executed CJ Language Elements 11 67 Expressions The relational operators can be applied to operands of type BOOLEAN By definition TRUE is greater than FALSE Comparisons involving nulls always yield a null The value of a Boolean expression can be assigned only to Boolean variables not to host variables or database columns Also datatype conversion to or from type BOOLEAN is not supported You can use the addition and subtraction operators to increment or decrement a date value as the following examples show hire date 10 MAY 95 hire_date hire_date 1 makes hire date 11 MAY 95 hire date hire dat 5 makes hire date 06 MAY 95 When PL SQL evaluates a boolean expression NOT has the highest precedence AND has the next highest precedence and OR has the lowest precedence However you can use
348. eference 10 External Procedures Well if I called the wrong number why did you answer the phone James Thurber PL SQL is a powerful development tool you can use it for almost any purpose But it is specialized for SQL transaction processing So some tasks are more quickly or easily done in a lower level language such as C which is more efficient at machine precision calculations For example a Fast Fourier Transform FFT routine written in C runs faster than one written in PL SQL To support such special purpose processing PL SQL provides an interface for calling routines written in other languages This makes the strengths and capabilities of those languages available to you No longer are you restricted to one language with its inherent limitations Major Topics What Is an External Procedure Creating an External Procedure Registering an External Procedure Calling an External Procedure How PL SQL Calls an External Procedure Passing Parameters to an External Procedure Using Service Routines Doing Callbacks Debugging External Procedures Guidelines for External Procedures Restrictions on External Procedures External Procedures 10 1 What Is an External Procedure What Is an External Procedure An external procedure is a third generation language routine stored in a dynamic link library DLL registered with PL SQL and called by you to do special purpose processing The routine must be callable from C b
349. ement SOLSROWCOUNT yields 0 if the statement affected no rows The cursor attributes apply to every cursor or cursor variable So for example you can open multiple cursors then use FOUND or SNOTFOUND to tell which cursors have rows left to fetch Likewise you can use SROWCOUNT to tell how many rows have been fetched so far 11 34 PL SQL User s Guide and Reference Cursor Attributes Examples If a cursor or cursor variable is not open referencing it with FOUND SNOTFOUND or SROWCOUNT raises the predefined exception INVALID_CURSOR When a cursor or cursor variable is opened the rows that satisfy the associated query are identified and form the result set Rows are fetched from the result set one at a time If a SELECT INTO statement returns more than one row PL SQL raises the predefined exception TOO_MANY_ROWS and sets SROWCOUNT to 1 not the actual number of rows that satisfy the query Before the first fetch SNOTFOUND evaluates to NULL So if FETCH never executes successfully the loop is never exited That is because the EXIT WHEN statement executes only if its WHEN condition is true To be safe you might want to use the following EXIT statement instead EXIT WHEN c1SNOTFOUND OR ciSNOTFOUND IS NULL You can use the cursor attributes in procedural statements but not in SQL statements The PL SQL block below uses FOUND to select an action The IF statement either inserts a row or exits
350. ements that a collection currently contains which is useful because the current size of a collection is not always known You can use COUNT wherever an integer expression is allowed For varrays COUNT always equals LAST For nested tables normally COUNT equals LAST But if you delete elements from the middle of a nested table COUNT is smaller than LAST DELETE This procedure has three forms DELETE removes all elements from a collection DELETE n removes the nth element from a nested table If nis null DELETE n does nothing DELETE m n removes all elements in the range m n froma nested table If mis larger than n or if mor nis null DELETE m n does nothing index This is an expression that must yield or convert implicitly to an integer For more information see Datatype Conversion on page 2 25 EXISTS EXISTS n returns TRUE if the nth element in a collection exists Otherwise EXISTS n returns FALSE Mainly you use EXISTS with DELETE to maintain sparse nested tables You can also use EXISTS to avoid raising an exception when you reference a nonexistent element When passed an out of range subscript EXISTS returns FALSE instead of raising SUBSCRIPT_OUTSIDE_LIMIT EXTEND This procedure has three forms EXTEND appends one null element to a collection EXTEND n appends n null elements to a collection EXTEND n i appe
351. emp WHERE job SALESMAN AND comm gt sal FOR UPDATE NOWAIT The FOR UPDATE clause identifies the rows that will be updated or deleted then locks each row in the result set This is useful when you want to base an update on the existing values in a row In that case you must make sure the row is not changed by another user before the update The optional keyword NOWAIT tells Oracle not to wait if the table has been locked by another user Control is immediately returned to your program so that it can do other work before trying again to acquire the lock If you omit the keyword NOWAIT Oracle waits until the table is available The wait has no limit unless the table is remote in which case the Oracle initialization parameter DISTRIBUTED_LOCK_TIMEOUT sets a limit All rows are locked when you open the cursor not as they are fetched The rows are unlocked when you commit or roll back the transaction So you cannot fetch from a FOR UPDATE cursor after a commit For a workaround see Fetching Across Commits on page 5 53 Interaction with Oracle 5 51 Processing Transactions When querying multiple tables you can use the FOR UPDATE clause to confine row locking to particular tables Rows in a table are locked only if the FOR UPDATE OF clause refers to a column in that table For example the following query locks rows in the emp table but not in the dept table
352. emp coll TYPE CURSOR c1 IS SELECT nl n2 n3 FROM data_table WHERE exper_num 1 BEGIN FOR cl_rec IN cl LOOP calculate and store the results result cl_rec n2 cl_rec nl cl_rec n3 INSERT INTO temp VALUES result NULL NULL END LOOP COMMIT END When the cursor FOR loop is entered the cursor name cannot belong to a cursor that was already opened by an OPEN statement or by an enclosing cursor FOR loop Before each iteration of the FOR loop PL SQL fetches into the implicitly declared record which is equivalent to a record explicitly declared as follows cl_rec c1SROWTYPE The record is defined only inside the loop You cannot refer to its fields outside the loop For example the following reference is illegal FOR cl_rec IN cl LOOP END LOOP result cl_rec n2 3 illegal 5 16 PL SQL User s Guide and Reference Using Cursor FOR Loops The sequence of statements inside the loop is executed once for each row that satisfies the query associated with the cursor When you leave the loop the cursor is closed automatically even if you use an EXIT or GOTO statement to leave the loop prematurely or an exception is raised inside the loop Using Subqueries Using Aliases You need not declare a cursor because PL SQL lets you substitute a subquery The following cursor FOR loop calculates a bonus then inserts the result into a dat
353. ences between the CHAR and VARCHAR2 base types are discussed in Appendix C VARCHAR2 Subtypes The VARCHAR2 subtypes below have the same range of values as their base type For example VARCHAR is just another name for VARCHAR2 STRING VARCHAR You can use these subtypes for compatibility with ANSI ISO and IBM types Note Currently VARCHAR is synonymous with VARCHAR2 However in future releases of PL SQL to accommodate emerging SOL standards VARCHAR might become a separate datatype with different comparison semantics So it is a good idea to use VARCHAR2 rather than VARCHAR NLS Character Types Although the widely used 7 or 8 bit ASCII and EBCDIC character sets are adequate to represent the Roman alphabet some Asian languages such as Japanese contain thousands of characters These languages require 16 bits two bytes to represent each character How does Oracle deal with such dissimilar languages Oracle provides National Language Support NLS which lets you process single byte and multi byte character data and convert between character sets It also lets your applications run in different language environments Fundamentals 2 17 Datatypes With NLS number and date formats adapt automatically to the language conventions specified for a user session Thus NLS allows users around the world to interact with Oracle in their native languages For more information about NLS see Oracle8 SQL Reference PL SQL V2
354. ent Examples The following example shows that any variables in the query associated with a cursor are evaluated only when the cursor is opened DECLARE my_sal NUMBER 7 2 n INTEGER 2 2 CURSOR emp_cur IS SELECT n sal FROM emp BEGIN OPEN emp_cur n equals 2 here LOOP FETCH emp_cur INTO my_sal EXIT WHEN emp_curSNOTFOUND process the data Tm 1 4 dy does not affect next FETCH sal will be multiplied by 2 END LOOP In the following Pro C example you fetch rows from a host cursor variable into a host record struct named emp_rec Exit loop when done fetching EXEC SQL WHENEVER NOTFOUND DO break for 55 Fetch row into record EXEC SOL FETCH emp_cur INTO emp_rec The next example shows that you can use a different INTO clause on separate fetches with the same cursor variable Each fetch retrieves another row from the same result set for 55 Fetch row from result set EXEC SQL FETCH emp cur INTO emp_recl Fetch next row from same result set EXEC SQL FETCH emp_cur INTO emp_rec2 Related Topics CLOSE Statement Cursors Cursor Variables LOOP Statements OPEN Statement OPEN FOR Statement 11 78 PL SQL User s Guide and Reference Functions Functions Syntax A function is a subprogram which can take para
355. ents but sends SQL statements to the SQL Statement Executor in the Oracle server Figure 1 4 PL SQL Engine PL SQL Engine Procedural PL SQL PL SQL Statement Block Block Executor SQL Statement Executor Oracle 1 18 PL SQL User s Guide and Reference Architecture In the Oracle Server Application development tools that lack a local PL SQL engine must rely on Oracle to process PL SQL blocks and subprograms When it contains the PL SQL engine an Oracle server can process PL SQL blocks and subprograms as well as single SOL statements The Oracle server passes the blocks and subprograms to its local PL SQL engine Anonymous Blocks Anonymous PL SQL blocks can be embedded in an Oracle Precompiler or OCI program At run time the program lacking a local PL SQL engine sends these blocks to the Oracle server where they are compiled and executed Likewise interactive tools such as SQL Plus and Enterprise Manager lacking a local PL SQL engine must send anonymous blocks to Oracle Stored Subprograms Subprograms can be compiled separately and stored permanently in an Oracle database ready to be executed A subprogram explicitly CREATEd using an Oracle tool is called a stored subprogram Once compiled and stored in the data dictionary it is a schema object which can be referenced by any number of applications connected to that database Stored subprograms defined within a package are called packaged subprog
356. er ending multi line comment delimiter Identifiers You use identifiers to name PL SQL program items and units which include constants variables exceptions cursors cursor variables subprograms and packages Some examples of identifiers follow X t2 phone credit_limit LastName oracle number An identifier consists of a letter optionally followed by more letters numerals dollar signs underscores and number signs Other characters such as hyphens slashes and spaces are illegal as the following examples show mine amp yours illegal ampersand debit amount illegal hyphen on off illegal slash user id illegal space 2 4 PL SQL User s Guide and Reference Lexical Units The next examples show that adjoining and trailing dollar signs underscores and number signs are legal money tree SN try_again_ You can use upper lower or mixed case to write identifiers PL SQL is not case sensitive except within string and character literals So if the only difference between identifiers is the case of corresponding letters PL SQL considers the identifiers to be the same as the following example shows lastname LastName same as lastname ASTNAME same as lastname and LastName The length of an identifier cannot exceed 30 characters But every character including dollar signs underscores and number signs is significant For example PL SQL considers the following iden
357. er s Guide and Reference Managing Cursors However you can use a different INTO list on separate fetches with the same cursor Each fetch retrieves another row and assigns values to the target variables as the following example shows DECLARE CURSOR cl IS SELECT ename FROM emp namel emp enamesTYPE name2 emp enamesTYPE name3 emp enamesTYPE BEGI OPEN cl FETCH cl INTO namel this fetches first row FETCH cl INTO name2 this fetches second row FETCH cl INTO name3 this fetches third row CLOSE cl END If you fetch past the last row in the result set the values of the target variables are indeterminate Note Eventually the FETCH statement must fail to return a row so when that happens no exception is raised To detect the failure you must use the cursor attribute FOUND or SNOTFOUND For more information see Using Cursor Attributes on page 5 38 Closing a Cursor The CLOSE statement disables the cursor and the result set becomes undefined An example of the CLOSE statement follows CLOSE cl Once a cursor is closed you can reopen it Any other operation on a closed cursor raises the predefined exception INVALID_CURSOR Interaction with Oracle 5 13 Managing Cursors Using Subqueries A subquery is a query usually enclosed by parentheses that appears within another SQL data manipulation sta
358. er Description Usage Notes integer This is an optionally signed whole number without a decimal point real_number This is an optionally signed whole or fractional number with a decimal point digit This is one of the numerals 0 9 char This is a member of the PL SOL character set For more information see Character Set on page 2 2 TRUE FALSE This is a predefined Boolean value NULL This is a predefined non value which stands for a missing unknown or inapplicable value Two kinds of numeric literals can be used in arithmetic expressions integers and reals Numeric literals must be separated by punctuation Space characters can be used in addition to the punctuation A character literal is an individual character enclosed by single quotes apostrophes Character literals include all the printable characters in the PL SQL character set letters numerals spaces and special symbols 11 92 PL SQL User s Guide and Reference Literals Examples Related Topics PL SQL is case sensitive within character literals So for example PL SQL considers the literals Q and q to be different A string literal is a sequence of zero or more characters enclosed by single quotes The null string contains zero characters To represent an apostrophe within a string write two single quotes PL SOL is case sensitive within string literals So for example PL SQL considers the literals white
359. er This appendix shows you how to run the PL SQL Wrapper a stand alone utility that enables you to deliver PL SQL applications without exposing your source code Appendix E Name Resolution Thus appendix explains how PL SQL resolves references to names in potentially ambiguous procedural and SQL statements Appendix F Reserved Words This appendix lists those words reserved for use by PL SQL Notational Conventions This guide uses the following notation in code examples lt gt lower case UPPER CASE Angle brackets enclose the name of a syntactic element A double hyphen begins a single line comment which extends to the end of a line A slash asterisk and an asterisk slash delimit a multi line comment which can span multiple lines An ellipsis shows that statements or clauses irrelevant to the discussion were left out Lower case denotes user defined items such as variables parameters and exceptions Upper case denotes PL SQL keywords Terms being defined for the first time words being emphasized error messages and book titles are italicized The syntax of PL SQL is described using a simple variant of Backus Naur Form BNF which has the following symbols and lexical conventions 147 lower case UPPER CASE punctuation Brackets enclose optional items Braces enclose items only one of which is required A vertical bar separates alternatives within brackets
360. er can call a service routine to obtain OCI environment and service handles With the OCI you can use callbacks to execute SOL statements and PL SQL subprograms fetch data and manipulate LOBs Moreover callbacks and external procedures operate in the same user session and transaction context So they have the same user privileges In SOL Plus suppose you run the following script CREATE TABLE emptab empno NUMBER 10 CREATE PROCEDURE insert_emptab empno BINARY_INTEGER AS EXTERNAL AME insert_emptab LIBRARY insert_lib WITH CONTEXT PARAMETERS CONTEXT empno LONG Later you might call service routine OCIExt ProcGetEnv from external procedure insert_emptab as follows include lt stdio h gt include lt stdlib h gt include lt oratypes h gt include lt oci h gt void insert_emptab ctx empno OCIExtProcContext ctx long empno OCIEnv envhp OCISvcCtx svchp 10 22 PL SQL User s Guide and Reference Doing Callbacks OCIError errhp int err err OCIExtProcGetEnv ctx amp envhp amp svchp amp errhp Restrictions on Callbacks With callbacks the following SOL commands and OCI routines are not supported a transaction control commands such as COMMIT a data definition commands such as CREATE a object oriented OCI routines such as OCIRefClear polling mode OCI r
361. er is not passed the default value of its corresponding formal parameter is used Consider the following calls to create_dept create_dept create_dept MARKETING create_dept MARKETING NEW YORK The first call passes no actual parameters so both default values are used The second call passes one actual parameter so the default value for new_loc is used The third call passes two actual parameters so neither default value is used Usually you can use positional notation to override the default values of formal parameters However you cannot skip a formal parameter by leaving out its actual parameter For example the following call incorrectly associates the actual parameter NEW YORK with the formal parameter new_dname create_dept NEW YORK incorrect You cannot solve the problem by leaving a placeholder for the actual parameter For example the following call is illegal create_dept NEW YORK illegal In such cases you must use named notation as follows create_dept new_loc gt NEW YORK Also you cannot assign a null to an uninitialized formal parameter by leaving out its actual parameter For example given the declaration DECLARE FUNCTION gross_pay emp_id IN NUMBER st_hours IN NUMBER DEFAULT 40 ot_hours IN NUMBER RETURN REAL IS the following function call does not assig
362. er literal and element_type is any PL SQL datatype except BINARY_INTEGER BOOLEAN LON LON NATURAL NATURALN NCHAR NCLOB NVARCHAR2 object types with TABLE or VARRAY attributes PLS_INTEGER POSITIVE POSITIVEN RAW aca Collections and Records 4 5 Defining and Declaring Collections REF CURSOR SIGNTYPE STRING TABLE VARRAY If element_type is a record type every field in the record must be a scalar type or an object type For index by tables you use the syntax TYPE type_name IS TABLE OF element_type NOT NULL INDEX BY BINARY _INTEGER Though not allowed for nested tables or varrays the following element types are allowed for index by tables BINARY_INTEGER BOOLEAN LONG LONG RAW NATURAL NATURALN PLS_INTEGER POSITIVE POSITIVEN SIGNTYPE and STRING That is because nested tables and varrays are intended primarily to be columns of database tables As such they cannot access PL SQL specific types When declared locally they could theoretically use those types but the restriction is preserved for consistency Unlike nested tables which are initially dense index by tables are initially sparse That enables you for example to store reference data in a temporary index by table using a numeric primary key as the index In the example below you declare an index by table of records Each element of the table stores a row from
363. er taken END IF EXCEPTION WHEN NO DATA FOUND THEN never invoked Processing Transactions This section explains how to do transaction processing You learn the basic techniques that safeguard the consistency of your database including how to control whether changes to Oracle data are made permanent or undone The jobs or tasks that Oracle manages are called sessions A user session is started when you run an application program or an Oracle tool and connect to Oracle To allow user sessions to work simultaneously and share computer resources Oracle must control concurrency the accessing of the same data by many users Without adequate concurrency controls there might be a loss of data integrity That is changes to data might be made in the wrong order 5 44 PL SQL User s Guide and Reference Processing Transactions Oracle uses locks to control concurrent access to data A lock gives you temporary ownership of a database resource such as a table or row of data Thus data cannot be changed by other users until you finish with it You need never explicitly lock a resource because default locking mechanisms protect Oracle data and structures However you can request data locks on tables or rows when it is to your advantage to override default locking You can choose from several modes of locking such as row share and exclusive A deadlock can occur when two or more users try to access the sa
364. erations needed to handle an abstract employee For example you need an operation that lets Management change the rank of an employee Object Types 9 3 What Is an Object Type Next you define a set of variables attributes to represent the data and a set of subprograms methods to perform the operations Finally you encapsulate the attributes and methods in an object type The data structure formed by the set of attributes is public visible to client programs However well behaved programs do not manipulate it directly Instead they use the set of methods provided That way the employee data is kept in a proper state Future releases of Oracle will let you define private data structures which can be manipulated only by the methods you provide At run time when the data structure is filled with values you have created an instance of an abstract employee You can create as many instances usually called objects as you need Each object has the name number job title and so on of an actual employee see Figure 9 2 This data is accessed or changed only by the methods associated with it Thus object types let you create objects with well defined attributes and behavior Figure 9 2 Object Type and Objects Instances of That Type Object Type Employee Attributes Methods name calculate_bonus id_number change_dept department change_job_title job_title change_salary salary change_rank rank Object
365. ere below quota DELETE FROM bonus WHERE sales_amt lt quota The following statement returns column sal from deleted rows and stores the column values in the elements of a host array DELETE FROM emp WHERE job CLERK AND sal gt 3000 RETURNING sal INTO clerk_sals FETCH Statement SELECT Statement Language Elements 11 51 EXCEPTION_INIT Pragma EXCEPTION_INIT Pragma Syntax The pragma EXCEPTION_INIT associates an exception name with an Oracle error number That allows you to refer to any internal exception by name and to write a specific handler for it instead of using the OTHERS handler For more information see Using EXCEPTION_INIT on page 6 8 exception_init_pragma PRA EXCEPTO A e DO Keyword and Parameter Description Usage Notes PRAGMA This keyword signifies that the statement is a pragma compiler directive Pragmas are processed at compile time not at run time They do not affect the meaning of a program they simply convey information to the compiler exception_name This identifies a user defined exception previously declared within the current scope error_number This is any valid Oracle error number These are the same error numbers returned by the function SOLCODE You can use EXCEPTION_INIT in the declarative part of any PL SQL block subprogram or package The pragma must appear in the same decl
366. es AS YPE EmpCurTyp IS REF CURSOR RETURN emp ROWTYPE YPE DeptCurTyp IS REF CURSOR RETURN dept ROWTYPE YPE BonusCurTyp IS REF CURSOR RETURN bonus ROWTYPE Ne END cv_types Related Topics CLOSE Statement Cursor Attributes Cursors FETCH Statement OPEN FOR Statement 11 44 PL SQL User s Guide and Reference Cursors Cursors Syntax To execute a multi row query Oracle opens an unnamed work area that stores processing information A cursor lets you name the work area access the information and process the rows individually For more information see Managing Cursors on page 5 9 cursor_declaration Or cursor_parameter_declaration BCO cursor_specification O Era PO cursor_body O RETURN ras AE O cursor_name cursor_name cursor_parameter_declaration expression parameter_name Language Elements 11 45 Cursors rowtype D O ROUTE o o RITE o record_name TYPE l record_type_name Keyword and Parameter Description select_statement This is a query that returns a result set of rows Its syntax is like that of select_into_statement without the INTO clause See SELECT INTO Statement on page 11 139 If the cursor declaration declares parameters each parameter must be used in the query RETURN This keyword introduces the RETURN clause which spec
367. es such as Solaris so libraries Creating an External Procedure To create an external procedure you and your DBA take the following steps 1 Set Up the Environment Your DBA sets up the environment for calling external procedures by adding entries to the files tnsnames ora and listener ora and by starting a Listener process exclusively for external procedures For details see Oracle8 Administrator s Guide 10 2 PL SQL User s Guide and Reference Registering an External Procedure 2 Identify the DLL In this context a DLL is any dynamically loadable operating system file that stores external procedures For safety your DBA controls access to the DLL Using the CREATE LIBRARY statement the DBA creates a schema object called an alias library which represents the DLL Then if you are an authorized user the DBA grants you EXECUTE privileges on the alias library If the DBA grants you CREATE ANY LIBRARY privileges you can create your own alias libraries using the following syntax CREATE LIBRARY library_name IS AS file_path You must specify the full path to the DLL because the linker cannot resolve references to just the DLL name In the following example you create alias library c_utils which represents DLL utils so create library c_utils as DLLs utils so 3 Designate the External Procedure You find or write a new routine then add it to the DLL or simply de
368. es to the actual parameters IN OUT Mode An IN OUT parameter lets you pass initial values to the subprogram being called and return updated values to the caller Inside the subprogram an IN OUT parameter acts like an initialized variable Therefore it can be assigned a value and its value can be assigned to another variable That means you can use an IN OUT formal parameter as if it were a normal variable You can change its value or reference the value in any way as the following example shows PROCEDURE calc_bonus emp_id IN INTEGER bonus IN OUT REAL IS hire_date DATE bonus_missing EXCEPTION BEGIN SELECT sal 0 10 hiredate INTO bonus hire_date FROM emp WHERE empno emp_id IF bonus IS NULL THEN RAISE bonus_missing END IF IF MONTHS BETWEEN SYSDATE hire_date gt 60 THEN bonus bonus 500 END IF 7 14 PL SQL User s Guide and Reference Parameter Default Values EXCEPTION WHEN bonus_missing THEN END calc_bonus The actual parameter that corresponds to an IN OUT formal parameter must be a variable it cannot be a constant or an expression Table 7 1 summarizes all you need to know about the parameter modes Table 7 1 Parameter Modes IN OUT IN OUT the default passes values to a subprogram formal parameter acts like a constant formal parameter cannot be assigne
369. eseceseescecseeceecseessecssesaecsueascneenaes 10 25 Restrictions on External Procedures cccccccesscsssssseessesseeecesceecceseeececseeesecseeesecasesaecauesaecnsenaes 10 25 Language Elements Assignment Statement iii lidia las 11 3 Block vicio ada teddies 11 7 CEOSE Statement imac a E A e E aeni 11 14 Collection Methods coi dd ia 11 16 Collections A E Mate eee a et ae 11 21 Comments iii ai ln eli iaa 11 26 COMMIT Stemi is 11 27 Constants and Variables 22 2 icccc2ccccc0eecsiodtic div edeesdcae aces ldsen need aniria ap eaa h aasa aidas 11 29 Gursor Attribittesi 0 cain Seinen ite oi eee an eee ee i 11 33 Cursor Variables A ia 11 38 CUPS OTS puc iii lib ai a e aaa a de Adi di 11 45 DELETE Statement onda e 11 49 EXCEPTION INEL Praga ocio at brida 11 52 Exceptions neenon eee a eee ae Aer tad Sd A nte cai 11 54 EXIT Statement A ia naa isla a asides laste caia 11 57 E pressions init doiad A LA ODE elses E AE P a N EEE 11 59 External Procedures io a aa ahead seed He ine 11 70 FETCH Statement is 11 76 FutictlOns nenei dida ds 11 79 GOTO Statement ninia di tA E Ea EEEE RE EEE A 11 83 TE Statement i cssei chiseled a a Rode dee a a eia ee a ea 11 85 INSERE Statement a e e ronda abe see Uses ates wh Sates tabs as Tea ENa EEE Sondae oe 11 88 Literal sis ane A idee eet i nee E en en eee 11 91 LOCK TABLE Statement eR es ER A 11 94 LOOP Statements A A eked 11 96 NULT Statements sad 11 102 Object TDS NO SNA be detenet E as 11 103 OP
370. eter Allowed External Default External Property Types Type Allowed Types Allowed Modes INDICATOR SHORT SHORT all scalars I INT IN OUT LONG OUT RETURN LENGTH UNSIGNED SHORT INT CHAR I UNSIGNED INT LONG RAW IN OUT UNSIGNED LONG RAW OUT VARCHAR2 RETURN MAXLEN UNSIGNED SHORT INT CHAR IN OUT UNSIGNED INT LONG RAW OUT UNSIGNED LONG RAW RETURN VARCHAR2 CHARSETID UNSIGNED SHORT UNSIGNED INT CHAR I CHARSETFORM UNSIGNED INT CLOB IN OUT UNSIGNED LONG VARCHAR2 OUT RETURN In the following example we use the PARAMETERS clause to specify properties for the PL SQL formal parameters and function result CREATE FUNCTION parse x IN BINARY_INTEGER Y IN OUT CHAR RETURN CHAR AS EXTERNAL LIBRARY c_utils Hy AME c_parse ANGUAGE C CALLING STANDARD PASCAL PARAMETERS X stores value of x x INDICATOR stores null status of x Y stores value of y External Procedures 10 13 Passing Parameters to an External Procedure y LENGTH stores current length of y y MAXLEN stores maximum length of y RETURN INDICATOR RETURN With this PARAMETERS clause the C prototype becomes char c_parse int x short x_ind char y int y_len int y_maxlen short retind The additional parameters in the C prototype correspond to the INDICATOR LENGTH and MAXLEN parameters in the PARAMETERS
371. eter or a function result Also always assign a value to IN OUT and OUT parameters and to function results Otherwise your external procedure will not return successfully If you include the WITH CONTEXT and PARAMETERS clauses you must specify the parameter CONTEXT which shows the position of the context pointer in the parameter list If you omit the PARAMETERS clause the context pointer is the first parameter passed to the external procedure CJ If you include the PARAMETERS clause and the external routine is a function you must specify the parameter RETURN not RETURN property in the last position For every formal parameter there must be a corresponding parameter in the PARAMETERS clause Also make sure that the datatypes of parameters in the PARAMETERS clause are compatible with those in the C prototype because no implicit conversions are done With a parameter of type RAW or LONG RAW you must use the property LENGTH Also if that parameter is IN OUT or OUT and null you must set the length of the corresponding C parameter to zero Restrictions on External Procedures Currently the following restrictions apply to external procedures a This feature is available only on platforms that support DLLs a Only routines callable from C code not C code are supported a You cannot pass PL SQL cursor variables records collections or instances of an object type to an externa
372. etrieve the number and title of a specific course offered by the History Department DECLARE my_course_no BER 4 my_title VARCHARZ2 35 BEGI SELECT course_no title INTO my_course_no my_title FROM THE SELECT courses FROM department WHERE name History WHERE course_no 3105 In the final example you delete all 5 credit courses offered by the English Department BEGI DELETE THE SELECT courses FROM department WHERE name English WHERE credits 5 Some Varray Examples Remember within SQL you cannot manipulate the individual elements of a varray You must use PL SQL procedural statements In the following example stored procedure add_project inserts a new project into a department s project list at a given position CREATE PROCEDURE add_project dept_no IN NUMBER new_project IN Project position IN NUMBER AS Collections and Records 4 19 Manipulating Collections my_projects ProjectList Re ELEC WH EX trieve project list into local varray T projects INTO my_projects FROM department ERE dept_no dept_id FOR UPDATE OF projects Extend varray to make room for new project my_projects EXTEND Move varray elements forward FOR i IN REVERSE position my_projects LAST 1 LOOP my_projects i 1 my_projects i
373. ever changes to a package specification require Oracle to recompile every stored subprogram that references the package 8 18 PL SQL User s Guide and Reference 9 Object Types It next will be right To describe each particular batch Distinguishing those that have feathers and bite From those that have whiskers and scratch Lewis Carroll Object oriented programming is rapidly gaining acceptance because it can reduce the cost and time required to build complex applications In PL SQL object oriented programming is based on object types They provide abstract templates for real world objects and so are an ideal modeling tool They also provide black box encapsulation like an integrated component that can be plugged into various electronic devices To plug an object type into your programs you need to know only what it does not how it works Major Topics The Role of Abstraction What Is an Object Type Why Use Object Types Structure of an Object Type Components of an Object Type Defining Object Types Declaring and Initializing Objects Accessing Attributes Calling Constructors and Methods Sharing Objects Manipulating Objects Object Types 9 1 The Role of Abstraction The Role of Abstraction An abstraction is a high level description or model of a real world entity Abstractions keep our daily lives manageable They help us reason about an object event or relationship by suppressing irrelevant det
374. example if you mark five savepoints then roll back to the third only the fourth and fifth are erased A simple rollback or commit erases all savepoints If you mark a savepoint within a recursive subprogram new instances of the SAVEPOINT statement are executed at each level in the recursive descent However you can only rollback to the most recently marked savepoint Savepoint names are undeclared identifiers and can be reused within a transaction This moves the savepoint from its old position to the current point in the transaction Thus a rollback to the savepoint affects only the current part of your transaction An example follows BEGIN SAVEPOINT my_point 5 48 PL SQL User s Guide and Reference Processing Transactions UPDATE emp SET WHERE empno emp_id SAVEPOINT my_point move my_point to current point INSERT INTO emp VALUES emp_id EXCEPTION WHEN OTHERS THEN ROLLBACK TO my_point END The number of active savepoints per session is unlimited An active savepoint is one marked since the last commit or rollback Implicit Rollbacks Before executing an INSERT UPDATE or DELETE statement Oracle marks an implicit savepoint unavailable to you If the statement fails Oracle rolls back to the savepoint Normally just the failed SQL statement is rolled back not the whole transaction However if the statement raises an unha
375. f 38 decimal digits PLS_INTEGER You use the PLS_INTEGER datatype to store signed integers Its magnitude range is 2147483647 2147483647 PLS_INTEGER values require less storage than NUMBER values Also PLS_INTEGER operations use machine arithmetic so they are faster than NUMBER and BINARY_INTEGER operations which use library arithmetic For better performance use PLS_INTEGER for all calculations that fall within its magnitude range Fundamentals 2 13 Datatypes Although PLS_INTEGER and BINARY_INTEGER have the same magnitude range they are not fully compatible When a PLS_INTEGER calculation overflows an exception is raised However when a BINARY_INTEGER calculation overflows no exception is raised if the result is assigned to a NUMBER variable Because of this small semantic difference you might want to continue using BINARY_INTEGER in old applications for compatibility In new applications always use PLS_INTEGER for better performance Character Types Character types allow you to store alphanumeric data represent words and text and manipulate character strings CHAR You use the CHAR datatype to store fixed length character data How the data is represented internally depends on the database character set which might be 7 bit ASCII or EBCDIC Code Page 500 for example The CHAR datatype take
376. families which store number character Boolean and date time data respectively 2 10 PL SQL User s Guide and Reference Datatypes Number Types Figure 2 1 Built in Datatypes PL SQL Datatypes Scalar Types BINARY_INTEGER DEC DECIMAL DOUBLE PRECISION FLOAT INT INTEGER NATURAL NATURALN NUMBER NUMERIC PLS_INTEGER POSITIVE POSITIVEN REAL SIGNTYPE SMALLINT CHAR CHARACTER LONG LONG RAW NCHAR NVARCHAR2 RAW ROWID STRING VARCHAR VARCHAR2 BOOLEAN DATE Composite Types RECORD TABLE VARRAY Reference Types REF CURSOR REF object_type LOB Types BFILE BLOB CLOB NCLOB This section discusses the scalar types and LOB types The composite types are discussed in Chapter 4 The reference types are discussed in Chapter 5 and Chapter 9 Number types allow you to store numeric data integers real numbers and floating point numbers represent quantities and do calculations BINARY_INTEGER You use the BINARY_INT range is 2147483647 2147483647 Like PLS_INTI values require less storage than NUMB EG ER datatype to store signed integers Its magnitude EGER values BINARY_INTEGER ER values However most BINARY_INTEGER operations are slower than PLS_INTEGER operations See PLS_INTEGER on page 2 13 Fundamentals 2 11 Datatypes BINARY_INTEGER Subtypes A base type is the datatype from which a s
377. fferent scope So if you want to save an attribute value for later use assign it to a Boolean variable immediately If a SELECT INTO statement fails to return a row PL SQL raises the predefined exception NO_DATA_ FOUND whether you check SQLSNOTFOUND on the next line or not However a SELECT INTO statement that calls a SQL group function never raises NO_DATA_FOUND That is because group functions such as AVG and SUM always return a value or a null In such cases SQLSNOTFOUND yields FALSE In the following example sNOTFOUND is used to insert a row if an update affects no rows UPDATE emp SET sal sal 1 05 WHERE empno my_empno IF SOLSNOTFOUND THEN INSERT INTO emp VALUES my_empno my_ename END IF In the next example you use SROWCOUNT to raise an exception if more than 100 rows are deleted DELETE FROM parts WHERE status OBSOLETE IF SQLSROWCOUNT gt 100 THEN more than 100 rows were deleted RAISE large_deletion END IF Cursors Cursor Attributes Language Elements 11 145 SQLCODE Function SQLCODE Function The function SQLCODE returns the number code associated with the most recently raised exception SQLCODE is meaningful only in an exception handler Outside a handler SOLCODE always returns zero For internal exceptions SOLCODE returns the number of the associated Oracle
378. fic Packages Packages 8 1 What Is a Package What Is a Package A package is a schema object that groups logically related PL SQL types items and subprograms Packages usually have two parts a specification and a body although sometimes the body is unnecessary The specification is the interface to your applications it declares the types variables constants exceptions cursors and subprograms available for use The body fully defines cursors and subprograms and so implements the specification Unlike subprograms packages cannot be called parameterized or nested Still the format of a package is similar to that of a subprogram CREATE PACKAGE name AS specification visible part public type and item declarations subprogram specifications END name CREATE PACKAGE BODY name AS body hidden part private type and item declarations subprogram bodies BEGI initialization statements END name The specification holds public declarations which are visible to your application The body holds implementation details and private declarations which are hidden from your application As Figure 8 1 shows you can think of the specification as an operational interface and of the body as a black box Figure 8 1 Package Interface Application Package Database gt specification body 8 2 PL SQL User s Guide and Reference What Is
379. for nulls LIKE Tests whether a character string matches a specified pattern which can include wildcards Set Operators Set operators combine the results of two queries into one result INTERSECT returns all distinct rows selected by both queries MINUS returns all distinct rows selected by the first query but not by the second UNION returns all distinct rows selected by either query UNION ALL returns all rows selected by either query including all duplicates 5 6 PL SQL User s Guide and Reference Using DDL and Dynamic SQL Row Operators Row operators return or reference particular rows ALL retains duplicate rows in the result of a query or in an aggregate expression DISTINCT eliminates duplicate rows from the result of a query or from an aggregate expression PRIOR refers to the parent row of the current row returned by a tree structured query You must use this operator in the CONNECT BY clause of such a query to define the parent child relationship SQL92 Conformance In late 1992 the American National Standards Institute ANSI and the International Organization for Standardization ISO adopted the current SQL standard known informally as SQL92 which greatly extends SQL89 the previous SOL standard SQL92 specifies a conforming SQL language and to allow implementation in stages defines three language levels a Full SQL a Intermediate SQL a subset of Full SQL a Transitional SQL a subset
380. for which you must have UPDATE privileges For the syntax of table_reference see DELETE Statement on page 11 49 Language Elements 11 151 UPDATE Statement THE The operand of THE is a subquery that returns a single column value to the UPDAT statement The column value must be a nested table Operator THE informs Oracle that the value is a nested table not a scalar value GI subquery1 This is a select statement that provides a value or set of values to the UPDATE statement Its syntax is like that of select_into_statement without the INTO clause See SELECT INTO Statement on page 11 139 alias This is another usually short name for the referenced table or view and is typically used in the WHERE clause column_name This is the name of the column or one of the columns to be updated It must be the name of a column in the referenced table or view A column name cannot be repeated in the column_name list Column names need not appear in the UPDAT statement in the same order that they appear in the table or view GI sql_expression This is any valid SQL expression For more information see Oracle8 SQL Reference SET column_name sql_ expression This clause assigns the value of sq1_expression to the column identified by column_name If sql_expression contains references to columns in the table being updated the references are resolved in the context of the current row Th
381. g block 3 18 PL SQL User s Guide and Reference Sequential Control GOTO and NULL Statements NULL Statement The NULL statement explicitly specifies inaction it does nothing other than pass control to the next statement It can however improve readability In a construct allowing alternative actions the NULL statement serves as a placeholder It tells readers that the associated alternative has not been overlooked but that indeed no action is necessary In the following example the NULL statement shows that no action is taken for unnamed exceptions EXCEPTION WHEN ZERO_DIVIDE THEN ROLLBACK WHEN VALUE_ERROR THEN INSERT INTO errors VALUES COMMIT WHEN OTHERS THEN NULL END Each clause in an IF statement must contain at least one executable statement The NULL statement meets this requirement So you can use the NULL statement in clauses that correspond to circumstances in which no action is taken In the following example the NULL statement emphasizes that only top rated employees receive bonuses IF rating gt 90 THEN compute_bonus emp_id ELSE ULL END IF Also the NULL statement is a handy way to create stubs when designing applications from the top down A stub is dummy subprogram that allows you to defer the definition of a procedure or function until you test and debug the main program In the followin
382. g declaration of maxi is illegal maxi INTEGER 2 mini illegal mini INTEGER 15 However PL SQL does allow the forward declaration of subprograms For more information see Forward Declarations on page 7 8 Some languages allow you to declare a list of variables that have the same datatype PL SQL does not allow this For example the following declaration is illegal i j k SMALLINT illegal The legal version follows i SMALLINT j SMALLINT k SMALLINT Naming Conventions The same naming conventions apply to all PL SQL program items and units including constants variables cursors cursor variables exceptions procedures functions and packages Names can be simple qualified remote or both qualified and remote For example you might use the procedure name raise_salaryin any of the following ways raise_salary simple emp_actions raise_salary qualified raise_salary newyork remote emp_actions raise_salary newyork qualified and remote In the first case you simply use the procedure name In the second case you must qualify the name using dot notation because the procedure is stored in a package called emp_actions In the third case using the remote access indicator you reference the database link newyork because the procedure is stored in a remote database In the fourth case you qualify the procedure name and reference a
383. g example the NULL statement meets the requirement that at least one statement must appear in the executable part of a subprogram PROCEDURE debit_account acct_id INTEGER amount REAL IS BEGI ULL ID debit_account E Control Structures 3 19 Sequential Control GOTO and NULL Statements 3 20 PL SQL User s Guide and Reference 4 Collections and Records Knowledge is that area of ignorance that we arrange and classify Ambrose Bierce Increasingly programmers are using collection types such as arrays bags lists nested tables sets and trees in traditional database applications To meet the growing demand PL SQL provides the datatypes TABLE and VARRAY which allow you to declare nested tables and variable size arrays In this chapter you learn how those types let you reference and manipulate collections of data as whole objects You also learn how the datatype RECORD lets you treat related but dissimilar data as a logical unit Major Topics What Is a Collection Initializing and Referencing Collections Assigning and Comparing Collections Manipulating Collections Using Collection Methods Avoiding Collection Exceptions What Is a Record Defining and Declaring Records Initializing and Referencing Records Assigning and Comparing Records Manipulating Records Collections and Records 4 1 What Is a Collection What Is a Collection Understanding A collecti
384. g method by value or by reference You do not pass parameters to an external procedure directly Instead you pass them to the PL SQL subprogram that registered the external procedure So you must specify PL SQL datatypes for the parameters For guidance see Table 10 1 on page 10 9 Each PL SQL datatype maps to a default external datatype In turn each external datatype maps to a C datatype To avoid errors when declaring C prototype parameters refer to Table 10 2 on page 10 11 which shows the C datatype to specify for a given external datatype and PL SQL parameter mode You can also use the PARAMETERS clause to pass additional information about PL SQL formal parameters and function results to an external procedure You do that by specifying the following properties INDICATOR LENGTH MAXLEN CHARSETID CHARSETFORM CONTEXT This parameter cannot be repeated If you include the WITH CONTEXT and PARAMETERS clauses you must specify this parameter which shows the position of the context pointer in the parameter list If you omit the PARAMETERS clause the context pointer is the first parameter passed to the external procedure INDICATOR This property lets you associate a null not null indicator with a formal parameter If the PL SQL subprogram is a function you can also associate an indicator with the return value LENGTH MAXLEN These properties let you specify parameters that st
385. g statement is illegal INSERT INTO dept VALUES dept_info illegal Also you cannot assign a list of values to a record using an assignment statement Therefore the following syntax is illegal record_name valuel value2 value3 illegal The example below shows that you can assign one nested record to another if they have the same datatype Such assignments are allowed even if the enclosing records have different datatypes DECLARE YPE TimeRec IS RECORD minutes SMALLINT hours SMALLINT YPE MeetingRec IS RECORD day DATE 4 34 PL SQL User s Guide and Reference Manipulating Records time TimeRec nested record room_no INTEGER 4 TYPE PartyRec IS RECORD day DATE time TimeRec nested record place VARCHAR2 25 seminar Meet ingRec party PartyRec BEGIN party time seminar time Comparing Records Records cannot be tested for nullity equality or inequality For instance the following IF conditions are illegal BEGIN IF emp info IS NULL THEN illegal IF dept2_info gt deptl_info THEN illegal Manipulating Records The datatype RECORD lets you collect information about the attributes of something The information is easy to manipulate because you can refer to the collection as a whole In the following example you collect accounting figures from database tables assets and
386. g subscripts fields in a record are accessed by name To reference an individual field you use dot notation and the following syntax record_name field_name For example you reference field hire_date in record emp_infoas follows emp_info hire_date When calling a function that returns a user defined record you use the following syntax to reference fields in the record function_name parameters field_nam For example the following call to function nth_highest_sal references the field salary in record emp_ info DECLARE YPE EmpRec IS RECORD emp_id NUMBER 4 job_title CHAR 14 Collections and Records 4 31 Initializing and Referencing Records salary REAL 7 2 middle_sal REAL FUNCTION nth_highest_sal n INTEGER RETURN EmpRec IS emp_info EmpRec BEGI RETURN emp_info return record END BEGIN middle_sal nth_highest_sal 10 salary call function When calling a parameterless function you use the following syntax function_name field_nam note empty parameter list To reference nested fields in a record returned by a function you use extended dot notation For instance the following call to function item references the nested field minutes in record item_info DECLARE YPE TimeRec IS RECORD minutes SMALLINT hours SMALLINT YPE Agendaltem IS RECORD priority INTEGER subject VARCHAR2 100
387. given the assignments numberl 75 number2 70 GI the following expression yields TRU numberl gt number2 Character Expressions Likewise you can compare character values for equality or inequality Comparisons are based on the collating sequence used for the database character set A collating sequence is an internal ordering of the character set in which a range of numeric codes represents the individual characters One character value is greater than another if its internal numeric value is larger For example given the assignments stringl Kathy string2 Kathleen e the following expression yields TRU stringl gt string2 However there are semantic differences between the CHAR and VARCHAR2 base types that come into play when you compare character values For more information refer to Appendix C Date Expressions You can also compare dates Comparisons are chronological that is one date is greater than another if it is more recent For example given the assignments datel 01 JAN 91 date2 31 DEC 90 GI the following expression yields TRU datel gt date2 Fundamentals 2 47 Expressions and Comparisons Guidelines In general do not compare real numbers for exact equality or inequality Real numbers are stored as approximate values So for example the following IF condition might not yield TRUE count 1 IF count 1 0 THEN
388. given the declarations namel CHAR 5 BELLO name2 CHAR 10 BELLO note trailing blanks the following IF condition is true IF namel name2 THEN If either value in a comparison has datatype VARCHAR2 non blank padding semantics are used That is when comparing character values of unequal length PL SQL makes no adjustments and uses the exact lengths For example given the declarations namel VARCHAR2 10 DOW name2 VARCHAR2 10 DOW note trailing blanks the following IF condition is false IF namel name2 THEN If one value in a comparison has datatype VARCHAR2 and the other value has datatype CHAR non blank padding semantics are used But remember when you assign a character value to a CHAR variable if the value is shorter than the declared length of the variable PL SQL blank pads the value to the declared length So given the declarations namel VARCHAR2 10 STAUB name2 CHAR 10 STAUB PL SQL blank pads value the following IF condition is false because the value of name2 includes five trailing blanks IF namel name2 THEN All string literals have datatype CHAR So if both values in a comparison are literals blank padding semantics are used If one value is a literal blank padding semantics are used only if the other value has datatype CHAR CHAR versus VARCHAR2 Semantics C 3 Inserting Character Values
389. gle SQL statements to break deadlocks Oracle signals an error to one of the participating transactions and rolls back the current statement in that transaction Interaction with Oracle 5 47 Processing Transactions Before executing a SQL statement Oracle must parse it that is examine it to make sure it follows syntax rules and refers to valid schema objects Errors detected while executing a SQL statement cause a rollback but errors detected while parsing the statement do not Using SAVEPOINT SAVEPOINT names and marks the current point in the processing of a transaction Used with the ROLLBACK TO statement savepoints let you undo parts of a transaction instead of the whole transaction In the example below you mark a savepoint before doing an insert If the INSERT statement tries to store a duplicate value in the empno column the predefined exception DUP_VAL_ON_INDEX is raised In that case you roll back to the savepoint undoing just the insert DECLARE emp_id emp empno TYPE BEGI UPDATE emp SET WHERE empno emp_id DELETE FROM emp WHERE SAVEPOINT do_insert INSERT INTO emp VALUES emp_id EXCEPTION WHEN DUP_VAL_ON_INDEX THEN ROLLBACK TO do_insert END When you roll back to a savepoint any savepoints marked after that savepoint are erased However the savepoint to which you roll back is not erased For
390. gram declarations in which the subprogram name matches the name of the called subprogram To resolve a call among possibly like named subprograms at the same level of scope the compiler must find an exact match between the actual and formal parameters That is they must match in number order and datatype unless some formal parameters were assigned default values If no match is found or if multiple matches are found the compiler generates a syntax error In the following example you call the enclosing procedure swap from within the function valid However the compiler generates an error because neither declaration of swap within the current scope matches the procedure call PROCEDURE swap dl DATE d2 DATE IS datel DATE date2 DATE FUNCTION valid d DATE RETURN BOOLEAN IS PROCEDURE swap nl INTEGER n2 INTEGER IS BEGIN END swap PROCEDURE swap nl REAL n2 REAL IS BEGIN END swap BEGIN swap datel date2 END valid BEGI Subprograms 7 21 Overloading Figure 7 1 How the PL SQL Compiler Resolves Calls encounter subprogram call compare name of called subprogram with names of any go to enclosing scope subprograms declared in current scope match es found enclosing scope compare actual parameter list in subprogram call with formal parameter lis
391. guage Elements 11 21 Collections element_type cursor_name T AQ O REF A PP object_type_name record_name TYPE record_type_name y J1 scalar_datatype_name abe ae OE XN Keyword and Parameter Description type_name This identifies a user defined type specifier which is used in subsequent declarations of collections element_type This is any PL SQL datatype except BOOLEAN NCHAR NCLOB NVARCHAR2 REF CURSOR TABLE and VARRAY or is any object type except those with TABLE or VARRAY attributes If element_type isa record type every field in the record must be a scalar type or an object type INDEX BY BINARY_INTEGER This optional clause lets you define Version 2 PL SQL tables which are called index by tables in Version 8 size_limit This is a positive integer literal that specifies the maximum size of a varray which is the maximum number of elements the varray can contain 11 22 PL SQL User s Guide and Reference Collections Usage Notes Every element reference includes the collection name and a subscript enclosed in parentheses the subscript determines which element is processed Except for index by tables collection subscripts have a fixed lower bound of 1 Nested tables can be sparse have non consecutive subscripts but varrays are always dense have consecutive subscripts Unlike nested tables varrays retain their ordering a
392. guages This makes the strengths and capabilities of those languages available to you An external procedure is a third generation language routine stored in a dynamic link library DLL registered with PL SQL and called by you to do special purpose processing At run time PL SQL loads the library dynamically then calls the routine as if it were a PL SQL subprogram Typically external procedures are used to interface with embedded systems solve scientific and engineering problems analyze data or control real time devices and processes For more information see Chapter 10 Object Types Collections Object oriented programming is based on the concept of interacting objects In PL SQL objects are instances of object types When you define an object type using the CREATE TYPE statement in SOL Plus for example you create an abstract template for some real world object An object type encapsulates a data structure along with the functions and procedures needed to manipulate the data At run time when the data structure is filled with values you have created an object You can create as many objects as you need Each object stores different real world values Object types which map directly into classes defined in object oriented languages such as C reduce complexity by breaking down a large system into logical entities This allows you to create software components that are modular maintainable and reusable
393. having attributes and behaviors For example a baby has the attributes gender age and weight and the behaviors eat drink and sleep Object types let you maintain this perspective when you sit down to write an application When you define an object type using the CREATE TYPE statement you create an abstract template for some real world object The template specifies only those attributes and behaviors the object will need in the application environment For example an employee has many attributes but usually only a few are needed to fill the requirements of an application see Figure 9 1 Figure 9 1 Form Follows Function Payroll Application name id_number ss_number Employee Attributes name date_hired address status phone_number department date_born job_title sex salary marital_status commission education_level rank military_service work_history hobbies office_location id_number office_size ss_number benefits choices user_id dependents phone_extension beneficiaries salary commission benefits_choices dependents Space Planning Application id_number job_title department office_location office_size Suppose you must write a program to allocate employee bonuses Not all employee attributes are needed to solve this problem So you design an abstract employee who has the following problem specific attributes name id_number department job title salary and rank Then you identify the op
394. he following line computes the area of a circle using pi which is the ratio between the circumference and diameter area pi radius 2 Fundamentals 2 9 Datatypes You can use multi line comment delimiters to comment out whole sections of code as the following example shows LOOP FETCH cl INTO emp_rec EXIT WHEN c1SNOTFOUND END LOOP Restrictions You cannot nest comments Also you cannot use single line comments in a PL SQL block that will be processed dynamically by an Oracle Precompiler program because end of line characters are ignored As a result single line comments extend to the end of the block not just to the end of a line So use multi line comments instead Datatypes Every constant and variable has a datatype which specifies a storage format constraints and valid range of values PL SQL provides a variety of predefined datatypes A scalar type has no internal components A composite type has internal components that can be manipulated individually A reference type holds values called pointers that designate other program items A LOB type holds values called locators that specify the location of large objects graphic images for example stored out of line Figure 2 1 shows the predefined datatypes available for your use An additional scalar type MLSLABEL is available with Trusted Oracle a specially secured version of Oracle The scalar types fall into four
395. he procedure using named notation debit_account amount gt 500 acct_id gt 10261 Related Topics Collections Functions Packages Records Language Elements 11 125 RAISE Statement RAISE Statement The RAISE statement stops normal execution of a PL SQL block or subprogram and transfers control to the appropriate exception handler Normally predefined exceptions are raised implicitly by the runtime system However RAISE statements can also raise predefined exceptions User defined exceptions must be raised explicitly by RAISE statements For more information see User Defined Exceptions on page 6 6 Syntax raise_statement RAISE G Keyword and Parameter Description exception_name This identifies a predefined or user defined exception For a list of the predefined exceptions see Predefined Exceptions on page 6 4 Usage Notes PL SQL blocks and subprograms should RAISE an exception only when an error makes it impractical or impossible to continue processing You can code a RAISE statement for a given exception anywhere within the scope of that exception When an exception is raised if PL SQL cannot find a handler for it in the current block the exception propagates That is the exception reproduces itself in successive enclosing blocks until a handler is found or there are no more blocks to search In the latter case PL SQL returns an unhandled exception error to the host e
396. he properties LENGTH and MAXLEN you can specify parameters that store the current length and maximum length of a formal parameter Note With parameters of type RAW or LONG RAW you must use the property LENGTH 10 14 PL SQL User s Guide and Reference Passing Parameters to an External Procedure For IN parameters LENGTH is passed by value unless you specify BY REF and is read only even if you specify BY REF For OUT IN OUT and RETURN parameters LENGTH is passed by reference MAXLEN does not apply to IN parameters For OUT IN OUT and RETURN parameters MAXLEN is passed by reference but is read only Using CHARSETID and CHARSETFORM Oracle provides national language support which lets you process single byte and multi byte character data and convert between character sets It also lets your applications run in different language environments The properties CHARSETID and CHARSETFORM identify the nondefault character set from which the character data being passed was formed With CHAR CLOB and VARCHAR2 parameters you can use CHARSETID and CHARSETFORM to pass the character set ID and form to the external procedure For IN parameters CHARSETID and CHARSETFORM are passed by value unless you specify BY REF and are read only even if you specify BY REF For OUT IN OUT and RETURN parameters CHARSETID and CHARSETFORM are passed by reference but are read only
397. hows IF trans_type CR THEN UPDATE accounts SET balance balance credit WHERE ELSE IF new_balance gt minimum balance THEN UPDATE accounts SET balance balanc debit WHERE ELSE RAISE insufficient funds END IF END IF IF THEN ELSIF TF statements can Sometimes you want to select an action from several mutually exclusive alternatives The third form of IF statement uses the keyword 1 to introduce additional conditions as follows IF conditionl THEN sequence_of_statements1 ELSIF condition2 THEN sequence_of_statements2 ELSE sequence_of_statements3 END IF ELSIF not ELSEIF If the first condition yields FALSE or NULL the ELSIF clause tests another condition An IF statement can have any number of ELSIF clauses the final ELSE clause is optional Conditions are evaluated one by one from top to bottom If any condition yields TRUE its associated sequence of statements is executed and control passes to the next statement If all conditions yield FALSE or NULL the sequence in the ELSE clause is executed Consider the following example BEGIN IF sales gt 50000 THEN bonus 1500 ELSIF sales gt 35000 THEN bonus 500 ELSE bonus 100 END IF INSERT INTO payroll VALUES emp_id bonus END 3 4 PL
398. ia 5 7 Using DDL and Dynamic SOL voii a 5 7 Efficiency versus Flexibility cccccccecscsseesssesneeseseseeesesescecesesesesnsnsnsseseseeseseseecesenesssnananenees 5 7 Some Limtati s nsr ei enuon iodo bee t e a a beh las oa Lal acia io aE dildo 5 8 Overcoming the Limitations ccccccccecesceseesssesneeseseseeseseseececesesssesnasneseseseseseseecenesesssnaanenees 5 8 Managing Cursors esis sissies iia cial eiaeia ica 5 9 Explicit CUT aiii oi A tees elon E S 5 9 Innplicit Cursors iaa iia 5 14 Packaging CUIDA dda 5 15 Using Cursor FOR Loops ooooococonoccconicconinnonorecinnccnnaranacnnnoronocnnnorononnnnoranarncnnnnnanecn narra rarannn nan arannonanares 5 16 PESA sien eels Min aa aae eee Meat aE Eea 5 17 Using ALASeS cscsiettadarts iman ata d So Kan Eea aaa EARD SE e e iiare nia 5 17 Passing Parameters isitepete seie ae oae iteiee teas eiae anaa ani T Eaa ORADE EAE oan AE EE AARE EES 5 18 Using Cursor Variables A r a T EE T 5 18 What Are Cursor Variables 3 ccacssctesiascuissiescestesncevcs ses adabassurebsdbaninsabussevedgvendsssetendebiioegsnens 5 19 Why Use Cursor Variables cccccccccccscscssesesesssnesesescenesescecenesesesesnsenssesescesescsescansnesescsnanensaeses 5 19 Defining REF CURSOR Type c ccccccscscescscssesesssssnsesesesnesssescececesesssnananeseseseeussesescecenesssssananens 5 20 Declaring Cursor Variables momi aea a e aE E a ea REESE 5 20 Controlling Cursor Variables voii aras 5 22 1NA t o CA ETE E
399. ia E E 2 10 Number Ps A A A E A A 2 11 Character Ty pesao alii ease EOS 2 14 NES Character Types irnar ea eaea EEE A daa TEKE ad EE AE EEE R 2 17 LOB Types aia alicia os 2 19 Other Types e o A aida 2 21 Uset Defined Subtypes coccion dias 2 22 Defining Subtypes caia idas 2 23 Using SUD Pesca A rn ii rod aii pd pois 2 24 Datatype Conversion sin n aa naie RaRa beste sect sive aa e eSa ca sub A EELSE EEDEN Eaa PA vies Aea 2 25 Explicit CONVERSION mensen ieat ta al PENERE AT A A RE 2 25 Implicit Conyv rsioN airett i eein area e e E EEEa AAE E EE ER Enea AA REEE 2 26 Implicit versus Explicit Conversion coococinonononnnnenenencnnnnnnrnaneraronnnnnnnnnrnnnrnnrarananannnrnrorannn nn nanananos 2 27 DATE Valles aunado wits lada deoiaatade 2 27 RAW anid LONG RAW Values encina naci ii ic 2 28 NES Vall cita A A td 2 28 Declarations AAA A A 2 28 Using DEFAU Doa A AA AA A ad 2 29 Usine NOTNUE Leccion Star id IE IEA he AI e IA 2 30 PE A T NS 2 30 Using ROWIYPE cocinan aaa 2 31 RES EPLCHL ONS sus A A Ao aia ii 2 34 NE AN AAA A tases et a aa eta EAE E Ea a Eae i a ieas TE 2 34 DY TION YING E A E ET 2 35 COPING aa il iia 2 35 Case SensSitiVitys sneer cute E EEEE iak Esia TSERE SIER E S EEEE EEEE E S Tat RET Seat 2 35 Name Resoltrtiontsss si lt 3h 0e e a OR on Oe 2 35 Scope and Visibility isis cassie nek esi dea ei Roe eit Se Sade hs 2 37 Assignments nsan n a dado 2 40 Boolean Valles tx E ES SS etn a RGR ea a aE 2 40 Database Values ii Shes ages eh G
400. iable The query can reference host variables and PL SQL variables parameters and functions but cannot be FOR UPDATE In the example below you open the cursor variable emp_cv Notice that you can apply cursor attributes sFOUND SNOTFOUND ISOPEN and SROWCOUNT to a cursor variable IF NOT emp_cv ISOPEN THEN Open cursor variable OPEN emp_cv FOR SELECT FROM emp END IF 5 22 PL SQL User s Guide and Reference Using Cursor Variables Other OPEN FOR statements can open the same cursor variable for different queries You need not close a cursor variable before reopening it Recall that consecutive OPENS of a static cursor raise the predefined exception CURSOR_ALREADY_OPEN When you reopen a cursor variable for a different query the previous query is lost In a Stored Procedure Typically you open a cursor variable by passing it to a stored procedure that declares a cursor variable as one of its formal parameters For example the following packaged procedure opens the cursor variable emp_cv CREATE PACKAGE emp_data AS TYPE EmpCurTyp IS REF CURSOR RETURN empSROWTYPE PROCEDURE open_emp cv emp cv IN OUT EmpCurTyp D emp_data E Z CREATE PACKAGE BODY emp data AS PROCEDURE open emp cv emp cv IN OUT EmpCurTyp IS BEGI OPEN emp_cv FOR SELECT FROM emp D open emp Cv
401. ibble 2 28 NES National Language Support 2 17 NES datatype 2 17 NLS_CHARSET_ID function 2 28 NLS_CHARSET_NAME function 2 28 NO_DATA_FOUND exception 6 5 non blank padding semantics C 3 NOT logical operator treatment of nulls 2 49 NOT NULL constraint effect on TYPE declaration 2 31 effect on performance 5 58 restriction 5 10 7 3 using in collection declaration 4 7 using in field declaration 4 31 using in variable declaration 2 30 NOT_LOGGED_ON exception 6 5 notation mixed 7 12 positional versus named 7 12 NOTFOUND cursor attribute 5 39 NOWAIT parameter 5 51 NVARCHAR2 datatype 2 19 NVL function treatment of nulls 2 50 null handling 2 48 NULL statement 3 19 syntax 11 102 using in a procedure 7 4 nullity 2 45 NUMBER datatype 2 12 numeric literal 2 7 NUMERIC subtype 2 13 O object 9 4 declaring 9 23 initializing 9 24 manipulating 9 31 sharing 9 28 object attribute 9 3 9 7 accessing 9 25 allowed datatypes 9 7 maximum number 9 7 object constructor calling 9 26 passing parameters to 9 27 object method 9 3 9 8 calling 9 27 object table 9 31 object type 9 1 9 3 advantages 9 5 defining 9 14 examples 9 14 structure 9 5 syntax 11 103 object oriented programming 9 1 OPEN statement 5 11 syntax 11 111 OPEN FOR statement 5 22 syntax 11 113 operator comparison 2 44 concatenation 2 46 DEREF 9 34 precedence 2 42 Index 9 REF 9 33 relational 2 45 VA
402. ibutes along with the operations methods needed to manipulate the data The body fully defines the methods and so implements the specification Figure 9 3 Object Type Structure specification attribute declarations is public interface method specifications body method bodies private implementation All the information a client program needs to use the methods is in the specification Think of the specification as an operational interface and of the body as a black box You can debug enhance or replace the body without changing the specification and without affecting client programs Object Types 9 5 Structure of an Object Type In an object type specification all attributes must be declared before any methods Only subprograms have an underlying implementation So if an object type specification declares only attributes the object type body is unnecessary You cannot declare attributes in the body All declarations in the object type specification are public visible outside the object type However the object type body can contain private declarations which define methods necessary for the internal workings of the object type The scope of private declarations is local to the object type body To understand the structure better study the example below in which an object type for complex numbers is defined For now it is enough to know that a complex number has two parts a real part and an imaginary part an
403. ic FOR loops iterate over a specified range of integers Cursor FOR loops which iterate over the result set of a cursor are discussed later The range is part of an iteration scheme which is enclosed by the keywords FOR and LOOP The range is evaluated when the FOR loop is first entered and is never re evaluated The sequence of statements in the loop is executed once for each integer in the range defined by lower_bound upper_bound After each iteration the loop index is incremented index_name This is an undeclared identifier that names the loop index sometimes called a loop counter Its scope is the loop itself Therefore you cannot reference the index outside the loop 11 98 PL SQL User s Guide and Reference LOOP Statements The implicit declaration of index_name overrides any other declaration outside the loop So another variable with the same name cannot be referenced inside the loop unless a label is used as follows lt lt main gt gt DECLARE num NUMBER BEGIN FOR num IN 1 10 LOOP IF main num gt 5 THEN refers to the variable num ae not to the loop index END IF END LOOP END main Inside a loop its index is treated like a constant The index can appear in expressions but cannot be assigned a value lower_bound upper_bound These are expressions that must yield integer values The expressions are evaluated only when the loop is first entered By
404. ications For example they are used in systems programming to prioritize interrupts and to manage recursion The simplest implementation of a stack uses an integer array Integers are stored in array elements with one end of the array representing the top of the stack PL SQL provides the datatype VARRAY which allows you to declare variable size arrays varrays for short To declare a varray attribute we must first define its type However we cannot define types in an object type specification So we define a stand alone varray type specifying its maximum size as follows CREATE TYPE IntArray AS VARRAY 25 OF INTEGER 9 14 PL SQL User s Guide and Reference Defining Object Types Now we can write our object type specification as follows CREATE TYPE Stack AS OBJECT max_size INTEGER top INTEGER position IntArray MEMBER PROCEDURE initialize MEMBER FUNCTION full RETURN BOOLEAN EMBER FUNCTION empty RETURN BOOLEAN MEMBER PROCEDURE push n IN INTEGE EMBER PROCEDURE pop n OUT INTEGE W W U W Finally we write the object type body as follows CREATE TYPE BODY Stack AS MEMBER PROCEDURE initialize IS top 0 Call constructor for varray and set element 1 to NULL position IntArray NULL max size posit
405. ide A table lock never keeps other users from querying a table and a query never acquires a table lock Only if two different transactions try to modify the same row will one transaction wait for the other to complete 5 52 PL SQL User s Guide and Reference Processing Transactions Fetching Across Commits Remember the FOR UPDATE clause acquires exclusive row locks All rows are locked when you open the cursor and they are unlocked when you commit your transaction So you cannot fetch from a FOR UPDATE cursor after a commit If you do PL SQL raises an exception In the following example the cursor FOR loop fails after the tenth insert DECLARE CURSOR cl IS SELECT ename FROM emp FOR UPDATE OF sal ctr NUMBER 0 BEGIN FOR emp_rec IN cl LOOP FETCHes implicitly Ctr t ctr 1 INSERT INTO temp VALUES ctr still going IF ctr gt 10 THEN COMMIT releases locks END IF END LOOP END If you want to fetch across commits do not use the FOR UPDATE and CURRENT OF clauses Instead use the ROWID pseudocolumn to mimic the CURRENT OF clause Simply select the rowid of each row into a ROWID variable Then use the rowid to identify the current row during subsequent updates and deletes An example follows DECLAF p CURSOR cl IS SELECT ename job rowid FROM emp my_enam mp enames TYPE my_Job emp JobSTY
406. idth of a LONG column is 2147483647 bytes However you cannot retrieve a value longer than 32760 bytes from a LONG column into a LONG variable LONG columns can store text arrays of characters or even short documents You can reference LONG columns in UPDATE INSERT and most SELECT statements but not in expressions SQL function calls or certain SOL clauses such as WHERE GROUP BY and CONNECT BY For more information see Oracle8 SQL Reference RAW You use the RAW datatype to store binary data or byte strings For example a RAW variable might store a sequence of graphics characters or a digitized picture Raw data is like VARCHAR2 data except that PL SQL does not interpret raw data Likewise Net8 does no character set conversions when you transmit raw data from one system to another The RAW datatype takes a required parameter that lets you specify a maximum length up to 32767 bytes The syntax follows RAW maximum_length You cannot use a constant or variable to specify the maximum length you must use an integer literal in the range 1 32767 The maximum width of a RAW database column is 2000 bytes So you cannot insert RAW values longer than 2000 bytes into a RAW column You can insert any RAW value into a LONG RAW database column because the maximum width of a LONG RAW column is 2147483647 bytes However you cannot retrieve a value longer than 32767 bytes from a LONG RAW column into a R
407. ification from its body That way you can hide implementation details by placing the procedure in a package You can define procedures in a package body without declaring their specifications in the package specification However such procedures can be called only from inside the package Procedures can be defined using any Oracle tool that supports PL SQL To become available for general use however procedures must be CREATEd and stored in an Oracle database You can issue the CREATE PROCEDURE Statement interactively from SQL Plus or Enterprise Manager For the full syntax of the CREATE PROCEDURE statement see Oracle8 SQL Reference At least one statement must appear in the executable part of a procedure The NULL statement meets this requirement The following procedure debits a bank account PROCEDURE debit_account acct_id INTEGER amount REAL IS old_balance REAL new_balance REAL overdrawn EXCEPTION BEGI SELECT bal INTO old_balance FROM accts WHERE acctno acct_id new_balance old balance amount IF new_balance lt 0 THEN RAISE overdrawn ELSE UPDATE accts SET bal new_balance WHERE acctno acct_id END IF EXCEPTION WHEN overdrawn THEN END debit_account 11 124 PL SQL User s Guide and Reference Procedures In the following example you call t
408. ifies the datatype of a cursor result value You can use the SROWTYPE attribute in the RETURN clause to provide a record type that represents a row in a database table or a row returned by a previously declared cursor Also you can use the TYPE attribute to provide the datatype of a previously declared record A cursor body must have a SELECT statement and the same RETURN clause as its corresponding cursor specification Also the number order and datatypes of select items in the SELECT clause must match the RETURN clause parameter_name This identifies a cursor parameter that is a variable declared as the formal parameter of a cursor A cursor parameter can appear in a query wherever a constant can appear The formal parameters of a cursor must be IN parameters The query can also reference other PL SQL variables within its scope db_table_name This identifies a database table or view that must be accessible when the declaration is elaborated 11 46 PL SQL User s Guide and Reference Cursors Usage Notes cursor_name This identifies an explicit cursor previously declared within the current scope record_name This identifies a user defined record previously declared within the current scope record_type_name This identifies a RECORD type previously defined within the current scope ROWTYPE This attribute provides a record type that represents a row in a database table or a
409. ilding blocks which you can use to construct modular maintainable applications Major Topics What Are Subprograms Advantages of Subprograms Procedures Functions RETURN Statement Declaring Subprograms Actual versus Formal Parameters Positional and Named Notation Parameter Modes Parameter Default Values Parameter Aliasing Overloading Recursion Subprograms 7 1 What Are Subprograms What Are Subprograms Subprograms are named PL SQL blocks that can take parameters and be invoked PL SQL has two types of subprograms called procedures and functions Generally you use a procedure to perform an action and a function to compute a value Like unnamed or anonymous PL SQL blocks subprograms have a declarative part an executable part and an optional exception handling part The declarative part contains declarations of types cursors constants variables exceptions and nested subprograms These items are local and cease to exist when you exit the subprogram The executable part contains statements that assign values control execution and manipulate Oracle data The exception handling part contains exception handlers which deal with exceptions raised during execution Consider the following procedure named debit_account which debits a bank account PROCEDURE debit_account acct_id INTEGER amount REAL IS old_balance REAL new_balance REAL overdrawn EXCEPTION BEGI SELECT bal INTO old_balance FROM ac
410. in Features a a a olin dees 1 2 a AA eee A A eh hatin EE cea ATAATA 1 2 Variables id Constants 20 02 32i eee ads 1 3 O a ok eee a ee te ehh i ae oy Se A Se ala a Bee Ne Ca 1 5 Cursor FOR LOOPS lia aa Nai 1 6 Cursor Va iablearoiin da aaa 1 6 ATERIDULOS A A a A dile eii 1 7 Control StrUCHUTES cui A A eee hie eee 1 8 Modularity sissors fert aeisvasasteasasea acetaes dheaa a Siea CAE SEE R Stade OIE rra aces 1 11 Data Abstraction aiii ainiin anaa e ble e e lodo id 1 14 Information HidIOS icono aria ita da ii Ac Canine 1 16 Error Hand sind atte ahaa odie Sooner IATA ias EEA A Aia 1 17 Architectures A A A E a Pd 1 18 In thie Oracle Servera lo At need dea 1 19 In Oracle ToolSs cten eine diet e ee ele de de 1 20 Advantages of PL SO iii tants nsa ea edini 1 21 support for SOl aaa pea tad asii 1 21 Support for Object Oriented Programming mcocononononnnnnnnnnnnncnrannnnnnannnannnnararanonnnnn coran no nonananannos 1 21 Better Performance A a ia 1 22 Dorta A E EA A e 1 23 Higher Productivity eeen seo hE eese eten EAEE EES TEESE EES T AEREE TE TESSE RESE EART TEESE 1 23 Integration with Oracle ssostni covered eaa E E a ds caia its 1 23 2 Fundamentals Character Setir nreno eea ea e a E E a na a a EEES E 2 2 Lexical Units cniras iia A enn 2 2 Delimiters iii idad 2 3 MASTS TS ie cfs eee cote nace Pieces TDT TEO cece UI E ara pia 2 4 Detter S ise cs bet chs ll Ai sls Sein AA Oral 2 7 COMMONS A A A AT E N 2 9 DatatyDesiiiiiaica in lala
411. ing head _ count INTEGER score UMBER SELECT COUNT INTO head count FROM emp WHERE job job title SELECT rating INTO score FROM reviews WHERE empno emp_id score score 100 maximum score is 100 RETURN head_count 1 ROUND head_count score END rank 8 10 PL SQL User s Guide and Reference Some Examples BEGIN initialization part starts here INSERT INTO emp audit VALUES SYSDATE USER EMP_ACTIONS number_hired 0 ND emp_actions ie Remember the initialization part of a package is run just once the first time you reference the package So in the last example only one row is inserted into the database table emp_audit Likewise the variable number_hired is initialized only once Every time the procedure hire_employee is called the variable number_hired is updated However the count kept by number_hi red is session specific That is the count reflects the number of new employees processed by one user not the number processed by all users In the next example you package some typical bank transactions Assume that debit and credit transactions are entered after business hours via automatic teller machines then applied to accounts the next morning CREATE PACKAGE bank_transactions AS Declare externally visible constant minimum_bala
412. ing SQL statement which does the same task INSERT INTO staff SELECT PRIOR ename manages ename 7 on tier to char LEVEL 1 FROM emp START WITH empno 7839 CONNECT BY PRIOR empno mgr The SQL statement is appreciably faster However the procedure is more flexible For example a multi table query cannot contain the CONNECT BY clause So unlike the procedure the SOL statement cannot be modified to do joins A join combines rows from two or more database tables In addition a procedure can process data in ways that a single SQL statement cannot Mutual Recursion Subprograms are mutually recursive if they directly or indirectly call each other In the example below the Boolean functions odd and even which determine whether a number is odd or even call each other directly The forward declaration of odd is necessary because even calls odd which is not yet declared when the call is made See Forward Declarations on page 7 8 FUNCTION odd n NATURAL RETURN BOOLEAN forward declaration FUNCTION even n NATURAL RETURN BOOLEAN IS BEGIN IF n 0 THEN RETURN TRUE ELSE RETURN odd n 1 mutually recursive call END IF END even FUNCTION odd n NATURAL RETURN BOOLEAN IS BEGIN IF n 0 THEN RETURN FALSE ELSE RETURN even n E mutually recursive call END IF END odd
413. ion LIMIT get varray size constraint 25 position EXTEND max_size 1 1 copy element 1 into 2 25 END initialize MEMBER FUNCTION full RETURN BOOLEAN IS BEGIN RETURN top max_size return TRUE if stack is full END full EMBER FUNCTION empty RETURN BOOLEAN IS BEGIN RETURN top 0 return TRUE if stack is empty END empty MEMBER PROCEDURE push n IN INTEGER IS BEGIN IF NOT full THEN top top 1 push integer onto stack position top n ELSE stack is full RAISE_APPLICATION_ERROR 20101 stack overflow END IF END push EMBER PROCEDURE pop n OUT INTEGER IS Object Types 9 15 Defining Object Types BEGIN IF NOT empty THEN n position top top top 1 pop integer off stack ELSE stack is empty RAISE_APPLICATION_ERROR 20102 stack underflow END IF END pop END Notice that in member procedures push and pop we use the built in procedure raise_application_error to issue user defined error messages That way we report errors to the client program and avoid returning unhandled exceptions to the host environment The client program gets a PL SQL exception which it can process using the error reporting functions SQLCODE and SQLERRM in an OTHERS exception ha
414. ion begins with the keyword FUNCTION and ends with the RETURN clause which specifies the datatype of the result value Parameter declarations are optional Functions that take no parameters are written without parentheses The function body begins with the keyword IS and ends with the keyword END followed by an optional function name The function body has three parts a declarative part an executable part and an optional exception handling part Subprograms 7 5 Functions Restriction The declarative part contains local declarations which are placed between the keywords IS and BEGIN The keyword DECLARE is not used The executable part contains statements which are placed between the keywords BEGIN and EXCEPTION or END One or more RETURN statements must appear in the executable part of a function The exception handling part contains exception handlers which are placed between the keywords EXCEPTION and END Consider the function sa1_ok which determines if an employee salary is out of range FUNCTION sal_ok salary REAL title REAL RETURN BOOLEAN IS min_sal REAL max_sal REAL BEGI SELECT losal hisal INTO min_sal max_sal FROM sals WHERE job title RETURN salary gt min_sal AND salary lt max_sal END sal_ok E When called this function accepts an employee salary and job title It uses the job title to select
415. ions Using SET TRANSACTION You use the SET TRANSACTION statement to begin a read only or read write transaction establish an isolation level or assign your current transaction to a specified rollback segment Read only transactions are useful for running multiple queries against one or more tables while other users update the same tables During a read only transaction all queries refer to the same snapshot of the database providing a multi table multi query read consistent view Other users can continue to query or update data as usual A commit or rollback ends the transaction In the example below as a store manager you use a read only transaction to gather sales figures for the day the past week and the past month The figures are unaffected by other users updating the database during the transaction DECLARE daily_sales REAL weekly sales REAL monthly_sales REAL COMMIT ends previous transaction TRANSACTION READ ONLY CT SUM amt INTO daily_sales FROM sales WHERE dte SYSDATE CT SUM amt INTO weekly_sales FROM sales WHERE dte gt SYSDATE 7 C WH E SUM amt INTO monthly_sales FROM sales ERE dte gt SYSDATE 30 77 ends read only transaction END The SET TRANSACTION statement must be the first SQL statement in a read only transaction and can only appear once in a transaction If you set a
416. ions are like variable declarations Each field has a unique name and specific datatype So the value of a record is actually a collection of values each of which is of some simpler type As the example below shows PL SQL lets you define records that contain objects collections and other records called nested records However object types cannot have attributes of type RECORD DECL AF YPE TimeRec IS RECORD seconds SMALLINT minutes SMALLINT hours SMALLINT TYPE FlightRec IS RECORD flight_no INTEGER plane_id VARCHAR2 10 Collections and Records 4 29 Defining and Declaring Records captain Employee declare object passengers PassengerList declare varray depart_tim TimeRec declare nested record airport_code VARCHAR2 10 The next example shows that you can specify a RECORD type in the RETURN clause of a function specification That allows the function to return a user defined record of the same type DECLARE YPE EmpRec IS RECORD emp_id INTEGER last_name VARCHAR2 15 dept_num INTEGER 2 job title VARCHAR2 15 salary REAL 7 2 FUNCTION nth_highest_salary n INTEGER RETURN EmpRec IS Declaring Records Once you define a RECORD type you can declare records of that type as the following example shows DECLARE YPE StockItem IS RECORD item_no INTEGER
417. ition with a sequence of statements Before each iteration of the loop the condition is evaluated If the condition yields TRUE the sequence of statements is executed then control resumes at the top of the loop If the condition yields FALSE or NULL the loop is bypassed and control passes to the next statement In the following example you find the first employee who has a salary over 4000 and is higher in the chain of command than employee 7902 available online in file examp3 DECLARE salary emp sal TYPE mgr_num emp mgrsTYPE last_nam mp enameSTYPE starting_empno CONSTANT NUMBER 4 7902 BEGI SELECT sal mgr INTO salary mgr_num FROM emp WHERE empno starting_empno WHILE salary lt 4000 LOOP SEL z CT sal mgr ename INTO salary mgr num last_name ROM emp WHERE empno mgr num END LOOP INSERT INTO temp VALUES NULL salary last_name COMIT tj z 1 10 PL SQL User s Guide and Reference Main Features Modularity The EXIT WHEN statement lets you complete a loop if further processing is impossible or undesirable When the EXIT statement is encountered the condition in the WHEN clause is evaluated If the condition yields TRUE the loop completes and control passes to the next statement In the following example the loop completes when the value of total exceeds
418. k or any sub block you can be sure it will be handled Error Handling 6 3 Predefined Exceptions Predefined Exceptions An internal exception is raised implicitly whenever your PL SQL program violates an Oracle rule or exceeds a system dependent limit Every Oracle error has a number but exceptions must be handled by name So PL SQL predefines some common Oracle errors as exceptions For example PL SQL raises the predefined exception NO_DATA_FOUND if a SELECT INTO statement returns no rows To handle other Oracle errors you can use the OTHERS handler The error reporting functions SOLCODE and SQLERRM are especially useful in the OTHERS handler because they return the Oracle error code and message text Alternatively you can use the pragma EXCEPTION_INIT to associate exception names with Oracle error numbers See Using EXCEPTION_INIT on page 6 8 PL SQL declares predefined exceptions globally in package STANDARD which defines the PL SQL environment So you need not declare them yourself You can write handlers for predefined exceptions using the names shown in the list below Also shown are the corresponding Oracle error codes and SOLCODE return values Exception Oracle Error SQLCODE Value _ ACCESS _INTO_ NULL ORA 06530 6530 COLLECTION_IS_NULL ORA
419. kage body can also contain private declarations which define types and items necessary for the internal workings of the package The scope of these declarations is local to the package body Therefore the declared types and items are inaccessible except from within the package body Unlike a package specification the declarative part of a package body can contain subprogram bodies Following the declarative part of a package body is the optional initialization part which typically holds statements that initialize some of the variables previously declared in the package The initialization part of a package plays a minor role because unlike subprograms a package cannot be called or passed parameters As a result the initialization part of a package is run only once the first time you reference the package Recall that if a specification declares only types constants variables and exceptions the package body is unnecessary However the body can still be used to initialize items declared in the specification Some Examples Consider the package below named emp_act ions The package specification declares the following types items and subprograms a types EmpRecTyp and DeptRecTyp a cursor desc_salary exception salary_missing a functions hire employee nth_highest_salary and rank procedures fire_employeeand raise_salary After writing the package you can develop applications that reference its types call its subprograms
420. ks periodicals and tapes A master table stores the title and category code 1 book 2 periodical 3 tape of each item Three detail tables store category specific information When called the procedure searches the master table by title uses the associated category code to pick an OPEN FOR statement then opens a cursor variable for a query of the proper detail table CREATE PACKAGE cv_types AS TYPE LibCurTyp IS REF CURSOR END cv_types CREATE PROCEDURE find_item title VARCHAR2 100 lib_cv IN OUT cv_types LibCurTyp AS code BINARY _INTEGER BEGI SELECT item_code FROM titles INTO code WHERE item_title title IF code 1 THEN OPEN lib_cv FOR SELECT FROM books Interaction with Oracle 5 27 Using Cursor Variables WHERE book_title title SIF code 2 THEN OPEN lib_cv FOR SELECT FROM periodicals WHERE periodical_title title SIF code 3 THEN OPEN lib_cv FOR SELECT FROM tapes WHERE tape_title title END IF END find_item zj 1 x Example 2 A client side application in a branch library might use the following PL SQL block to display the retrieved information DECLARE lib cv cv_types LibCurTyp book_rec booksSROWTYPE periodical_rec periodicals ROWTYPE
421. l procedure External Procedures 10 25 Restrictions on External Procedures a Inthe LIBRARY subclause you cannot use a database link to specify a remote library a The Listener must start agent extproc on the machine that runs the Oracle server Starting extrproc on a different machine is not supported a The maximum number of parameters that you can pass to a C external procedure is 128 However if you pass float or double parameters by value the maximum is less than 128 How much less depends on the number of such parameters and your operating system To get a rough estimate count each float or double passed by value as two parameters 10 26 PL SQL User s Guide and Reference 11 Language Elements Grammar which knows how to control even kings Moli re This chapter is a quick reference guide to PL SQL syntax and semantics It shows you how commands parameters and other language elements are sequenced to form PL SOL statements Also to save you time and trouble it provides usage notes and short examples Major Topics Assignment Statement Blocks CLOSE Statement Collection Methods Collections Comments COMMIT Statement Constants and Variables Cursor Attributes Cursor Variables Cursors DELETE Statement EXCEPTION_INIT Pragma Exceptions EXIT Statement Expressions External Procedures FETCH Statement Functions Language Elements 11 1 GOTO Statement IF Statement INSERT Statement Litera
422. le before you assign it a value You can use assignment statements to assign values to a variable For example the following statement assigns a new value to the variable bonus overwriting its old value bonus salary 0 15 The expression following the assignment operator can be arbitrarily complex but it must yield a datatype that is the same as or convertible to the datatype of the variable Boolean Values Only the values TRUE and FALSE and the non value NULL can be assigned to a Boolean variable For example given the declaration DECLARE done BOOLEAN the following statements are legal BEGIN done FALSE WHILE NOT done LOOP END LOOP When applied to an expression the relational operators return a Boolean value So the following assignment is legal done count gt 500 2 40 PL SQL User s Guide and Reference Expressions and Comparisons Database Values Alternatively you can use the SELECT statement to have Oracle assign values to a variable For each item in the select list there must be a corresponding type compatible variable in the INTO list An example follows DECLARE my_empno emp empnosTYPE my_ename emp enamesTYPE wages NUMBER 7 2 BEGI SELECT ename sal comm INTO last_name wages FROM emp WHERE empno emp_id However you cannot select column values i
423. les must be prefixed with a colon indicator_name This identifies an indicator variable declared in a PL SQL host environment and passed to PL SQL Indicator variables must be prefixed with a colon An indicator variable indicates the value or condition of its associated host variable For example in the Oracle Precompiler environment indicator variables can detect nulls or truncated values in output host variables numeric_constant_name This identifies a previously declared constant that stores a numeric value It must be initialized to a numeric value or a value implicitly convertible to a numeric value numeric_function_call This is a function call that returns a numeric value or a value implicitly convertible to a numeric value Language Elements 11 65 Expressions numeric_literal This is a literal that represents a numeric value or a value implicitly convertible to a numeric value collection_name This identifies a nested table index by table or varray previously declared within the current scope numeric_variable_name This identifies a previously declared variable that stores a numeric value NULL This keyword represents a null it stands for a missing unknown or inapplicable value When NULL is used in a numeric or date expression the result is a null exponent This is an expression that must yield a numeric value E These symbols are the addition subtraction division multipli
424. lized variable Therefore its value cannot be assigned to another variable or reassigned to itself For instance the following assignment statement causes a compilation error PROCEDURE calc_bonus emp_id IN INTEGER bonus OUT REAL IS hire_date DATE BEGI SELECT sal 0 10 hiredate INTO bonus hire_date FROM emp WHERE empno emp_id Subprograms 7 13 Parameter Modes IF MONTHS BETWEEN SYSDATE hire_date gt 60 THEN bonus bonus 500 causes syntax error END IF The actual parameter that corresponds to an OUT formal parameter must be a variable it cannot be a constant or an expression For example the following procedure call is illegal calc_bonus 7499 salary commission causes compilation error An OUT actual parameter can have a value before the subprogram is called However the value is lost when you call the subprogram Inside the subprogram an OUT formal parameter cannot be used in an expression the only operation allowed on the parameter is to assign it a value Like variables OUT formal parameters are initialized to NULL So before exiting a subprogram explicitly assign values to all OUT formal parameters Otherwise the corresponding actual parameters will be null If you exit successfully PL SQL assigns values to the actual parameters However if you exit with an unhandled exception PL SQL does not assign valu
425. llows DECLARE CURSOR cl IS SELECT empno sal FROM emp WHERE sal gt 2000 AND ROWNUM lt 10 returns 10 rows The value of ROWNUM increases only when a row is retrieved so the only meaningful use of ROWNUM in a WHERE clause is WHERE ROWNUM lt constant Interaction with Oracle 5 5 SQL Support SQL Operators PL SQL lets you use all the SQL comparison set and row operators in SQL statements This section briefly describes some of these operators For more information see Oracle8 SQL Reference Comparison Operators Typically you use comparison operators in the WHERE clause of a data manipulation statement to form predicates which compare one expression to another and always yields TRUE FALSE or NULL You can use all the comparison operators listed below to form predicates Moreover you can combine predicates using the logical operators AND OR and NOT ALL Compares a value to each value in a list or returned by a subquery and yields TRUE if all of the individual comparisons yield TRUE ANY SOME Compares a value to each value in a list or returned by a subquery and yields TRUE if any of the individual comparisons yields TRUE BETWEEN Tests whether a value lies in a specified range EXISTS Returns TRUE if a subquery returns at least one row IN Tests for set membership IS NULL Tests
426. loops END LOOP inner END LOOP outer Related Topics Expressions LOOP Statements 11 58 PL SQL User s Guide and Reference Expressions Expressions Syntax An expression is an arbitrarily complex combination of variables constants literals operators and function calls The simplest expression is a single variable The PL SQL compiler determines the datatype of an expression from the types of the variables constants literals and operators that comprise the expression Every time the expression is evaluated a single value of that type results For more information see Expressions and Comparisons on page 2 41 expression boolean_expression character_expression date_expression L numeric_expression 5 boolean_expression i boolean_constant_name boolean_function_call boolean_literal boolean_variable_name other_boolean_form NOT boolean_constant_name p boolean_function_call d boolean literal boolean_variable_name L other_boolean_form Language Elements 11 59 Expressions other_boolean_form relational_operator expression Era AO AO NOT expression NOT NOT LER ae cm NOT cursor_name cursor_variable_name C host_cursor_variable_name Y otto Sa ua character_expression character_constant_name character_function_call character_literal H character_variable_name E h
427. lowed Declaring Collections Once you define a collection type you can declare collections of that type as the following SQL Plus script shows CREATE TYPE CourseList AS TABLE OF VARCHAR2 10 define TABLE type CREATE TYPE Student AS OBJECT create object id num INTEGER 4 name VARCHARZ2 25 address VARCHAR2 35 status CHAR 2 courses CourseList declare nested table as attribute The identifier courses represents an entire nested table Each element of courses will store the code name of a college course such as Math 1020 Collections and Records 4 7 Defining and Declaring Collections The script below creates a database column that stores varrays Each element of the varrays will store a Project object CREATE TYPE Project AS OBJECT create object project_no NUMBER 2 title VARCHAR2 35 cost NUMBER 7 2 CREATE TYPE ProjectList AS VARRAY 50 OF Project define VARRAY type CREATE TABLE department create database table dept_id NUMBER 2 name VARCHAR2 15 budget NUMBER 11 2 projects ProjectList declare varray as column The following example shows that you can use TYPE to provide the datatype of a previously declared collection DECLARE YPE Platoon IS VARRAY 20 OF Soldier pl Platoon p2 p1 TYPE
428. ls LOCK TABLE Statement LOOP Statements NULL Statement Object Types OPEN Statement OPEN FOR Statement Packages Procedures RAISE Statement Records RETURN Statement ROLLBACK Statement ROWTYPE Attribute SAVEPOINT Statement SELECT INTO Statement SET TRANSACTION Statement SOL Cursor SQLCODE Function SQLERRM Function TYPE Attribute UPDATE Statement Reading the Syntax Diagrams When you are unsure of the syntax to use in a PL SQL statement trace through its syntax diagram reading from left to right and top to bottom You can verify or construct any PL SQL statement that way The diagrams are graphic representations of Bachus Naur Form BNF productions Within the diagrams keywords are enclosed in boxes delimiters in circles and identifiers in ovals Each diagram defines a syntactic element Every path through the diagram describes a possible form of that element Follow in the direction of the arrows If a line loops back on itself you can repeat the element enclosed by the loop 11 2 PL SQL User s Guide and Reference Assignment Statement Assignment Statement An assignment statement sets the current value of a variable field parameter or element The statement consists of an assignment target followed by the assignment operator and an expression When the statement is executed the expression is evaluated and the resulting value is stored in the target For more information see Assignments on page
429. ls This chapter focuses on the small scale aspects of PL SOL It discusses lexical units scalar datatypes user defined subtypes data conversion expressions assignments block structure declarations and scope Chapter 3 Control Structures This chapter shows you how to structure the flow of control through a PL SQL program It describes conditional iterative and sequential control You learn how to apply simple but powerful control structures such as IF THEN ELSE and WHILE LOOP Chapter 4 Collections and Records This chapter focuses on the composite datatypes TABLE VARRAY and RECORD You learn how to reference and manipulate whole collections of data You also learn how to treat related but dissimilar data as a logical unit Chapter 5 Interaction with Oracle This chapter shows you how PL SQL supports the SOL commands functions and operators that let you manipulate Oracle data You also learn how to manage cursors process transactions and safeguard your database Chapter 6 Error Handling This chapter provides an in depth discussion of error reporting and recovery You learn how to detect and handle errors using PL SQL exceptions Chapter 7 Subprograms This chapter shows you how to write and use subprograms It discusses procedures functions forward declarations actual versus formal parameters positional and named notation parameter modes parameter default values aliasing overloading and recursion xvii xviii Ch
430. lue DELETE allows you to maintain sparse nested tables In the following example you retrieve nested table prospects into a temporary table prune it then store it back in the database DECLARE my_prospects ProspectList revenue NUMBER BEGIN SELECT prospects INTO my_prospects FROM customers WHERE FOR i IN my_prospects FIRST my_prospects LAST LOOP stimate_revenue my_prospects i revenue IF revenue lt 25000 THEN my_prospects DELETE i END IF END LOOP UPDATE customers SET prospects my_prospects WHERE call procedure The amount of memory allocated to a nested table can increase or decrease dynamically As you delete elements memory is freed page by page If you delete the entire table all the memory is freed 4 26 PL SQL User s Guide and Reference Avoiding Collection Exceptions Applying Methods to Collection Parameters Within a subprogram a collection parameter assumes the properties of the argument bound to it So you can apply methods FIRST LAST COUNT and so on to such parameters In the following example a nested table is declared as the formal parameter of a packaged procedure CREATE PACKAGE personnel AS TYPE Staff IS TABLE OF Employee PROCEDURE award_bonuses members IN Staff END personnel CREATE PACKAGE BODY personnel AS
431. ly and control passes to the next statement An example follows LOOP IF credit_rating lt 3 THEN EXIT exit loop immediately END IF END LOOP control resumes here The next example shows that you cannot use the EXIT statement to complete a PL SQL block BEGIN IF credit_rating lt 3 THEN EXIT illegal END IF END Remember the EXIT statement must be placed inside a loop To complete a PL SQL block before its normal end is reached you can use the RETURN statement For more information see RETURN Statement on page 7 7 EXIT WHEN The EXIT WHEN statement allows a loop to complete conditionally When the EXIT statement is encountered the condition in the WHEN clause is evaluated If the condition yields TRUE the loop completes and control passes to the next statement after the loop An example follows LOOP FETCH cl INTO EXIT WHEN c1SNOTFOUND exit loop if condition is true END LOOP CLOSE cl Control Structures 3 7 Iterative Control LOOP and EXIT Statements Until the condition yields TRUE the loop cannot complete So statements within the loop must change the value of the condition In the last example if the FETCH statement returns a row the condition yields FALSE When the FETCH statement fails to return a row the condition yields TRUE the loop completes and control passes to the CLOS
432. mal parameter must be compatible Fetching with a Cursor The FETCH statement retrieves the rows in the result set one at a time After each fetch the cursor advances to the next row in the result set An example of the FETCH statement follows FETCH cl INTO my_empno my_ename my_deptno For each column value returned by the query associated with the cursor there must be a corresponding variable in the INTO list Also their datatypes must be compatible Typically you use the FETCH statement as follows LOOP FETCH cl INTO my_record EXIT WHEN c1SNOTFOUND process data record END LOOP The query can reference PL SQL variables within its scope However any variables in the query are evaluated only when the cursor is opened In the following example each retrieved salary is multiplied by 2 even though factor is incremented after each fetch DECLARE my_sal emp salSTYPE my_job emp jobsTYPE factor INTEGER 2 CURSOR cl IS SELECT factor sal FROM emp WHERE job my_job BEGIN OPEN cl here factor equals 2 LOOP FETCH cl INTO my_sal EXIT WHEN cl NOTFOUND factor factor 1 does not affect FETCH END LOOP END To change the result set or the values of variables in the query you must close and reopen the cursor with the input variables set to their new values 5 12 PL SQL Us
433. me datatype family For example given the following declarations the value of verb can be assigned to sentence DECLARE SUBTYPE Word IS CHAR SUBTYPE Text IS VARCHAR2 verb Word sentence Text BEGI sentence verb Datatype Conversion Sometimes it is necessary to convert a value from one datatype to another For example if you want to examine a rowid you must convert it to a character string PL SQL supports both explicit and implicit automatic datatype conversion Explicit Conversion To convert values from one datatype to another you use built in functions For example to convert a CHAR value to a DATE or NUMBER value you use the function TO_DATE or TO_NUMBER respectively Conversely to convert a DATE or NUMBER value to a CHAR value you use the function TO_CHAR For more information about these functions see Oracle8 SQL Reference Fundamentals 2 25 Datatype Conversion Implicit Conversion When it makes sense PL SQL can convert the datatype of a value implicitly This allows you to use literals variables and parameters of one type where another type is expected In the example below the CHAR variables start_time and finish_time hold string values representing the number of seconds past midnight The difference between those values must be assigned to the NUMBER variable elapsed_time So PL SQL converts the CHAR values to NUMBER values automatically
434. me column is not null and not KING the following statement deletes no rows DELETE FROM emp WHERE ename NOT IN NULL KING Concatenation Operator Double vertical bars serve as the concatenation operator which appends one string to another as the following example shows suit case suitcase If both operands have datatype CHAR the concatenation operator returns a CHAR value Otherwise it returns a VARCHAR2 value Boolean Expressions PL SQL lets you compare variables and constants in both SQL and procedural statements These comparisons called Boolean expressions consist of simple or complex expressions separated by relational operators Often Boolean expressions are connected by the logical operators AND OR and NOT A Boolean expression always yields TRUE FALSE or NULL In a SOL statement Boolean expressions let you specify the rows in a table that are affected by the statement In a procedural statement Boolean expressions are the basis for conditional control There are three kinds of Boolean expressions arithmetic character and date 2 46 PL SQL User s Guide and Reference Expressions and Comparisons Arithmetic Expressions You can use the relational operators to compare numbers for equality or inequality Comparisons are quantitative that is one number is greater than another if it represents a larger quantity For example
435. me schema object For example two users updating the same table might wait if each tries to update a row currently locked by the other Because each user is waiting for resources held by another user neither can continue until Oracle breaks the deadlock by signaling an error to the last participating transaction When a table is being queried by one user and updated by another at the same time Oracle generates a read consistent view of the data for the query That is once a query begins and as it proceeds the data read by the query does not change As update activity continues Oracle takes snapshots of the table s data and records changes in a rollback segment Oracle uses rollback segments to build read consistent query results and to undo changes if necessary How Transactions Guard Your Database Oracle is transaction oriented that is it uses transactions to ensure data integrity A transaction is a series of one or more logically related SQL statements that accomplish a task Oracle treats the series of SQL statements as a unit so that all the changes brought about by the statements are either committed made permanent or rolled back undone at the same time If your program fails in the middle of a transaction the database is automatically restored to its former state The first SOL statement in your program begins a transaction When one transaction ends the next SQL statement automatically begins another transaction Thus every
436. ment is null REPLACE returns its first argument with every occurrence of its second argument removed For example after the assignments syllabified_name Gold i locks name REPLACE syllabified_name NULL the value of name is goldilocks If its second and third arguments are null REPLACE simply returns its first argument Built In Functions PL SQL provides many powerful functions to help you manipulate data These built in functions fall into the following categories error reporting a number Character a conversion a date a miscellaneous Table 2 4 shows the functions in each category For descriptions of the error reporting functions see Chapter 11 For descriptions of the other functions see Oracle8 SQL Reference You can use all the functions in SQL statements except the error reporting functions SQLCODE and SOLERRM Also you can use all the functions in procedural statements except the miscellaneous functions DECODE DUMP and VSIZE The SQL group functions AVG MIN MAX COUNT SUM STDDEV and VARIANCE are not built into PL SQL Nevertheless you can use them in SQL statements but not in procedural statements Fundamentals 2 51 Built In Functions Table 2 4 Built in Functions
437. meters and be invoked Generally you use a function to compute a value A function has two parts the specification and the body The function specification begins with the keyword FUNCTION and ends with the RETURN clause which specifies the datatype of the result value Parameter declarations are optional Functions that take no parameters are written without parentheses The function body begins with the keyword IS and ends with the keyword END followed by an optional function name The function body has three parts an optional declarative part an executable part and an optional exception handling part The declarative part contains declarations of types cursors constants variables exceptions and subprograms These items are local and cease to exist when you exit the function The executable part contains statements that assign values control execution and manipulate Oracle data The exception handling part contains exception handlers which deal with exceptions raised during execution For more information see Functions on page 7 5 function_specification gt parameter_declaration 0 O function_body function_declaration O FUNCTION RETURN LY datatype type_definition item_declaration lt function_declaration E procedure_declaration Language Elements 11 79 Functions PE er EXCEPTION G exception_handler y END parameter_decl
438. n 1 16 data integrity 5 44 data lock 5 45 database changes making permanent 5 46 undoing 5 47 database character set 2 18 datatype 2 10 BFILE 2 20 BINARY_INTEGER 2 11 BLOB 2 20 BOOLEAN 2 21 CHAR 2 14 CLOB 2 20 constraint 7 4 DATE 2 21 families 2 10 implicit conversion 2 26 LONG 2 15 LONG RAW 2 15 MLSLABEL 2 22 NCHAR 2 18 NCLOB 2 21 NLS 2 17 NUMBER 2 12 NVARCHAR2 2 19 PLS_INTEGER 2 13 RAW 2 15 RECORD 4 28 REF CURSOR 5 19 Index 4 ROWID 2 16 scalar versus composite 2 10 TABLE 4 2 VARCHAR2 2 16 VARRAY 4 4 date converting 2 27 TO_CHAR default format 2 27 DATE datatype 2 21 DBMS_ALERT package 8 18 DBMS_OUTPUT package 8 16 DBMS_PIPE package 8 17 DBMS_SQL package 5 8 8 17 array interface 5 57 DBMS_STANDARD package 8 16 DDL support 5 7 deadlock 5 45 effect on transactions 5 47 how broken 5 47 DEBUG_EXTPROC package 10 24 DEC subtype 2 13 DECIMAL subtype 2 13 declaration collection 4 7 constant 2 29 cursor 5 10 cursor variable 5 20 exception 6 6 forward 7 8 object 9 23 record 4 30 subprogram 7 8 variable 2 28 declarative part function 7 6 PL SQL block 1 3 procedure 7 4 DECODE function treatment of nulls 2 50 DEFAULT keyword 2 29 default parameter value 7 15 default pragma 9 13 DELETE collection method 4 26 DELETE statement RETURNING clause 5 55 syntax 11 49 delimiter 2 3 demo external procedure 10 24 dense
439. n a null to ot_hours IF gross_pay emp_num gt max_pay THEN illegal Instead you must pass the null explicitly as in IF gross pay emp_num ot_hour gt NULL gt max pay THEN or you can initialize ot_hours to NULL as follows ot_hours IN NUMBER DEFAULT NULL 7 16 PL SQL User s Guide and Reference Parameter Aliasing Finally when creating a stored subprogram you cannot use bind variables in the DEFAULT clause The following SQL Plus example raises a bad bind variable exception because at the time of creation num is just a placeholder whose value might change SQL gt VARIABLE num NUMBER SQL gt CREATE FUNCTION gross_pay emp_id IN BER DEFAULT num Parameter Aliasing To optimize a subprogram call the PL SQL compiler can choose between two methods of parameter passing With the by value method the value of an actual parameter is passed to the subprogram With the by reference method only a pointer to the value is passed in which case the actual and formal parameters reference the same item Passing large composite types by value is inefficient So in most cases but never across client server boundaries PL SQL passes composite types by reference which saves time The easy to avoid problem of aliasing occurs when a global variable appears as an actual parameter in a subprogram call and then is referenced within the su
440. n about the execution of data manipulation statements For more information see Managing Cursors on page 5 9 sql_cursor EE Keyword and Parameter Description SQL This is the name of the implicit SOL cursor FOUND This attribute yields TRUE if an INSERT UPDATE or DELETE statement affected one or more rows or a SELECT INTO statement returned one or more rows Otherwise it yields FALS GI ISOPEN This attribute always yields FALSE because Oracle closes the SQL cursor automatically after executing its associated SQL statement NOTFOUND This attribute is the logical opposite of FOUND It yields TRUE if an INSERT UPDATE or DELETE statement affected no rows or a SELECT INTO statement returned no rows Otherwise it yields FALSE H 11 144 PL SQL User s Guide and Reference SQL Cursor Usage Notes Examples Related Topics ROWCOUNT This attribute yields the number of rows affected by an INSERT UPDATI DELETE statement or returned by a SELECT INTO statement mi X o 5 You can use cursor attributes in procedural statements but not in SQL statements Before Oracle opens the SQL cursor automatically the implicit cursor attributes yield NULL The values of cursor attributes always refer to the most recently executed SQL statement wherever that statement appears It might be in a di
441. n model a community in which several people might share the same home We use the type modifier REF to declare refs which hold pointers to objects CREATE TYPE Person AS OBJECT first_name VARCHAR2 10 last_name VARCHAR2 15 birthday DATE home_address REF Home can be shared by family phone_number VARCHAR2 15 ss_number INTEGER mother REF Person family members refer to each other father REF Person y Notice how references from persons to homes and between persons model real world relationships You can declare refs as variables parameters fields or attributes And you can use refs as input or output variables in SOL data manipulation statements However you cannot navigate through refs Given an expression such as x attribute where x is a ref PL SQL cannot navigate to the table in which the referenced object is stored For example the following assignment is illegal DECLARE p_ref REF Person phone_no VARCHAR2 15 Object Types 9 29 Sharing Objects BEGIN phone_no p_ref phone_number illegal Instead you must use the operator DEREF to access the object For some examples see Using Operator DEREF on page 9 34 Forward Type Definitions You can refer only to schema objects that already exist In the following example the first CREATE TYPE statement is illegal because it refers to object type Department
442. n nulls to a variable defined as NOT NULL If you try PL SQL raises the predefined exception VALUE_ERROR Only the values TRUE and FALSE and the non value NULL can be assigned to a Boolean variable When applied to an expression the relational operators return a Boolean value So the following assignment is legal DECLARE out_of_range BOOLEAN BEGIN out_of_range salary lt minimum OR salary gt maximum As the next example shows you can assign the value of an expression to a specific field in a record DECLARE emp_rec emp ROWTYPE BEGIN mp_rec sal current_salary increase Language Elements 11 5 Assignment Statement Moreover you can assign values to all fields in a record at once PL SQL allows aggregate assignment between entire records if their declarations refer to the same cursor or table For example the following assignment is legal DECLARE emp_recl emp ROWTYPE emp_rec2 emp ROWTYPE dept_rec dept ROWTYPE BEGIN mp recl emp_rec2 The next assignment is illegal because you cannot use the assignment operator to assign a list of values to a record dept_rec 60 PUBLICITY LOS ANGELES Using the following syntax you can assign the value of an expression to a specific element in a collection collection_name index expression In the following example you assign the uppe
443. n the specification of emp_actions items declared in the body are restricted to use within the package Therefore PL SQL code outside the package cannot reference the variable number_hired Such items are termed private However items declared in the specification of emp_act ions such as the exception salary_missing are visible outside the package Therefore any PL SQL code can reference the exception salary_missing Such items are termed public When you must maintain items throughout a session or across transactions place them in the declarative part of the package body For example the value of number_hiredis retained between calls to hire_employee Remember however that the value of number_hiredis session specific If you must also make the items public place them in the package specification For example the constant minimum_balance declared in the specification of the package bank_transactions is available for general use Note When you call a packaged subprogram remotely the whole package is reinstantiated and its previous state is lost Overloading Recall from Chapter 7 that PL SQL allows two or more packaged subprograms to have the same name This option is useful when you want a subprogram to accept parameters that have different datatypes For example the following package defines two procedures named journalize CREATE PACKAGE journal_entries AS PROCEDURE journalize amount NUMBER trans_date VARCHA
444. n the final example you use SROWTYPE to define a packaged cursor CREATE PACKAGE emp _ actions AS Declare cursor specification CURSOR cl RETURN emp ROWTYPE END emp_actions CREATE PACKAGE BODY emp_actions AS Define cursor body CURSOR cl RETURN emp ROWTYPE IS SELECT FROM emp WHERE sal gt 3000 END emp_actions Aggregate Assignment A SROWTYPE declaration cannot include an initialization clause However there are two ways to assign values to all fields in a record at once First PL SQL allows aggregate assignment between entire records if their declarations refer to the same table or cursor For example the following assignment is legal DECLARE dept_recl deptSROWTYPE dept_rec2 dept SROWTYPE CURSOR cl IS SELECT deptno dname loc FROM dept dept_rec3 c1SROWTYPE BEGIN dept_recl dept_rec2 However because dept_rec2 is based on a table and dept_rec3 is based ona cursor the following assignment is illegal dept_rec2 dept_rec3 illegal 2 32 PL SQL User s Guide and Reference Declarations Second you can assign a list of column values to a record by using the SELECT or FETCH statement as the example below shows The column names must appear in the order in which they were defined by the CREATE TABLE or CREATE VIEW statement DECLARE
445. n2 THEN statement2 ELSE IF condition3 THEN statement3 END IF END IF END IF IF condit ionl THEN statement1 END IF ELSIF condition2 THEN statement2 ELSIF condition3 THEN statement3 These statements are logically equivalent but the first statement obscures the flow of logic whereas the second statement reveals it Iterative Control LOOP and EXIT Statements LOOP statements let you execute a sequence of statements multiple times There are three forms of LOOP statements LOOP WHILI LOOP E LOOP and FOR LOOP The simplest form of LOOP statement is the basic or infinite loop which encloses a sequence of statements between the keywords LOOP and END LOOP as follows LOOP sequence_of_statements END LOOP With each iteration of the loop the sequence of statements is executed then control resumes at the top of the loop If further processing is undesirable or impossible you can use an EXIT statement to complete the loop You can place one or more 3 6 PL SQL User s Guide and Reference EXIT WH1 EXIT statements anywhere inside a loop but nowhere outside a loop There are two forms of EXIT statements EXIT and EN EN Iterative Control LOOP and EXIT Statements EXIT The EXIT statement forces a loop to complete unconditionally When an EXIT statement is encountered the loop completes immediate
446. nals the end of a PL SQL block It must be the last keyword in a block Neither the END IF in an IF statement nor the END LOOP in a LOOP statement can substitute for the keyword END END does not signal the end of a transaction Just as a block can span multiple transactions a transaction can span multiple blocks The following PL SQL block declares several variables and constants then calculates a ratio using values selected from a database table available online in file examp11 DECLARE numerator NUMBER denominator NUMBER the_ratio NUMBER W OJ 11 12 PL SQL User s Guide and Reference Blocks lower_limit CONSTANT NUMBER 0 72 samp_num CONSTANT NUMBER 132 SELECT x y INTO numerator denominator FROM result_table WHERE sample_id samp_num the_ratio numerator denominator IF the_ratio gt lower_limit THEN INSERT INTO ratio VALUES samp_ num the_ratio INSERT INTO ratio VALUES samp_num 1 IF IT EXCEPTION WHEN ZERO DIVIDE THEN INSERT INTO ratio VALUES samp_num 0 COMMIT WHEN OTHERS THEN ROLLBACK n Q E Og o Z Related Topics Constants and Variables Exceptions Functions Procedures Language Elements 11 13 CLOSE Statement CLOSE Statement The CLOSE s
447. ncat concatenates two strings then returns the result If either string is null the result is also null As the following example shows concat uses OCIExtProcAllocCallMemory to allocate memory for the result string char concat ctx strl strl_i str2 str2 1 ret_i ret_1 OCIExtProcContext ctx char strl short strl_i char str2 short str2_i Ss Ss hort ret_i hort ret_l char tmp short len Check for null inputs if strl_i OCI_IND_NULL str2_i OCI_IND_NULL ret_i short OCI_IND_NULL PL SQL has no notion of a null ptr so return a zero byte string tmp OCIExtProcAllocCallMemory ctx 1 tmp 0 0 return tmp Allocate memory for result string including null terminator len strlen strl strlen str2 tmp OCIExtProcAllocCallMemory ctx len 1 strcpy tmp strl strcat tmp str2 Set null indicator and length ret_i short OCI_IND_NOTNULL ret_l len Return pointer which PL SQL frees later return tmp 10 18 PL SQL User s Guide and Reference Using Service Routines OCIExtProcRaiseExcp This service routine raises a predefined exception which must have a valid Oracle error number in the range 1 32767 After doing any necessary cleanup the external procedure must return immediately No values are assigned to OUT or IN OUT parameters The C prototype for this function follows
448. nce IF Statement IF Statement Syntax The IF statement lets you execute a sequence of statements conditionally Whether the sequence is executed or not depends on the value of a Boolean expression For more information see Conditional Control IF Statements on page 3 2 if_statement lt FO Keyword and Parameter Description boolean_expression This is an expression that yields the Boolean value TRUE FALSE or NULL It is associated with a sequence of statements which is executed only if the expression yields TRUE THEN This keyword associates the Boolean expression that precedes it with the sequence of statements that follows it If the expression yields TRUE the associated sequence of statements is executed ELSIF This keyword introduces a Boolean expression to be evaluated if the expression following IF and all the expressions following any preceding ELSIFs yield FALS or NULL GI Language Elements 11 85 IF Statement ELSE If control reaches this keyword the sequence of statements that follows it is executed Usage Notes There are three forms of IF statements IF THEN IF THEN ELSE and IF THEN ELSIF The simplest form of IF statement associates a Boolean expression with a sequence of statements enclosed by the keywords THEN and END IF The sequence of statements is executed only if the expression yields TRUE If the expression yields FALSE or NULL th
449. nce CONSTANT NUMBER 100 00 Declare externally callable procedures PROCEDURE apply_transactions PROCEDURE enter_transaction acct BER kind CHAR amount BER E za D bank_transactions CREATE PACKAGE BODY bank_transactions AS Declare global variable to hold transaction status new_status VARCHAR2 70 Unknown Use forward declarations because apply_transactions calls credit_account and debit_account which are not yet declared when the calls are made PROCEDURE credit_account acct NUMBER credit REAL PROCEDURE debit_account acct BER debit REAL Fully define procedures specified in package PROCEDURE apply transactions IS Apply pending transactions in transactions table to accounts table Use cursor to fetch rows CURSOR trans_cursor IS SELECT acct_id kind amount FROM transactions Packages 8 11 Some Examples WHERE status Pending ORDER BY time_tag FOR UPDATE OF status to lock rows Gl WD BEGIN FOR trans IN trans_cursor LOOP IF trans kind D THEN debit_account trans acct_id trans amount SIF trans kind C THEN credit_account trans acct_id trans amount E SE new_status Rejected END IF UPDATE transactions SET status new_status
450. nce an element you specify its subscript using the syntax collection_name subscript where subscript is an expression that yields a positive integer For nested tables the integer must lie in the range 1 2147483647 For varrays the integer must lie in the range 1 maximum_size You can reference a collection in all expression contexts In the following example you reference an element in nested table names DECLARE YPE Roster IS TABLE OF VARCHARZ2 15 names Roster Roster J Hamil D Caruso R Singh 1 BINARY_INTEGER BEGIN IF names i J Hamil THEN The next example shows that you can reference the elements of a collection in subprogram calls DECLARE YPE Roster IS TABLE OF VARCHARZ2 15 names Roster Roster J Hamil D Caruso R Singh 1 BINARY_INTEGER BEGIN verify_name names 1 call procedure When calling a function that returns a collection you use the following syntax to reference elements in the collection function name parameter_list subscript Collections and Records 4 11 Assigning and Comparing Collections For example the following call references the third element in the varray returned by function new_hires DECLARE YPE Staff IS VARRAY 20 OF Employee staffer Employee FUNCTION new_hires hiredate
451. ncnnnncerarrcararorincncnoss 9 25 Accessing Attributes iccc cicteccs sisd cates iia aii ii e ei aen a a chub AEE S i O a a r 9 25 10 Calling Constructors and Methods ooooioicicicococicnononnonenconononinnoninnonononconinnono ronca nnonono ron cnnnonano ran cn anno 9 26 Passing Parameters to a Constructor seened tise tere A e i taae 9 27 Calling Methods iiinn e a a E E eB eels NRE 9 27 Sharing ObjectS unimarc da 9 28 Using Refs 0 A AE E aa 9 29 Forward Type Definitions oconoconcocinnnonoononrnenenecannnnenennrnrannnnnnnnnnnnnnnorananannn nara ee erine TEP Sietni 9 30 Manipulating ObjectS oonioinicinoniononononncnnonononanananononananananononononanononononononononononon aran ononononararonononenos 9 31 Selecting Object vias aiii pida oia 9 32 Inserting Objects gris coi cio AA esa ici rata cis 9 36 Updating Objects ci ii iO TS 9 38 Deleting Objects ciar AAA e OE AAA AAA 9 38 External Procedures What Is an External Procedure cocoooninnnncicnnoninonicononononononononanononononononononononononononon anar E E 10 2 Creating an External Proceduresssnisesssin oeeie E E E E E ronca anno 10 2 Registering an External Procedure ooooicicicinononionononnoninnenonennnenconanonin cn nnnnano ronca ononano non co cacao ran cn anno 10 3 Understanding the EXTERNAL Clause ccccccccccssssesescenenesesescsneneseseeceseseseecanenesesesnaneneneees 10 4 O S Eie AEE edhe t aa Tat Abaya E tds 10 5 Calling an External Procedure ii ica 10 5 NI 1
452. nd subscripts when stored in the database You can define collection types in the declarative part of any PL SQL block subprogram or package In SQL collection types can be CREATEd and stored in the database Collections follow the usual scoping and instantiation rules In a package collections are instantiated when you first reference the package and cease to exist when you end the database session In a block or subprogram local collections are instantiated when you enter the block or subprogram and cease to exist when you exit Until you initialize it a collection is atomically null that is the collection itself is null not its elements To initialize a collection you use a constructor which is a system defined function with the same name as the collection type This function constructs a collection from the elements passed to it Because collections can be atomically null they can be tested for nullity However collections cannot be compared for equality or inequality This restriction also applies to implicit comparisons For example collections cannot appear in a DISTINCT GROUP BY or ORDER BY list Collections can store instances of an object type and conversely can be attributes of an object type Also nested tables and varrays can be passed as parameters So you can use them to move collections of data into and out of database tables or between client side applications and stored subprograms When
453. ndled exception the host environment determines what is rolled back If you exit a stored subprogram with an unhandled exception PL SQL does not assign values to OUT parameters Also PL SQL does not roll back database work done by the subprogram Ending Transactions A good programming practice is to commit or roll back every transaction explicitly Whether you issue the commit or rollback in your PL SQL program or in the host environment depends on the flow of application logic If you neglect to commit or roll back a transaction explicitly the host environment determines its final state For example in the SOL Plus environment if your PL SQL block does not include a COMMIT or ROLLBACK statement the final state of your transaction depends on what you do after running the block If you execute a data definition data control or COMMIT statement or if you issue the EXIT DISCONNECT or QUIT command Oracle commits the transaction If you execute a ROLLBACK statement or abort the SOL Plus session Oracle rolls back the transaction In the Oracle Precompiler environment if your program does not terminate normally Oracle rolls back your transaction A program terminates normally when it explicitly commits or rolls back work and disconnects from Oracle using the RELEASE parameter as follows EXEC SQL COMMIT WORK RELEASE Interaction with Oracle 5 49 Processing Transact
454. ndler as follows DECLARE err_num BER err_msg VARCHAR2 100 BEGIN EXCEPTION WHEN OTHERS THEN err num SQLCODE err_msg SUBSTR SQLERRM 1 100 DBMS_OUTPUT PUT_LINE TO_CHAR err_num err msg T The string function SUBSTR ensures that a VALUE_ERROR exception for truncation is not raised when you assign the value of SOLERRM to err_msg Alternatively the program can use pragma EXCEPTION_INIT to map the error numbers returned by raise_application_error to named exceptions as the following example shows DECLARE stack_overflow EXCEPTION stack_underflow EXCEPTION PRAGMA EXCEPTION_INIT stack_overflow 20101 PRAGMA EXCEPTION_INIT stack_underflow 20102 BEGIN EXCEPTION WHEN stack_overflow THEN 9 16 PL SQL User s Guide and Reference Defining Object Types Object Type Ticket_Booth Consider a chain of low budget triplex movie theatres Each theatre has a ticket booth where tickets for three different movies are sold All tickets are priced at 2 50 Periodically ticket receipts are collected and the stock of tickets is replenished Before defining an object type that represents a ticket booth we must consider the data and operations needed For a simple ticket booth the object type needs attributes for the ticket
455. nds n copies of the ith element to a collection Language Elements 11 17 Collection Methods Usage Notes EXTEND operates on the internal size of a collection So if EXTEND encounters deleted elements it includes them in its tally FIRST LAST FIRST and LAST return the first and last smallest and largest index numbers in a collection If the collection is empty FIRST and LAST return NULL If the collection contains only one element FIRST and LAST return the same index number For varrays FIRST always returns 1 and LAST always equals COUNT For nested tables normally LAST equals COUNT But if you delete elements from the middle of a nested table LAST is larger than COUNT LIMIT For nested tables which have no maximum size LIMIT returns NULL For varrays LIMIT returns the maximum number of elements that a varray can contain which you specify in its type definition NEXT PRIOT PRIOR n returns the index number that precedes index n in a collection NEXT n returns the index number that succeeds index n If n has no predecessor PRIOR n returns NULL Likewise if n has no successor NEXT n returns NULL TRIM This procedure has two forms TRIM removes one element from the end of a collection TRIM n removes n elements from the end of a collection If n is greater than COUNT TRIM n raises SUBSCRIPT_BEYOND_COUNT TRIM operates on the internal
456. needs If not you can provide more information using the PARAMETERS clause which lets you specify a non default external datatypes a the current and or maximum length of a parameter a null not null indicators for parameters a character set IDs and forms the positions of parameters in the list a how IN parameters are passed by value or by reference For every formal parameter there must be a corresponding parameter in the PARAMETERS clause If you include the WITH CONTEXT clause you must specify the parameter CONTEXT which shows the position of the context pointer in the parameter list Also if the external routine is a function you must specify the parameter RETURN in the last position Specifying Properties You can also use the PARAMETERS clause to pass additional information about PL SQL formal parameters and function results to an external procedure You do that by specifying the following properties INDICATOR LENGTH MAXLEN C C HARSETID HARSETFORM 10 12 PL SQL User s Guide and Reference Passing Parameters to an External Procedure Table 10 3 shows the external datatypes PL SQL datatypes and PL SQL parameter modes allowed for a given property Notice that MAXLEN cannot be applied to an IN parameter Table 10 3 Property Datatype Mappings C Parameter PL SQL Param
457. ng the function in a package You can define functions in a package body without declaring their specifications in the package specification However such functions can be called only from inside the package Inside a function an IN parameter acts like a constant Therefore it cannot be assigned a value An OUT parameter acts like an uninitialized variable So its value cannot be assigned to another variable or reassigned to itself An IN OUT parameter acts like an initialized variable Therefore it can be assigned a value and its value can be assigned to another variable For summary information about the parameter modes see Table 7 1 on page 7 15 Avoid using the OUT and IN OUT modes with functions The purpose of a function is to take zero or more parameters and return a single value Also functions should be free from side effects which change the values of variables not local to the subprogram Functions can be defined using any Oracle tool that supports PL SQL However to become available for general use functions must be CREATEd and stored in an Oracle database You can issue the CRI EATE FUNCTION statement interactively from SOL Plus or Enterprise Manager For the full syntax of the CREATE FUNCTION statement see Oracle8 SQL Reference Example The following function returns the balance of a specified bank account E Related Topics RETURN acct_bal ID balance
458. nnncnnonnennrornnnennnanannnnenararannnnnnnraos 6 17 Using SOLCODE and SQLERRM oii ss ccesecs tevcesciven ii dia de cta dele ove 6 18 Unhandled Exc s oni i e o EN a REE E E EE E E A A E EES 6 19 Useful Techniques rarene aia rc ir 6 20 Continuing after an Exception Is Raised oooonononinnoninnnoncononcnenercnronnncnrornnnenncnnnrnnnrnoraranannnnnraros 6 20 Retrying a Transaction cccccccceseccceeeseseccscsesesesescscsesesesescscscsesesesesescseseseseseseseseseseeeseseseseseeenees 6 21 Using Locator Variables cccccccccccscsseesesesseesescececesescsssnensseseseenesesescecesessscsansneseseseeneneseseeney 6 22 7 Subprograms What Are Subprogram cccccccccecccsesesescscscsesesescsesesesesescsesesesesescsesesesesescsesssesesescsesesesesesees 7 2 Advantages of Subprogram ccccccccccssesesccscesesescscsesesesescsesesesesescsesesesesescsesesesesescseseseseseseess 7 3 Proce AUTE A ec e ee AA ied eh ae 7 3 Functions A A elie Sa certian as 7 5 ReStrictlonicicveccei ate nt be oie clean iene eee tater Pa T 7 6 RETURN Statements 4 ts 805 cdi dard tl danita 7 7 Declaring Subprogram cece eeaeee R E a e A a ail 7 8 Forward Declaration e 7 8 Stored SUbPrOsramm Senee iscsecssschardeetasashsssrnceedeaslateononend cusnsvondodbassehinasievedpracehdoseteadaslaseeseess 7 10 Actual versus Formal Parameters ccccccsccssessssscesseescescecsecssecsecssesasceassaecessesesesseeseseeeeeeseeaes 7 11 Positional and Named Nota
459. not specify the file extension because it defaults to sq1 For example the following commands are equivalent WRAP INAME mydir myfile WRAP INAME mydir myfile sql However you can specify a different file extension as the following example shows WRAP INAME mydir myfile src D 2 PL SQL User s Guide and Reference Running the PL SQL Wrapper Optionally the WRAP command takes a second argument which is ONAME output_file where out put_file is the path and name of the Wrapper output file You need not specify the output file because its name defaults to that of the input file and its extension defaults to p1b PL SQL binary For example the following commands are equivalent WRAP INAME mydir myfile WRAP INAME mydir myfile sql ONAME mydir myfile plb However you can use the option ONAME to specify a different file name and extension as the following example shows WRAP INAME mydir myfile ONAME yourdir yourfile obj Input and Output Files The input file can contain any combination of SQL statements However the PL SQL Wrapper wraps only the following CREATE statements which define PL SQL packages and stand alone subprograms CREATE OR REPLACE PACKAGE CREATE OR REPLACE PACKAGE BODY CREATE OR REPLACE FUNCTION CREATE OR REPLACE PROCEDURE All othe
460. ns memory allocation and the user environment The WITH CONTEXT clause specifies that a context pointer will be passed to the external procedure For example if you write the following PL SQL function CREATE FUNCTION get_num x IN REAL RETURN BINARY _INTEGER AS EXTERNAL LIBRARY c_utils AME c_get_num ANGUAGE C WITH CONTEXT PARAMETERS CONTEXT x BY REF RETURN INDICATOR then the C prototype would be int c_get_num OCIExtProcContext with_context float x short retind The context data structure is opaque to the external procedure but is available to service routines called by the external procedure If you also include the PARAMETERS clause you must specify the parameter CONTEXT which shows the position of the context pointer in the parameter list If you omit the PARAMETERS clause the context pointer is the first parameter passed to the external procedure 10 16 PL SQL User s Guide and Reference Using Service Routines Using Service Routines When called from an external procedure a service routine can raise exceptions allocate memory and get OCI Oracle Call Interface handles for callbacks to the server To use the functions you must specify the WITH CONTEXT clause which lets you pass a context structure to the external procedure The context structure is declared in header file ociextp
461. ns is local to your database schema and global to the package So the declared items are accessible from your application and from anywhere in the package Figure 8 2 illustrates the scoping Figure 8 2 Package Scope procedure package spec package body function procedure schema function package spec package body function procedure other objects The specification lists the package resources available to applications All the information your application needs to use the resources is in the specification For example the following declaration shows that the function named fac takes one argument of type INTEGER and returns a value of type INTEGER FUNCTION fac n INTEGER RETURN INTEGER returns n Packages 8 5 The Package Specification That is all the information you need to call the function You need not consider the underlying implementation of fac whether it is iterative or recursive for example Only subprograms and cursors have an underlying implementation or definition So if a specification declares only types constants variables and exceptions the package body is unnecessary Consider the following bodiless package a bodiless package CREATE PACKAGE trans_data AS YPE TimeRec IS RECORD minutes SMALLINT hours SMALLINT YPE TransRec IS RECORD category VARCHAR2 account INTEGER amount REAL time TimeRec minimum_balance CONSTANT REAL 10
462. nsaction you might want to retry it The technique you use is simple First encase the transaction in a sub block Then place the sub block inside a loop that repeats the transaction Before starting the transaction you mark a savepoint If the transaction succeeds you commit then exit from the loop If the transaction fails control transfers to the exception handler where you roll back to the savepoint undoing any changes then try to fix the problem Consider the example below When the exception handler completes the sub block terminates control transfers to the LOOP statement in the enclosing block the sub block starts executing again and the transaction is retried You might want to use a FOR or WHILE loop to limit the number of tries DECLARE name CHAR 20 ansl CHAR 3 ans2 CHAR 3 ans3 CHAR 3 suffix NUMBER 1 BEGIN LOOP could be FOR i IN 1 10 LOOP to allow ten tries BEGIN sub block begins SAVEPOINT start_transaction mark a savepoint Remove rows from a table of survey results DELETE FROM results WHERE answerl NO Add a survey respondent s name and answers INSERT INTO results VALUES name ansl ans2 ans3 raises DUP_VAL_ON_INDEX if two respondents have the same name because there is a unique index on the name column COMMIT EXIT EXCEPTION WHEN DUP_VAL_ON_INDEX TH
463. nt retrieves rows one at a time from the result set of a multi row query The statement syntax follows FETCH cursor_variable_name host_cursor_variable_name INTO variable_name variable_name record_name In the next example you fetch rows from the cursor variable emp_cv into the user defined record emp_rec LOOP Fetch from cursor variable FETCH emp_cv INTO emp_rec EXIT WHEN emp_cvSNOTFOUND exit when last row is fetched process data record END LOOP Any variables in the associated query are evaluated only when the cursor variable is opened To change the result set or the values of variables in the query you must reopen the cursor variable with the variables set to their new values However you can use a different INTO clause on separate fetches with the same cursor variable Each fetch retrieves another row from the same result set PL SQL makes sure the return type of the cursor variable is compatible with the INTO clause of the FETCH statement For each column value returned by the query associated with the cursor variable there must be a corresponding type compatible field or variable in the INTO clause Also the number of fields or variables must equal the number of column values Otherwise you get an error The error occurs at compile time if the cursor variable is strongly typed or at run time if it is weakly typed At run time PL SQL raises the predefined exception
464. ntax 11 96 LUB group function 5 3 maintainability 7 3 map method 9 10 MAX group function 5 3 maximum length CHAR value 2 14 identifier 2 5 LONG RAW value 2 15 LONG value 2 15 NCHAR value 2 18 NVARCHAR2 value 2 19 Index 8 Oracle error message 6 18 RAW value 2 15 VARCHAR value 2 16 maximum precision 2 12 maximum size LOB 2 19 MAXLEN property 10 14 membership test 2 46 method COUNT 4 22 DELETE 4 26 EXISTS 4 22 EXTEND 4 24 FIRST 4 23 LAST 4 23 LIMIT 4 22 map 9 10 NEXT 4 23 object 9 3 9 8 order 9 10 PRIOR 4 23 TRIM 4 25 method calls chaining 9 27 method collection 4 21 MIN group function 5 3 MINUS set operator 5 6 mixed notation 7 12 MLSLABEL datatype 2 22 mode parameter IN 7 13 IN OUT 7 14 OUT 7 13 modularity 1 11 7 3 8 4 multi line comment 2 9 mutual recursion 7 26 N name cursor 5 10 qualified 2 34 savepoint 5 48 variable 2 35 NAME clause 10 4 name resolution 2 35 E 1 named notation 7 12 naming conventions 2 34 national character set 2 18 National Language Support NLS 2 17 NATURAL subtype 2 12 NATURALN subtype 2 12 NCHAR datatype 2 18 NCHAR_CS value 2 28 NCLOB datatype 2 21 nested table 4 2 manipulating 4 14 versus index by table 4 3 nesting block 1 3 FOR loop 3 14 object 9 7 record 4 29 network traffic reducing 1 22 new features A 1 NEXT collection method 4 23 NEXTVAL pseudocolumn 5 4 n
465. nto a Boolean variable Expressions and Comparisons Expressions are constructed using operands and operators An operand is a variable constant literal or function call that contributes a value to an expression An example of a simple arithmetic expression follows EXA 25 Unary operators such as the negation operator operate on one operand binary operators such as the division operator operate on two operands PL SQL has no ternary operators The simplest expressions consist of a single variable which yields a value directly PL SOL evaluates finds the current value of an expression by combining the values of the operands in ways specified by the operators This always yields a single value and datatype PL SQL determines the datatype by examining the expression and the context in which it appears Fundamentals 2 41 Expressions and Comparisons Operator Precedence The operations within an expression are done in a particular order depending on their precedence priority Table 2 2 shows the default order of operations from first to last top to bottom Table 2 2 Order of Operations Operator Operation NOT exponentiation logical negation identity negation El multiplication division o addition subtraction concatenation t lt gt lt gt comparison IS NULL LIKE BEIWEEN IN AND conjunction OR inclusion Operators with higher precedence are applied fi
466. nvironment Omitting the exception name in a RAISE statement which is allowed only in an exception handler reraises the current exception When a parameterless RAISE statement executes in an exception handler the first block searched is the enclosing block not the current block 11 126 PL SQL User s Guide and Reference RAISE Statement Example In the following example you raise an exception when an inventoried part is out of stock IF quantity_on_hand 0 THEN RAISE out_of_stock END IF Related Topics Exceptions Language Elements 11 127 Records Records Syntax Records are items of type RECORD Records have uniquely named fields that can store data values of different types For more information see What Is a Record on page 4 28 record_type_definition Au toto NOT NULL field_declaration gt expression record_declaration record_name Y type_name 7 Keyword and Parameter Description record_type_name This identifies a user defined type specifier which is used in subsequent declarations of records NOT NULL This constraint prevents the assigning of nulls to a field At run time trying to assign a null to a field defined as NOT NULL raises the predefined exception VALUE_ERROR The constraint NOT NULL must be followed by an initialization clause datatype This is a type specifier For the syntax of datatype see Constants
467. o PL SQL Moreover application development tools such as Oracle Forms and Oracle Reports which have a PL SQL engine can use cursor variables entirely on the client side The Oracle server also has a PL SQL engine So you can pass cursor variables back and forth between an application and server via remote procedure calls RPCs And if you have a PL SQL engine on the client side calls from client to server impose no restrictions For example you can declare a cursor variable on the client side open and fetch from it on the server side then continue to fetch from it back on the client side Mainly you use cursor variables to pass query result sets between PL SQL stored subprograms and various clients Neither PL SQL nor any of its clients owns a result set they simply share a pointer to the query work area in which the result set is stored For example an OCI client Oracle Forms application and Oracle server can all refer to the same work area REF CURSOR types can be strong restrictive or weak nonrestrictive A strong REF CURSOR type definition specifies a return type but a weak definition does not Strong REF CURSOR types are less error prone because the PL SQL compiler lets you associate a strongly typed cursor variable only with type compatible queries However weak REF CURSOR types are more flexible because the compiler lets you associate a weakly typed cursor variable with any query Once you define a REF CUR
468. o defer the definition of object type Address Moreover the incomplete type Customer can be made available to other application developers for use in refs Manipulating Objects You can use an object type in the CREATE TABLE statement to specify the datatype of a column Once the table is created you can use SQL statements to insert an object select its attributes call its methods and update its state In the SQL Plus script below the INSERT statement calls the constructor for object type Rational then inserts the resulting object The SELECT statement retrieves the value of attribute num The UPDATE statement calls member method reciprocal which returns a Rational value after swapping attributes num and den Notice that a table alias is required when you reference an attribute or method For an explanation see Appendix E CREATE TABLE numbers rn Rational INSERT INTO numbers rn VALUES Rational 3 62 inserts 3 62 SELECT n rn num INTO my_num FROM numbers n WHERE returns 3 UPDATE numbers n SET n rn n rn reciprocal WHERE yields 62 3 When you instantiate an object this way it has no identity outside the database table However the object type exists independently of any table and can be used to create objects in other ways In the next example you create a table that stores objects of t
469. o get acquainted with PL SQL is to look at a sample program The program below processes an order for tennis rackets First it declares a variable of type NUMBER to store the quantity of tennis rackets on hand Then it retrieves the quantity on hand from a database table named inventory If the quantity is greater than zero the program updates the table and inserts a purchase record into another table named purchase_record Otherwise the program inserts an out of stock record into the purchase_record table available online in file exampl DECLARE qty_on hand NUMBER 5 BEGI SELECT quantity INTO qty_on hand FROM inventory WHERE product TENNIS RACKET FOR UPDATE OF quantity IF qty_on hand gt 0 THEN check quantity UPDATE inventory SET quantity quantity 1 WHERE product TENNIS RACKET INSERT INTO purchase_record VALUES Tennis racket purchased SYSDATE INSERT INTO purchase_record VALUES Out of tennis rackets SYSDATE With PL SQL you can use SQL statements to manipulate Oracle data and flow of control statements to process the data Moreover you can declare constants and variables define procedures and functions and trap runtime errors Thus PL SQL combines the data manipulating power of SQL with the data processing power of procedural languages Block Structu
470. ody must have a RETURN claus SELECT statement and the same RETURN clause as the cursor specification Also the number and datatypes of select items in the SELECT statement must match the e Packaged cursors increase flexibility For instance you can change the cursor body in the last example as follows without having to change the cursor specification CREATE PACKAGE BODY emp_actions AS Define cursor body CURSOR cl RETURN emp ROWTYPE IS SELECT FROM emp WHERE deptno 20 new WHERE clause END emp_actions Interaction with Oracle 5 15 Using Cursor FOR Loops Using Cursor FOR Loops In most situations that require an explicit cursor you can simplify coding by using a cursor FOR loop instead of the OPEN FETCH and CLOSE statements A cursor FOR loop implicitly declares its loop index as a SROWTYPE record opens a cursor repeatedly fetches rows of values from the result set into fields in the record and closes the cursor when all rows have been processed Consider the PL SQL block below which computes results from an experiment then stores the results in a temporary table The FOR loop index c1_recis implicitly declared as a record Its fields store all the column values fetched from the cursor c1 Dot notation is used to reference individual fields available online in file examp7 DECLARE result t
471. of Intermediate SQL a Entry SQL a subset of Transitional SQL A conforming SQL implementation must support at least Entry SQL PL SQL fully supports Entry SQL Using DDL and Dynamic SQL This section explains why PL SQL does not support SQL data definition language DDL or dynamic SQL then shows how to solve the problem Efficiency versus Flexibility Before a PL SQL program can be executed it must be compiled The PL SQL compiler resolves references to Oracle schema objects by looking up their definitions in the data dictionary Then the compiler assigns storage addresses to program variables that will hold Oracle data so that Oracle can look up the addresses at run time This process is called binding Interaction with Oracle 5 7 Using DDL and Dynamic SQL How a database language implements binding affects runtime efficiency and flexibility Binding at compile time called static or early binding increases efficiency because the definitions of schema objects are looked up then not at run time On the other hand binding at run time called dynamic or late binding increases flexibility because the definitions of schema objects can remain unknown until then Designed primarily for high speed transaction processing PL SQL increases efficiency by bundling SQL statements and avoiding runtime compilation Unlike SQL which is compiled and executed statement by statement at run time late binding PL SQL is processed into machine
472. of a stack uses an integer array Integers are stored in array elements with one end of the array representing the top of the stack CREATE TYPE IntArray AS VARRAY 25 OF INTEGER CREATE TYPE Stack AS OBJECT max_size INTEGER top INTEGER position IntArray EMBER PROCEDURE initialize EMBER FUNCTION full RETURN BOOLEAN ER FUNCTION empty RETURN BOOLI ER PROCEDURE push n IN INTEG ER PROCEDURE pop n OUT INTEGE 7 z4 x T B B B B CREATE TYPE BODY Stack AS BER PROCEDURE initialize IS fill stack with nulls Ww ira Q H top 0 Call constructor for varray and set element 1 to NULL position IntArray NULL max_Size position LIMIT use varray size constraint 25 position EXTEND max_size 1 1 copy element 1 into 2 25 ID initialize E T EMBER FUNCTION full RETURN BOOLEAN IS return TRUE if stack is full BEGI 11 108 PL SQL User s Guide and Reference Object Types RETURN top max_size END full EMBER FUNCTION empty RETURN BOOLEAN IS return TRUE if stack is empty BEGIN RETURN top 0 T ea o D g Es EMBER PROCED
473. of values The query can reference bind variables and PL SQL variables parameters and functions but cannot be FOR UPDATE The syntax of select_statement is similar to the syntax for select_into_statement defined in SELECT INTO Statement on page 11 139 except that select_statement cannot have an INTO clause Language Elements 11 113 OPEN FOR Statement Usage Notes Examples You can declare a cursor variable in a PL SQL host environment such as an OCI or Pro C program To open the host cursor variable you can pass it as a bind variable to an anonymous PL SQL block You can reduce network traffic by grouping OPEN FOR statements For example the following PL SQL block opens five cursor variables in a single round trip anonymous PL SQL block in host environment BEGIN OPEN emp_cv FOR SELECT FROM emp OPEN dept_cv FOR SELECT FROM dept OPEN grade_cv FOR SELECT FROM salgrade OPEN pay_cv FOR SELECT FROM payroll OPEN ins_cv FOR SELECT FROM insurance END Other OPEN FOR statements can open the same cursor variable for different queries You need not close a cursor variable before reopening it When you reopen a cursor variable for a different query the previous query is lost Unlike cursors cursor variables do not take parameters No flexibility is lost however because you can pass whole queries not just parameters to a cursor variable
474. on cursor_variable_declaration di exception_declaration object_declaration record_declaration variable_declaration statement assignment_statement exit_statement goto_statement if_statement lt lt gt loop_statement null_statement plsql_block raise_statement return_statement sql_statement Lal 11 8 PL SQL User s Guide and Reference Blocks sql_statement i close_statement commit_statement delete_statement fetch_statement insert_statement lock_table_statement iit open_statement open for_statement rollback_statement savepoint_statement select_statement set_transaction_statement update_statement i Keyword and Parameter Description label_name This is an undeclared identifier that optionally labels a PL SQL block If used label_name must be enclosed by double angle brackets and must appear at the beginning of the block Optionally 1abe1_name can also appear at the end of the b lock J A global identifier declared in an enclosing block can be redeclared in a sub block in which case the local declaration prevails and the sub block cannot reference the global identifier To reference the global identifier you must use a block label to qualify the reference as the following example shows lt lt outer gt gt D ECLARE Bl x INTEGER EGI Y one gt Language Elements 11 9
475. on ORDER BY time_tag ACCOUNT_ID O NEW VALUE STATUS IME_TAG 3 599 18 NOV 88 6 20099 18 NOV 88 Sd 18 NOV 88 7 u 1599 18 NOV 88 1 1 399 18 NOV 88 9d 18 NOV 88 10 x 18 NOV 88 7 records selected Sample Programs B 15 Sample 4 Batch Transaction Processing PL SQL Block available online in file sample4 DECLARE CURSOR cl IS SELECT account_id oper_type new_value FROM action ORDER BY time_tag FOR UPDATE OF status BEGIN FOR acct IN cl LOOP process each row one at a time acct oper_type upper acct oper_type i K Process an UPDATE If the account to be updated doesn t exist create a new account Jas zy IF acct oper_type U THEN UPDATE accounts SET bal acct new_valu WHERE account_id acct account_id IF SOLSNOTFOUND THEN account didn t exist Create it INSERT INTO accounts VALUES acct account_id acct new_value UPDATE action SET status Update ID not found Value inserted WHERE CURRENT OF cl UPDATE action SET status Update Success WHERE CURRENT OF c1 END IF aa EJ Process an INSERT If the account already exists do an update of the account aA instead RA pE xJ ELSIF acct oper_type I THEN BEGIN INSERT INTO accounts VALUES acct acc
476. on is an ordered group of elements all of the same type for example the grades for a class of students Each element has a unique subscript that determines its position in the collection PL SQL offers two kinds of collections nested tables and varrays short for variable size arrays Collections work like the arrays found in most third generation programming languages However collections can have only one dimension and must be indexed by integers In some languages such as Ada and Pascal arrays can have multiple dimensions and can be indexed by enumeration types Collections can store instances of an object type and conversely can be attributes of an object type Also collections can be passed as parameters So you can use them to move columns of data into and out of database tables or between client side applications and stored subprograms Furthermore you can define collection types in a PL SQL package then use them programmatically in your applications Note To use nested tables and varrays you must have the Oracle8 Enterprise Edition and the Objects Option For more information see Getting to Know Oracle and the Oracle8 Enterprise Edition Nested Tables Items of type TABLE are called nested tables Within the database they can be viewed as one column database tables Oracle stores the rows of a nested table in no particular order But when you retrieve the nested table into a PL SQL variable the rows are
477. ons 2 46 operators 2 44 5 6 compilation using the PL SQL Wrapper D 1 compiler 5 7 component selector 1 6 composite type 2 10 compound symbol 2 4 concatenation operator 2 46 treatment of nulls 2 50 concurrency 5 44 conditional control 3 2 constant declaring 2 29 syntax 11 29 constraint NOT NULL 2 30 where not allowed 2 23 7 4 constructor collection 4 9 object 9 12 control structure 3 2 conditional 3 2 iterative 3 6 sequential 3 15 conventions naming 2 34 conversion function when needed 2 26 conversion datatype 2 25 correlated subquery 5 14 COUNT collection method 4 22 COUNT group function 5 3 CREATE LIBRARY statement 10 3 CURRENT OF clause 5 52 current row 1 5 CURRVAL pseudocolumn 5 4 cursor 1 5 5 9 analogy 1 5 closing 5 13 declaring 5 10 explicit 5 9 fetching from 5 12 implicit 5 14 opening 5 11 packaged 5 15 parameterized 5 11 RETURN clause 5 15 scope rules 5 10 syntax 11 45 cursor attribute FOUND 5 38 5 42 ISOPEN 5 38 5 42 NOTFOUND 5 39 ROWCOUNT 5 39 5 43 implicit 5 42 syntax 11 33 values 5 40 cursor FOR loop 5 16 passing parameters to 5 18 Index 3 cursor variable 5 18 assignment 5 34 closing 5 27 declaring 5 20 fetching from 5 26 opening 5 22 restrictions 5 37 syntax 11 38 using to reduce network traffic 5 33 CURSOR_ALREADY_OPEN exception 6 5 D dangling ref 9 34 data abstraction 9 2 data encapsulatio
478. ons of your own in the declarative part of any PL SQL block or subprogram In the executable part you check for the condition that needs special attention If you find that the condition exists you execute a RAISE statement In the example below you compute the bonus earned by a salesperson The bonus is based on salary and commission So if the commission is null you raise the exception comm_missing DECLARE comm missing EXCEPTION declare exception BEGIN IF commission IS NULL THEN RAISE com missing raise exception ELSE bonus salary 0 10 commission 0 15 END IF EXCEPTION WHEN comm_missing THEN process error Overview 1 17 Architecture Architecture The PL SQL runtime system is a technology not an independent product Think of this technology as an engine that executes PL SQL blocks and subprograms The engine can be installed in an Oracle server or in an application development tool such as Oracle Forms or Oracle Reports So PL SQL can reside in two environments a the Oracle server a Oracle tools These two environments are independent PL SQL might be available in the Oracle server but unavailable in tools or the other way around In either environment the PL SQL engine accepts as input any valid PL SQL block or subprogram Figure 1 4 shows the PL SQL engine processing an anonymous block The engine executes procedural statem
479. or FALSE if the last fetch failed to return a row Until a SQL statement is executed SQLSFOUND yields NULL Thereafter it yields TRUE if the statement affected any rows or FALSE if it affected no rows ISOPEN This is a cursor attribute which can be appended to the name of a cursor or cursor variable If a cursor is open cursor_name ISOPEN yields TRUE otherwise it yields FALSE Oracle automatically closes the implicit SOL cursor after executing its associated SQL statement so SQL ISOPEN always yields FALSE NOTFOUND This is a cursor attribute which can be appended to the name of a cursor or cursor variable Before the first fetch from an open cursor cursor_namesNOTFOUND yields NULL Thereafter it yields FALSE if the last fetch returned a row or TRUE if the last fetch failed to return a row Until a SOL statement is executed SOLSNOTFOUND yields NULL Thereafter it yields FALSE if the statement affected any rows or TRUE if it affected no rows ROWCOUNT This is a cursor attribute which can be appended to the name of a cursor or cursor variable When a cursor is opened SROWCOUNT is zeroed Before the first fetch cursor_namesROWCOUNT yields 0 Thereafter it yields the number of rows fetched so far The number is incremented if the latest fetch returned a row Until a SOL statement is executed SQLSROWCOUNT yields NULL Thereafter it yields the number of rows affected by the stat
480. or each item lets you treat the data as a logical unit Consider the following example DECLARE YPE TimeRec IS RECORD minutes SMALLINT hours SMALLINT YPE MeetingTyp IS RECORD day DATE time TimeRec nested record place VARCHAR2 20 purpose VARCHAR2 50 Notice that you can nest records That is a record can be the component of another record Object Types In PL SQL object oriented programming is based on object types An object type encapsulates a data structure along with the functions and procedures needed to manipulate the data The variables that form the data structure are called attributes The functions and procedures that characterize the behavior of the object type are called methods Object types reduce complexity by breaking down a large system into logical entities This allows you to create software components that are modular maintainable and reusable When you define an object type using the CREATE TYPE statement in SQL Plus for example you create an abstract template for some real world object As the following example of a bank account shows the template specifies only those attributes and behaviors the object will need in the application environment CREATE TYPE Bank_Account AS OBJECT acct_number INTEGER 5 balance REAL status VARCHAR2 10 EMBER PROCEDURE open amount IN REAL EMBER PROCEDURE verify_acct num IN INT
481. or the day of the month an abbreviation of the month name and the last two digits of the year You can add and subtract dates For example the following statement returns the number of days since an employee was hired SE H ECT SYSDATE hiredate INTO days_worked FROM emp WHERE empno 7499 In arithmetic expressions PL SQL interprets integer literals as days For instance SYSDATE 1 is tomorrow For more information about date functions and format models see Oracle8 SQL Reference MLSLABEL Trusted Oracle provides the MLSLABEL datatype which stores Trusted Oracle s internal representation of labels generated by multi level secure operating systems Trusted Oracle uses the labels to control database access For compatibility with Trusted Oracle applications the Oracle server lets you use MLSLABEL to define database columns However such columns can store only nulls For more information see your Trusted Oracle documentation User Defined Subtypes Each PL SQL base type specifies a set of values and a set of operations applicable to items of that type Subtypes specify the same set of operations as their base type but only a subset of its values Thus a subtype does not introduce a new type it merely places an optional constraint on its base type PL SQL predefines several subtypes in package STANDARD For example PL SQL predefines the subtype CHARACTER as follows
482. ore the current length and maximum length of a formal parameter With parameters of type RAW or LONG RAW you must use the property LENGTH 11 72 PL SQL User s Guide and Reference External Procedures Usage Notes CHARSETID CHARSETFORM The properties CHARSETID and CHARSETFORM identify the nondefault character set from which the character data being passed was formed With CHAR CLOB and VARCHAR2 parameters you can use CHARSETID and CHARSETFORM to pass the character set ID and form to the external procedure The OCI attribute names for these properties are OCI_ATTR_CHARSET_ID and OCI_ATTR_CHARSET_FORM BY REF In C you can pass IN parameters by value the value of the parameter is passed or by reference a pointer to the value is passed When an external procedure expects a pointer BY REF lets you pass the parameter by reference When calling external procedures never write to IN parameters or overflow the capacity of OUT parameters PL SQL does no runtime checks for these error conditions Likewise never read an OUT parameter or a function result Also always assign a value to IN OUT and OUT parameters and to function results Otherwise your external procedure will not return successfully If you include the WITH CONTEXT and PARAMETERS clauses you must specify the parameter CONTEXT which shows the position of the context pointer in the parameter list If you omit the PARAMETERS clause
483. orporation does not warrant that this document is error free If this Program is delivered to a U S Government Agency of the Department of Defense then it is delivered with Restricted Rights and the following legend is applicable Restricted Rights Legend Programs delivered subject to the DOD FAR Supplement are commercial computer software and use duplication and disclosure of the Programs shall be subject to the licensing restrictions set forth in the applicable Oracle license agreement Otherwise Programs delivered subject to the Federal Acquisition Regulations are restricted computer software and use duplication and disclosure of the Programs shall be subject to the restrictions in FAR 52 227 14 Rights in Data General including Alternate III June 1987 Oracle Corporation 500 Oracle Parkway Redwood City CA 94065 Net8 Oracle and SOL Plus are registered trademarks of Oracle Corporation Developer 2000 Oracle7 Oracle8 Oracle Call Interface Oracle Forms Oracle Reports Oracle Enterprise Manager PL SQL Pro C Pro C C and Trusted Oracle are trademarks of Oracle Corporation All other products or company names are used for identification purposes only and may be trademarks of their respective owners Contents Send US Your Comments 0 0 ccccccccccccccccccccscscscsnsesecscsesesscecscesecsusscsesvssucasatsseueecsesesessseatanseeeees xiii ARA O EE EAT OAEIAE IE alte ERA lito theca iio ES XV 1 Overview Ma
484. ors Major Topics Overview Advantages of Exceptions Predefined Exceptions User Defined Exceptions How Exceptions Are Raised How Exceptions Propagate Reraising an Exception Handling Raised Exceptions Useful Techniques Error Handling 6 1 Overview Overview In PL SQL a warning or error condition is called an exception Exceptions can be internally defined by the runtime system or user defined Examples of internally defined exceptions include division by zero and out of memory Some common internal exceptions have predefined names such as ZERO_DIVIDE and STORAGE_ERROR The other internal exceptions can be given names You can define exceptions of your own in the declarative part of any PL SQL block subprogram or package For example you might define an exception named insufficient_funds to flag overdrawn bank accounts Unlike internal exceptions user defined exceptions must be given names When an error occurs an exception is raised That is normal execution stops and control transfers to the exception handling part of your PL SQL block or subprogram Internal exceptions are raised implicitly automatically by the runtime system User defined exceptions must be raised explicitly by RAISE 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 block stops executing and the en
485. osed by the keywords LOOP and END LOOP as follows WHILE condition LOOP sequence_of_statements END LOOP Before each iteration of the loop the condition is evaluated If the condition yields TRUE the sequence of statements is executed then control resumes at the top of the loop If the condition yields FALSE or NULL the loop is bypassed and control passes to the next statement An example follows WHILE total lt 25000 LOOP SELECT sal INTO salary FROM emp WHERE total total salary END LOOP The number of iterations depends on the condition and is unknown until the loop completes Since the condition is tested at the top of the loop the sequence might execute zero times In the last example if the initial value of total is greater than 25000 the condition yields FALSE and the loop is bypassed Control Structures 3 9 Iterative Control LOOP and EXIT Statements Some languages have a LOOP UNTIL or REPEAT UNTIL structure which tests the condition at the bottom of the loop instead of at the top Therefore the sequence of statements is executed at least once PL SQL has no such structure but you can easily build one as follows LOOP sequence_of_statements EXIT WHEN boolean_expression END LOOP To ensure that a WHILE loop executes at least once use an initialized Boolean variable in the condition as follows done FALSE WHIL
486. ost_variable_name E indicator_name lt character_constant_name character_function_call character_literal character_variable_name ES indicator_name O host_variable_name 11 60 PL SQL User s Guide and Reference Expressions date_expression date_constant_name date_function_call date_literal x Es date_variable_name o host_variable_name lt numeric_expression ES indicator_name numeric_expression y SQL 6 host_variable_name numeric_constant_name O X O exponent numeric_function_call numeric_literal numeric_variable_name y Vv FIRST LAST collection_name 6 LIMIT NEXT O index O DEDO Language Elements 11 61 Expressions cursor_variable_name o host_cursor_variable_name l SQL indicator_name host_variable_name numeric_constant_name numeric_function_call COEN numeric_literal numeric_variable_name FIRST LAST collection_name LIMIT NEX PRIOR Keyword and Parameter Description boolean_expression This is an expression that yields the Boolean value TRUE FALSE or NULL character_expression This is an expression that yields a character or character string date_expre
487. ount_id acct new_value UPDATE action set status Insert Success WHERE CURRENT OF c1 B 16 PL SQL User s Guide and Reference Sample 4 Batch Transaction Processing a EXCE PTION WHEN DUP_VAL ON_INDEX TH EN account already exists UPDATE accounts SET bal acct new_valu WHERE account_id acct account_id UPDATE action SET status Insert Acct exists Updated instead WHERE CURRENT OF cl END Z8 Process a DELETE If the account doesn t exist set the status field to say that E the account wasn t found Ay Jas Ay ELSIF acct oper_type D THEN DELETE FROM accounts WHERE account_id acct account_id IF SQLSNOTFOUND THEN account didn t exist UPDATE action SET status Delete ID not found WHERE CURRENT OF c1 F SE UPDATE action SET status Delete Success WHERE CURRENT OF c1 END IF JE e The requested operation is invalid xj Jas xy ELSE oper_type is invalid UPDATE action SET status Invalid operation No action taken WHERE CURRENT OF c1 END IF E LOOP COMMIT ND Sample Programs B 17 Sample 4 Batch Transaction Processing Output Tables SQL gt SELECT FR
488. outines such as OCIGet PieceInfo a all these OCI routines OCIEnvInit OCIInitialize OCIPasswordChange OCIServerAttach OCIServerDetach OCISessionBegin OCISessionEnd OCISvcCtxToLda OCITransCommit OCITransDetach OCITransRollback OCITransStart Also with OCI routine OCIHandleAlloc the following handle types are not supported OCI_HTYPE_SERVER OCI_HTYPE_SESSION OCI_HTYPE_SVCCTX OCI_HTYPE_TRANS External Procedures 10 23 Debugging External Procedures Debugging External Procedures Usually when an external procedure fails its C prototype is faulty That is the prototype does not match the one generated internally by PL SQL This can happen if you specify an incompatible C datatype For example to pass an OUT parameter of type REAL you must specify float Specifying float double or any other C datatype will result in a mismatch In such cases you might get a lost RPC connection to external procedure agent error which means that agent extproc terminated abnormally because the external procedure caused a core dump To avoid errors when declaring C prototype parameters refer to Table 10 2 Using Package DEBUG_EXTPROC To help you debug external procedures PL SQL provides the utility package DEBUG_EXTPROC To install the package run the script dbgextp sql which you can find in the PL SQL demo directory For the location of the directory see your Oracle installation or user s guide To
489. ows returned by a multi row query is called the result set Its size is the number of rows that meet your search criteria As Figure 1 2 shows an explicit cursor points to the current row in the result set This allows your program to process the rows one at a time Figure 1 2 Query Processing Result Set 7369 SMITH CLERK 7566 JONES MANAGER MONDE Current Row 7876 ADAMS CLERK 7902 FORD ANALYST Multi row query processing is somewhat like file processing For example a COBOL program opens a file processes records then closes the file Likewise a PL SQL program opens a cursor processes rows returned by a query then closes the cursor Just as a file pointer marks the current position in an open file a cursor marks the current position in a result set You use the OPEN FETCH and CLOSE statements to control a cursor The OPEN statement executes the query associated with the cursor identifies the result set and positions the cursor before the first row The FETCH statement retrieves the current row and advances the cursor to the next row When the last row has been processed the CLOSE statement disables the cursor Overview 1 5 Main Features Cursor FOR Loops In most situations that require an explicit cursor you can simplify coding by using a cursor FOR loop instead of the OPEN FETCH and CLOSE statements A cursor FOR loop implicitly declares its loop index as a record that represents a row
490. p cursor FOR loop For more information see Iterative Control LOOP and EXIT Statements on page 3 6 basic_loop_statement lt lt label_name gt label_name TO pp Loren EDO O while_loop_statement label_name OCO label_name TOE J Ger EDO for_loop_statement label_name REVERSE LE OA label_name TF y lanar END LOOP 11 96 PL SQL User s Guide and Reference LOOP Statements cursor_for_loop_statement label_name Oe E cursor_parameter_name cursor_name label_name en O Keyword and Parameter Description label_name This is an undeclared identifier that optionally labels a loop If used 1abel_name must be enclosed by double angle brackets and must appear at the beginning of the loop Optionally 1abe1_name can also appear at the end of the loop You can use label_name in an EXIT statement to exit the loop labelled by label_name You cannot reference the index of a FOR loop from a nested FOR loop if both indexes have the same name unless the outer loop is labeled by 1abe1_name and you use dot notation as follows label_name index name In the following example you compare two loop indexes that have the same name one used by an enclosing loop the other by a nested loop lt lt outer gt gt FOR ctr IN 1 20 LOOP lt lt inner gt gt FOR ctr IN 1 10 LOOP IF outer ctr gt ctr THEN END LOOP inner
491. parentheses to override the default operator precedence Within an expression operations occur in their predefined order of precedence From first to last top to bottom the default order of operations is parentheses exponents unary operators multiplication and division addition subtraction and concatenation PL SQL evaluates operators of equal precedence in no particular order When parentheses enclose an expression that is part of a larger expression PL SQL evaluates the parenthesized expression first then uses the result value in the larger expression When parenthesized expressions are nested PL SQL evaluates the innermost expression first and the outermost expression last Examples Several examples of expressions follow a 5 gt e Boolean expression NOT finished Boolean expression TO_CHAR acct_no character expression Fat cats character expression 15 NOV 99 date expression MONTHS BETWEEN d1 d2 date expression PE CLFEZ numeric expression emp_cvSROWCOUNT numeric expression 11 68 PL SQL User s Guide and Reference Expressions Related Topics Assignment Statement Constants and Variables EXIT Statement IF Statement LOOP Statements Language Elements 11 69 External Procedures External Procedures Syntax An external procedure is a third generation language routine stored in a dynamic link library or shared library that loads
492. plains all the concepts behind PL SQL and illustrates every facet of the language Good programming style is stressed throughout and supported by numerous examples Using this guide you learn PL SQL quickly and effectively and you learn why PL SQL is ideal for building enterprise wide applications Major Topics What s New in This Edition How This Guide Is Organized Notational Conventions Sample Database Tables XV Audience Anyone developing applications for Oracle will benefit from reading this guide Written especially for programmers this comprehensive treatment of PL SQL will also be of value to systems analysts project managers and others interested in database applications To use this guide effectively you need a working knowledge of the following subjects a procedural programming language such as Ada C or COBOL a the SQL database language a Oracle concepts and terminology You will not find installation instructions or system specific information in this guide For that kind of information see the Oracle installation or user s guide for your system What s New in This Edition xvi Release 8 0 of PL SQL offers an array of new features that help you build powerful database applications For example now you can benefit from a an interface for calling routines written in other languages support for object oriented programming based on object types the collection types TABLE and VARRAY which allow you
493. plicit Datatype Conversions At run time PL SQL converts between structurally different datatypes implicitly For instance assigning a PLS_INTEGER variable to a NUMBER variable results in a conversion because their internal representations are different Avoiding implicit conversions can improve performance Look at the example below The integer literal 15 is represented internally as a signed 4 byte quantity so PL SQL must convert it to an Oracle number before the addition However the floating point literal 15 0 is represented as a 22 byte Oracle number so no conversion is necessary DECLARE n NUMBER c CHAR 5 BEGIN n n 15 converted n n 15 0 not converted Another example follows DECLARE c CHAR 5 BEGIN c t 25 converted c 25 not converted Interaction with Oracle 5 59 Processing Transactions Dealing with Size Limitations PL SQL was designed primarily for high speed transaction processing As a result the compiler limits the number of tokens identifiers keywords operators and so on that a program unit block subprogram or package can contain Units that exceed the limit cause a program too large compilation error Generally units larger than 128K exceed the token limit However smaller units can also exceed the limit if they contain many variables or complex SQL statements Typically this problem occurs with package bodies
494. ply only to nested tables a To extend a nested table you must use the built in procedure EXTEND But to extend an index by table you just specify larger subscripts a The built in procedures EXTEND and TRIM can be applied only to nested tables Understanding Varrays Items of type VARRAY are called varrays They allow you to associate a single identifier with an entire collection This association lets you manipulate the collection as a whole and reference individual elements easily To reference an element you use standard subscripting syntax see Figure 4 2 For example Grade 3 references the third element in varray Grades Figure 4 2 Varray of Size 10 Varray Grades B C A A C D B 1 3D 3B A 6 7 Maximum Size 10 A varray has a maximum size which you must specify in its type definition Its index has a fixed lower bound of 1 and an extensible upper bound For example the current upper bound for varray Grades is 7 but you can extend it to 8 9 or 10 Thus a varray can contain a varying number of elements from zero when empty to the maximum specified in its type definition Varrays versus Nested Tables Nested tables differ from varrays in the following ways a Varrays have a maximum size but nested tables do not a Varrays are always dense but nested tables can be sparse So you can delete individual elements from a nested table but not from a varray 4 4 PL SQL User
495. ponents A composite type such as RECORD has internal components that can be manipulated individually Like the RECORD type an object type is a composite type However its operations are user defined not predefined Currently you cannot define object types within PL SQL They must be CREATEd and stored in an Oracle database where they can be shared by many programs A program that uses object types is called a client program It can declare and manipulate an object without knowing how the object type represents data or implements operations This allows you to write the program and object type separately and to change the implementation of the object type without affecting the program Thus object types support both procedural and data abstraction Note To use object types you must have the Oracle8 Enterprise Edition and the Objects Option For more information see Getting to Know Oracle8 and the Oracle8 Enterprise Edition 9 2 PL SQL User s Guide and Reference What Is an Object Type What Is an Object Type An object type is a user defined composite datatype that encapsulates a data structure along with the functions and procedures needed to manipulate the data The variables that form the data structure are called attributes The functions and procedures that characterize the behavior of the object type are called methods We usually think of an object such as a person car or bank account as
496. pplication an OCI application and various Oracle tools including Oracle Forms Oracle Reports and SQL Plus If you redeclare ABS in a PL SQL program your local declaration overrides the global declaration However you can still call the built in function by using dot notation as follows STANDARD ABS x Most built in functions are overloaded For example package STANDARD contains the following declarations FUNCTION TO_CHAR FUNCTION TO_CHAR FUNCTION TO_CHAR FUNCTION TO_CHAR right DATE RETURN VARCHAR2 left NUMBER RETURN VARCHAR2 left DATE right VARCHAR2 RETURN VARCHAR2 left NUMBER right VARCHAR2 RETURN VARCHAR2 PL SQL resolves a call to TO_CHAR by matching the number and datatypes of the formal and actual parameters Packages 8 15 Product specific Packages Product specific Packages Oracle and various Oracle tools are supplied with product specific packages that help you build PL SQL based applications For example Oracle is supplied with many utility packages a few of which are highlighted below For more information see Oracle8 Application Developer s Guide DBMS_STANDARD Package DBMS_STANDARD provides language facilities that help your application interact with Oracle For instance the procedure raise_application_error lets you issue user defined error messages That way you can report errors to an application and avoid re
497. psulating operations with data object types let you move data maintenance code out of SQL scripts and PL SQL blocks into methods Also object types hide implementation details so that you can change the details without affecting client programs Overview 1 21 Advantages of PL SQL In addition object types allow for realistic data modeling Complex real world entities and relationships map directly into object types That helps your programs better reflect the world they are trying to simulate Better Performance Without PL SQL Oracle must process SQL statements one at a time Each SQL statement results in another call to Oracle and higher performance overhead Ina networked environment the overhead can become significant Every time a SQL statement is issued it must be sent over the network creating more traffic However with PL SQL an entire block of statements can be sent to Oracle at one time This can drastically reduce communication between your application and Oracle As Figure 1 5 shows if your application is database intensive you can use PL SQL blocks and subprograms to group SQL statements before sending them to Oracle for execution Figure 1 5 PL SQL Boosts Performance Application Gan O Other DBMSs icati Oracle cae with PL SQL Oracle Application RPC with PL SQL and Stored Procedures PL SQL also improves performance by adding procedural processing power to Oracle tools Using PL SQ
498. r you must close it first However you need not close a cursor variable before reopening it You can use different INTO lists on separate fetches with the same cursor or cursor variable Each fetch retrieves another row and assigns values to the target variables If you FETCH past the last row in the result set the values of the target fields or variables are indeterminate and the sNOTFOUND attribute yields TRUE PL SQL makes sure the return type of a cursor variable is compatible with the INTO clause of the FETCH statement For each column value returned by the query associated with the cursor variable there must be a corresponding type compatible field or variable in the INTO clause Also the number of fields or variables must equal the number of column values When you declare a cursor variable as the formal parameter of a subprogram that fetches from the cursor variable you must specify the IN or IN OUT mode However if the subprogram also opens the cursor variable you must specify the IN OUT mode Eventually the FETCH statement must fail to return a row so when that happens no exception is raised To detect the failure you must use the cursor attribute SFOUND or SNOTFOUND For more information see Using Cursor Attributes on page 5 38 PL SQL raises the predefined exception INVALID_CURSOR if you try to fetch from a closed or never opened cursor or cursor variable Language Elements 11 77 FETCH Statem
499. r SQL statements are passed intact to the output file Comment lines beginning with REM or are deleted unless they appear in a package or subprogram definition A wrapped package or subprogram definition has the form lt header gt WRAPPED lt body gt where header begins with the reserved word CREATE and ends with the name of the package or subprogram and body is an intermediate form of object code that looks like a random sequence of characters The keyword WRAPPED tells the PL SQL compiler that the package or subprogram is wrapped PL SQL Wrapper D 3 Running the PL SQL Wrapper The header can contain comments For example the Wrapper converts CREATE OR REPLACE PACKAGE Author J Smith Date 11 15 94 mypkg AS into CREATE OR REPLACE PACKAGE Author J Smith Date 11 15 94 mypkg WRAPPED 8c724af33 Generally the output file is much larger than the input file Error Detection If your input file contains syntactic errors the PL SQL Wrapper detects and reports them However the Wrapper cannot detect semantic errors because it does not resolve external references That is done at compile time So only the PL SQL compiler can detect semantic errors D 4 PL SQL User s Guide and Reference E Name Resolution This appendix explains how PL SQL resolves references to names in potentially ambiguous procedural and SQL statements
500. r allows you to compare expressions For the meaning of each operator see Comparison Operators on page 2 44 IS NOT NULL This comparison operator returns the Boolean value TRUE if its operand is null or FALSE if its operand is not null NOT LIKE This comparison operator compares a character value to a pattern Case is significant LIKE returns the Boolean value TRUE if the character patterns match or FALSE if they do not match Language Elements 11 63 Expressions pattern This is a character string compared by the LIKE operator to a specified string value It can include two special purpose characters called wildcards An underscore _ matches exactly one character a percent sign matches zero or more characters NOT BETWEEN This comparison operator tests whether a value lies in a specified range It means greater than or equal to low value and less than or equal to high value NOT IN This comparison operator tests set membership It means equal to any member of The set can contain nulls but they are ignored Also expressions of the form value NOT IN set yield FALSE if the set contains a null cursor_name This identifies an explicit cursor previously declared within the current scope cursor_variable_name This identifies a PL SQL cursor variable previously declared within the current scope host_cursor_variable_ name This identifies a cursor variable de
501. r function read write access to database tables packaged variables or both In the object type specification you code the pragma somewhere after the method to which it applies You can specify up to four constraints in any order but you must specify WNDS To call the method from parallel queries you must also specify WNP S RNDS and RNPS No constraint implies another If you specify the keyword DEFAULT instead of a method name the pragma applies to all member functions including the system defined constructor You can declare the pragma for any member function Such pragmas override the default pragma However a non default pragma can apply to only one method So among overloaded methods the pragma always applies to the nearest preceding method 11 106 PL SQL User s Guide and Reference Object Types Usage Notes Once an object type is defined and installed in the schema you can use it to declare objects in any PL SQL block subprogram or package For example you can use the object type to specify the datatype of an attribute column variable bind variable record field table element formal parameter or function result Like a package an object type has two parts a specification and a body The specification is the interface to your applications it declares a data structure set of attributes along with the operations methods needed to manipulate the data The body fully defines the methods and so implements th
502. r is not open the CURRENT OF clause causes an error If the cursor is open but no rows have been fetched or the last fetch returned no rows PL SQL raises the predefined exception NO_DATA_FOUND RETURNING This clause lets you return values from the deleted row thereby eliminating the need to SELECT the row beforehand You can retrieve the column values into variables and or host variables You can use the DELETE WHERE CURRENT OF statement after a fetch from an open cursor this includes implicit fetches executed in a cursor FOR loop provided the associated query is FOR UPDATE This statement deletes the current row that is the one just fetched 11 50 PL SQL User s Guide and Reference DELETE Statement Example Related Topics The implicit SOL cursor and the cursor attributes sNOTFOUND SFOUND and SROWCOUNT let you access useful information about the execution of a DELETE statement A DELETE statement might delete one or more rows or no rows If one or more rows are deleted you get the following results SQL NOTFOUND yields FALSE SQLS FOUND yields TRUE SQLSROWCOUNT yields the number of rows deleted If no rows are deleted you get these results SQL NOTFOUND yields TRUE SQL FOUND yields FALSE SQL SROWCOUNT yields 0 The following statement deletes from the bonus table all employees whose sales w
503. r to the host environment which determines the outcome For example in the Oracle Precompilers environment any database changes made by a failed SQL statement or PL SQL block are rolled back Unhandled exceptions can also affect subprograms If you exit a subprogram successfully PL SQL assigns values to OUT parameters However if you exit with an unhandled exception PL SQL does not assign values to OUT parameters Also if a stored subprogram fails with an unhandled exception PL SQL does not roll back database work done by the subprogram You can avoid unhandled exceptions by coding an OTHERS handler at the topmost level of every PL SQL block and subprogram Error Handling 6 19 Useful Techniques Useful Techniques In this section you learn three techniques that increase flexibility Continuing after an Exception Is Raised An exception handler lets you recover from an otherwise fatal error before exiting a block But when the handler completes the block terminates You cannot return to the current block from an exception handler In the following example if the SELECT INTO statement raises ZERO_DIVIDE you cannot resume with the INSERT statement DECLARE pe_ratio NUMBER 3 1 BEGI DELETE FROM stats WHERE symbol XYZ SELECT price NVL earnings 0 INTO pe_ratio FROM stocks WHERE symbol XYZ INSERT INTO stats symbol ratio VALUES XYZ pe ratio
504. rameter declarations are optional Procedures that take no parameters are written without parentheses The procedure body begins with the keyword IS and ends with the keyword END followed by an optional procedure name The procedure body has three parts an optional declarative part an executable part and an optional exception handling part The declarative part contains declarations of types cursors constants variables exceptions and subprograms These items are local and cease to exist when you exit the procedure The executable part contains statements that assign values control execution and manipulate Oracle data The exception handling part contains exception handlers which deal with exceptions raised during execution For more information see Procedures on page 7 3 procedure_specification C procedure_body procedure_declaration Sd lt type_definition E item_declaration lt function_declaration procedure_declaration Language Elements 11 121 Procedures EN lanar EXCEPTION G exception _handler y END G parameter_declaration expression paar Keyword and Parameter Description procedure_name This identifies a user defined procedure parameter_name This identifies a formal parameter which is a variable declared in a procedure specification and referenced in the procedure body IN OUT IN OUT These
505. rams those defined independently are called stand alone subprograms Subprograms defined within another subprogram or within a PL SQL block are called local subprograms They cannot be referenced by other applications and exist only for the convenience of the enclosing block Stored subprograms offer higher productivity better performance memory savings application integrity and tighter security For example by designing applications around a library of stored procedures and functions you can avoid redundant coding and increase your productivity You can call stored subprograms from a database trigger another stored subprogram an Oracle Precompiler application an OCI application or interactively from SQL Plus or Enterprise Manager For example you might call the stand alone procedure create_dept from SQL Plus as follows SQL gt EXECUTE create_dept FINANCE NEW YORK Overview 1 19 Architecture In Oracle Tools Subprograms are stored in parsed compiled form So when called they are loaded and passed to the PL SQL engine immediately Also they take advantage of shared memory So only one copy of a subprogram need be loaded into memory for execution by multiple users Database Triggers A database trigger is a stored subprogram associated with a table You can have Oracle automatically fire the database trigger before or after an INSERT UPDATE or DELETE statement affects the t
506. range limits from the sals database table The function identifier sal_ok is set to a Boolean value by the RETURN statement If the salary is out of range sal_ok is set to FALSE otherwise sal_ok is set to TRUE A function is called as part of an expression For example the function sal_ok might be called as follows IF sal_ok new_sal new_title THEN The function identifier acts like a variable whose value depends on the parameters passed to it To be callable from SQL expressions a stored function must obey certain rules meant to control side effects For stand alone functions Oracle can enforce these rules by checking the function body However the body of a packaged function is hidden So for packaged functions you must use the pragma RESTRICT_REFERENCES to enforce the rules For more information see Oracle8 Application Developer s Guide 7 6 PL SQL User s Guide and Reference RETURN Statement RETURN Statement The RETURN statement immediately completes the execution of a subprogram and returns control to the caller Execution then resumes with the statement following the subprogram call Do not confuse the RETURN statement with the RETURN clause which specifies the datatype of the result value in a function specification A subprogram can contain several RETURN statements none of which need be the last lexical statement Executing any of them completes the subprogram
507. ransparent to calling applications Data Structures You implement information hiding for data structures though data encapsulation By developing a set of utility subprograms for a data structure you insulate it from users and other developers That way other developers know how to use the subprograms that operate on the data structure but not how the structure is represented With PL SOL packages you can specify whether subprograms are public or private Thus packages enforce data encapsulation by letting you put subprogram definitions in a black box A private definition is hidden and inaccessible Only the package not your application is affected if the definition changes This simplifies maintenance and enhancement 1 16 PL SQL User s Guide and Reference Main Features Error Handling PL SQL makes it easy to detect and process predefined and user defined error conditions called exceptions When an error occurs an exception is raised That is normal execution stops and control transfers to the exception handling part of your PL SQL block or subprogram To handle raised exceptions you write separate routines called exception handlers Predefined exceptions are raised implicitly by the runtime system For example if you try to divide a number by zero PL SQL raises the predefined exception ZERO_DIVIDE automatically You must raise user defined exceptions explicitly with the RAISE statement You can define excepti
508. rapper D 1 input and output files D 3 running D 2 PLS_INTEGER datatype 2 13 PLSQL_V2_COMPATIBILITY flag 5 62 pointer 5 19 portability 1 23 positional notation 7 12 POSITIVE subtype 2 12 POSITIVEN subtype 2 12 pragma 6 8 EXCEPTION_INIT 6 8 RESTRICT_REFERENCES 7 6 9 12 SERIALLY_REUSABLE 5 55 precedence operator 2 42 precision of digits specifying 2 12 predefined exception list of 6 4 raising explicitly 6 11 redeclaring 6 10 predicate 5 6 preface Send Us Your Comments xiii PRIOR collection method 4 23 PRIOR row operator 5 5 5 7 private object 8 14 procedural abstraction 9 2 procedure 7 1 7 3 body 7 4 calling 7 5 external 10 2 parameter 7 3 parts 7 4 specification 7 4 syntax 11 121 productivity 1 23 program unit 1 11 PROGRAM_ERROR exception 6 5 propagation exception 6 12 property CHARSETFORM 10 15 CHARSETID 10 15 INDICATOR 10 14 LENGTH 10 14 MAXLEN 10 14 pseudocolumn 5 4 CURRVAL 5 4 LEVEL 5 5 NEXTVAL 5 4 ROWID 5 5 ROWNUM 5 5 pseudoinstruction 6 8 public object 8 14 purity level 9 12 Q qualifier using subprogram name as 2 37 when needed 2 34 2 39 query work area 5 19 quoted identifier 2 6 R RAISE statement 6 11 syntax 11 126 using in exception handler 6 15 raise_application_error procedure 6 9 raising an exception 6 11 range operator 3 10 RAW datatype 2 15 converting 2 28 maximum length 2 15 read consisten
509. rcase value of 1ast_name to the third row in nested table ename_tab ename_tab 3 UPPER last_name Examples Several examples of assignment statements follow wages hours_worked hourly_salary country France costs labor supplies done count gt 100 dept_rec loc BOSTON comm_tab 5 sales 0 15 Related Topics Constants and Variables Expressions SELECT INTO Statement 11 6 PL SQL User s Guide and Reference Blocks Blocks Syntax The basic program unit in PL SQL is the block A PL SQL block is defined by the keywords DECLARE BEGIN EXCEPTION and END These keywords partition the PL SQL block into a declarative part an executable part and an exception handling part Only the executable part is required You can nest a block within another block wherever you can place an executable statement For more information see Block Structure on page 1 2 and Scope and Visibility on page 2 37 plsql_block gt lid type_definition F function_declaration item_declaration f procedure_declaration eren EXCEPTION C exception_handler y END G type_definition record_type_definition ref_cursor_type_definition table_type_definition b varray_type_definition Language Elements 11 7 Blocks item_declaration collection_declaration constant_declaration cursor_declarati
510. rd OR as follows EXCEPTION WHEN over_limit OR under_limit OR VALUE_ERROR THEN handle the error If any of the exceptions in the list is raised the associated sequence of statements is executed The keyword OTHERS cannot appear in the list of exception names it must appear by itself You can have any number of exception handlers and each handler can associate a list of exceptions with a sequence of statements However an exception name can appear only once in the exception handling part of a PL SQL block or subprogram The usual scoping rules for PL SQL variables apply so you can reference local and global variables in an exception handler However when an exception is raised inside a cursor FOR loop the cursor is closed implicitly before the handler is invoked Therefore the values of explicit cursor attributes are not available in the handler Exceptions Raised in Declarations Exceptions can be raised in declarations by faulty initialization expressions For example the following declaration raises an exception because the constant limit cannot store numbers larger than 999 DECLARE limit CONSTANT NUMBER 3 5000 raises an exception BEGIN EXCEPTION WHEN OTHERS THEN cannot catch the exception 6 16 PL SQL User s Guide and Reference Handling Raised Exceptions Handlers in the current block cannot catch the raised exception
511. re PL SQL is a block structured language That is the basic units procedures functions and anonymous blocks that make up a PL SQL program are logical blocks which can contain any number of nested sub blocks Typically each logical block corresponds to a problem or subproblem to be solved Thus PL SQL supports the divide and conquer approach to problem solving called stepwise refinement 1 2 PL SQL User s Guide and Reference Main Features A block or sub block lets you group logically related declarations and statements That way you can place declarations close to where they are used The declarations are local to the block and cease to exist when the block completes As Figure 1 1 shows a PL SQL block has three parts a declarative part an executable part and an exception handling part In PL SQL a warning or error condition is called an exception Only the executable part is required The order of the parts is logical First comes the declarative part in which items can be declared Once declared items can be manipulated in the executable part Exceptions raised during execution can be dealt with in the exception handling part Figure 1 1 Block Structure DECLARE declarations statements EXCEPTION handlers BEGIN END You can nest sub blocks in the executable and exception handling parts of a PL SQL block or subprogram but not in the declarative part Also you can define local s
512. res a constant For the syntax of constant_declaration see Constants and Variables on page 11 29 exception_declaration This construct declares an exception For the syntax of exception_declaration see Exceptions on page 11 54 object_declaration This identifies an object instance of an object type previously declared within the current scope For the syntax of ob ject_declaration see Object Types on page 11 103 record_declaration This construct declares a user defined record For the syntax of record_declarat ion see Records on page 11 128 11 118 PL SQL User s Guide and Reference Packages Usage Notes variable_declaration This construct declares a variable For the syntax of variable_declaration see Constants and Variables on page 11 29 cursor_specification This construct declares the interface to an explicit cursor For the syntax of cursor_specification see Cursors on page 11 45 function_specification This construct declares the interface to a function For the syntax of function_specification see Functions on page 11 79 procedure_specification This construct declares the interface to a procedure For the syntax of procedure_specification see Procedures on page 11 121 cursor_body This construct defines the underlying implementation of an explicit cursor For the syntax of cursor_body see Cursors on page 11 45 function_body Thi
513. rictions some of which future releases of PL SQL will remove You cannot declare cursor variables in a package because they do not have persistent state Language Elements 11 41 Cursor Variables Examples Remote subprograms on another server cannot accept the values of cursor variables Therefore you cannot use RPCs to pass cursor variables from one server to another If you pass a host cursor variable bind variable to PL SQL you cannot fetch from it on the server side unless you also open it there on the same server call The query associated with a cursor variable in an OPEN FOR statement cannot be FOR UPDATE You cannot use comparison operators to test cursor variables for equality inequality or nullity You cannot assign nulls to a cursor variable zai You cannot use REF CURSOR types to specify column types ina CREATE TABLI or CREATE VIEW statement So database columns cannot store the values of cursor variables Cursors and cursor variables are not interoperable that is you cannot use one where the other is expected You cannot use a REF CURSOR type to specify the element type of a collection which means that elements in a collection cannot store the values of cursor variables You cannot use cursor variables with dynamic SQL You can declare a cursor variable in a PL SQL host environment such as an OCI or Pro C program To use the host cursor variable you must pass it as
514. rn_type where ref_type_name is a type specifier used in subsequent declarations of cursor variables and return_type must represent a record or a row in a database table In the following example you specify a return type that represents a row in the database table dept DECLARE YPE DeptCurTyp IS REF CURSOR RETURN dept ROWTYPE Ne REF CURSOR types can be strong restrictive or weak nonrestrictive As the next example shows a strong REF CURSOR type definition specifies a return type but a weak definition does not DECLARE YPE EmpCurTyp IS REF CURSOR RETURN emp ROWTYPE strong YPE GenericCurTyp IS REF CURSOR weak Strong REF CURSOR types are less error prone because the PL SQL compiler lets you associate a strongly typed cursor variable only with type compatible queries However weak REF CURSOR types are more flexible because the compiler lets you associate a weakly typed cursor variable with any query Declaring Cursor Variables Once you define a REF CURSOR type you can declare cursor variables of that type in any PL SQL block or subprogram In the following example you declare the cursor variable dept_cv DECLARE YPE DeptCurTyp IS REF CURSOR RETURN dept ROWTYPE dept_cv DeptCurTyp declare cursor variable 5 20 PL SQL User s Guide and Reference Using Cursor Variables Note You c
515. rocedure name or a parameter list Parameter declarations are optional Procedures that take no parameters are written without parentheses The procedure body begins with the keyword IS and ends with the keyword END followed by an optional procedure name The procedure body has three parts a declarative part an executable part and an optional exception handling part The declarative part contains local declarations which are placed between the keywords IS and BEGIN The keyword DECLARE which introduces declarations in an anonymous PL SQL block is not used The executable part contains statements which are placed between the keywords BEGIN and EXCEPTION or END At least one statement must appear in the executable part of a procedure The NULL statement meets this requirement The exception handling part contains exception handlers which are placed between the keywords EXCEPTION and END Consider the procedure raise_salary which increases the salary of an employee PROCEDURE raise _salary emp id INTEGER increase REAL IS current_salary REAL salary_missing EXCEPTION BEGIN SELECT sal INTO current_salary FROM emp WHERE empno emp_id IF current_salary IS NULL THEN RAISE salary_missing F SE UPDATE emp SET sal sal increase WHERE empno emp_id END IF EXCEPTION WHEN NO_DATA FOUND THE INSERT INTO emp_audit VALUES emp_id No such number WHEN salary_mi
516. rocess each SQL statement not associated with an explicitly declared cursor PL SQL lets you refer to the most recent implicit cursor as the SOL cursor You cannot use the OPEN FETCH and CLOSE statements to control the SOL cursor But you can use cursor attributes to get information about the most recently executed SQL statement See Using Cursor Attributes on page 5 38 5 14 PL SQL User s Guide and Reference Packaging Cursors Packaging Cursors You can separate a cursor specification from its body for placement in a package That way you can change the cursor body without having to change the cursor specification You code the cursor specification in the package specification using the syntax CURSOR cursor_name parameter parameter RETURN return_type In the following example you use the SROWTYPE attribute to provide a record type that represent s a row in the database table emp CREATE PACKAGE Declare CURSOR cl END emp_actio emp_actions AS cursor specification RETURN empSROWTYPE ns CREATE PACKAGE BODY emp_actions AS Define CURSOR cl cursor body RETURN empSROWTYPE IS SELECT FROM emp WHERE sal gt 3000 END emp_actions The cursor specification has no SELECT statement because the RETURN clause defines the datatype of the result value However the cursor b
517. roper value of 50 because processing of an IF statement stops after an expression yields TRUE and its associated sequence of statements is executed The expression associated with ELSIF is never evaluated and control passes to the INSERT statement IF shoe_count lt 20 THEN order_quantity 50 ELSIF shoe_count lt 30 THEN order_quantity 20 11 86 PL SQL User s Guide and Reference IF Statement ELSE order_quantity 10 END IF INSERT INTO purchase_order VALUES shoe_type order_quantity In the following example depending on the value of score one of two status messages is inserted into the grades table IF score lt 70 THEN fail fail 1 INSERT INTO grades VALUES student_id Failed ELSE pass pass 1 INSERT INTO grades VALUES student_id Passed END IF Related Topics Expressions Language Elements 11 87 INSERT Statement INSERT Statement Syntax The INSERT statement adds new rows of data to a specified database table or view For a full description of the INSERT statement see Oracle8 SQL Reference insert_statement table_reference Lay O E ee VU subquery2 pa INTO O C host_variable_name Keyword and Parameter Description table_reference This identifies a table or view that must be accessible when you execute the I
518. rough one ref attribute to another You can also navigate through ref columns to attributes if you use a table alias For example the following syntax is legal table_alias object_column ref_attribute table_alias object_column ref_attribute attribute table_alias ref_column attribute Assume that you have run the following SQL Plus script which creates object types Address and Person and object table persons CREATE TYPE Address AS OBJECT street VARCHAR2 35 city VARCHAR2 15 state CHAR 2 zip_code INTEGER Object Types 9 35 Manipulating Objects CREATE TYPE Person AS OBJECT first_name VARCHARZ2 15 last_name VARCHARZ2 15 birthday DATE home_address REF Address shared with other Person objects phone_number VARCHAR2 15 CREATE TABLE persons OF Person Ref attribute home_address corresponds to a column in object table persons that holds refs to Address objects stored in some other table After populating the tables you can select a particular address by dereferencing its ref as follows DECLARE addr1 Address addr2 Address BEGIN SELECT DEREF home_address INTO addrl FROM persons p WHERE p last_name Derringer In the example below you navigate through ref column home_address to attribute st reet In this case a table alias is required DECLARE my_street VARCHAR2 25
519. row fetched from a previously declared cursor Fields in the record and corresponding columns in the row have the same names and datatypes TYPE This attribute provides the datatype of a previously declared collection cursor variable field object record database column or variable datatype This is a type specifier For the syntax of datatype see Constants and Variables on page 11 29 expression This is an arbitrarily complex combination of variables constants literals operators and function calls The simplest expression consists of a single variable When the declaration is elaborated the value of expression is assigned to the parameter The value and the parameter must have compatible datatypes You must declare a cursor before referencing it in an OPEN FETCH or CLOSE statement And you must declare a variable before referencing it in a cursor declaration The word SQL is reserved by PL SQL for use as the default name for implicit cursors and cannot be used in a cursor declaration You cannot assign values to a cursor name or use it in an expression However cursors and variables follow the same scoping rules For more information see Scope and Visibility on page 2 37 Language Elements 11 47 Cursors You retrieve data from a cursor by opening it then fetching from it Because the FETCH statement specifies the target variables using an INTO clause in the SELECT statement of a cur
520. rsal resource locator string contacts the specified site and returns the requested data which is usually in hypertext markup language HTML format Package DBMS_SQL allows PL SQL to execute SQL data definition and data manipulation statements dynamically at run time For an example see Using DDL and Dynamic SQL on page 5 7 Packages 8 17 Guidelines DBMS_ALERT Package DBMS_ALERT lets you use database triggers to alert an application when specific database values change The alerts are transaction based and asynchronous that is they operate independently of any timing mechanism For example a company might use this package to update the value of its investment portfolio as new stock and bond quotes arrive Guidelines When writing packages keep them as general as possible so they can be reused in future applications Avoid writing packages that duplicate some feature already provided by Oracle Package specifications reflect the design of your application So define them before the package bodies Place in a specification only the types items and subprograms that must be visible to users of the package That way other developers cannot misuse the package by basing their code on irrelevant implementation details To reduce the need for recompiling when code is changed place as few items as possible in a package specification Changes to a package body do not require Oracle to recompile dependent procedures How
521. rst For example both of the following expressions yield 8 because division has a higher precedence than addition 5 12 4 12 4 5 Operators with the same precedence are applied in no particular order You can use parentheses to control the order of evaluation For example the following expression yields 7 not 11 because parentheses override the default operator precedence 8 6 2 In the next example the subtraction is done before the division because the most deeply nested subexpression is always evaluated first 100 20 5 7 3 The following example shows that you can always use parentheses to improve readability even when they are not needed salary 0 05 commission 0 25 2 42 PL SQL User s Guide and Reference Expressions and Comparisons Logical Operators The logical operators AND OR and NOT follow the tri state logic shown in Table 2 3 AND and OR are binary operators NOT is a unary operator Table 2 3 Logic Truth Table Xx y XANDy xORy NOTx TRUE TRUE TRUE TRUE FALSE RUE FALSE FALSE RUE RUE NULL NULL RUE FALS TRUE FALSE RUE TRUE FALSE FALSE FALSE FALSE FALSE NULL FALSE ULL NUL TRUE NULL TRUE NULL NUL FALSE FALSE ULL NULL NULL NULL ULL As the truth table shows AND returns TRUE only if both its operands are true On the other hand OR returns TRUE if either of its operands
522. s User defined records follow the usual scoping and instantiation rules In a package they are instantiated when you first reference the package and cease to exist when you exit the application or end the database session In a block or subprogram they are instantiated when you enter the block or subprogram and cease to exist when you exit the block or subprogram Like scalar variables user defined records can be declared as the formal parameters of procedures and functions The restrictions that apply to scalar parameters also apply to user defined records 11 130 PL SQL User s Guide and Reference Records Example Related Topics You can specify a RECORD type in the RETURN clause of a function specification That allows the function to return a user defined record of the same type When calling a function that returns a user defined record you use the following syntax to reference fields in the record function_name parameters field_nam To reference nested fields in a record returned by a function you use the following syntax function_name parameters field_name nested_field_nam Currently you cannot use the syntax above to call a parameterless function because PL SQL does not allow empty parameter lists That is the following syntax is illegal function_name field_nam illegal empty parameter list You cannot just drop the empty parameter list because the following syntax is also illegal
523. s The PL SQL character set includes a the upper and lowercase letters A Z a Z a the numerals 0 9 a tabs spaces and carriage returns a thesymbols lt gt amp _1 PL SQL is not case sensitive so lowercase letters are equivalent to corresponding uppercase letters except within string and character literals Lexical Units A line of PL SQL text contains groups of characters known as lexical units which can be classified as follows a delimiters simple and compound symbols a identifiers which include reserved words a literals comments For example the line bonus salary 0 10 compute bonus contains the following lexical units a identifiers bonus and salary compound symbol simple symbols and numeric literal 0 10 comment compute bonus To improve readability you can separate lexical units by spaces In fact you must separate adjacent identifiers by a space or punctuation The following line is illegal because the reserved words END and IF are joined IF x gt y THEN high x ENDIF illegal 2 2 PL SQL User s Guide and Reference Lexical Units Delimiters However you cannot embed spaces in lexical units except for string literals and comments For example the following line is illegal because the compound symbol for assignment is split count count 1 illegal To show structure you can divide lines using c
524. s an optional parameter that lets you specify a maximum length up to 32767 bytes The syntax follows CHAR maximum_length You cannot use a constant or variable to specify the maximum length you must use an integer literal in the range 1 32767 If you do not specify a maximum length it defaults to 1 Remember you specify the maximum length in bytes not characters So if a CHAR n variable stores multi byte characters its maximum length is less than n characters The maximum width of a CHAR database column is 2000 bytes So you cannot insert CHAR values longer than 2000 bytes into a CHAR column You can insert any CHAR n value into a LONG database column because the maximum width of a LONG column is 2147483647 bytes or 2 gigabytes However you cannot retrieve a value longer than 32767 bytes from a LONG column into a CHAR n variable CHAR Subtype The CHAR subtype CHARACTER has the same range of values as its base type That is CHARACTER is just another name for CHAR You can use this subtype for compatibility with ANSI ISO and IBM types or when you want an identifier more descriptive than CHAR 2 14 PL SQL User s Guide and Reference Datatypes LONG You use the LONG datatype to store variable length character strings The LONG datatype is like the VARCHAR2 datatype except that the maximum length of a LONG value is 32760 bytes You can insert any LONG value into a LONG database column because the maximum w
525. s being called by checking their formal parameters Consider the example below If you call initialize witha DateTabTyp parameter PL SQL uses the first version of initialize But if you call initialize witha RealTabTyp parameter PL SQL uses the second version DECLARE YPE DateTabTyp IS TABLE OF DATE INDEX BY BINARY_INTEGER YPE RealTabTyp IS TABLE OF REAL INDEX BY BINARY_INTEGER hiredate_tab DateTabTyp comm_tab RealTabTyp indx BINARY_INTEGER BEGIN indx 50 initialize hiredate_tab indx calls first version initialize comm_tab indx calls second version END Only local or packaged subprograms can be overloaded Therefore you cannot overload stand alone subprograms Also you cannot overload two subprograms if their formal parameters differ only in name or parameter mode For example you cannot overload the following two procedures PROCEDURE reconcile acct_no IN INTEGER IS BEGI END Subprograms 7 19 Overloading PROCEDURE reconcile acct_no OUT INTEGER IS BEGI END Furthermore you cannot overload two subprograms if their formal parameters differ only in datatype and the different datatypes are in the same family For instance you cannot overload the following procedures because the datatypes INTEGER and REAL are in the same f
526. s construct defines the underlying implementation of a function For the syntax of funct ion_body see Functions on page 11 79 procedure_body This construct defines the underlying implementation of a procedure For the syntax of procedure_body see Procedures on page 11 121 You cannot define packages in a PL SQL block or subprogram However you can use any Oracle tool that supports PL SQL to create and store packages in an Oracle database You can issue the CREATE PACKAGE and CREATE PACKAGE BODY statements interactively from SQL Plus or Enterprise Manager and from an Oracle Precompiler or OCI host program For the full syntax of the CREATE PACKAGE statement see Oracle8 SQL Reference Language Elements 11 119 Packages Related Topics Most packages have a specification and a body The specification is the interface to your applications it declares the types variables constants exceptions cursors and subprograms available for use The body fully defines cursors and subprograms and so implements the specification Only subprograms and cursors have an underlying implementation definition So if a specification declares only types constants variables and exceptions the package body is unnecessary However the body can still be used to initialize items declared in the specification as the following example shows CREATE PACKAGE emp_actions AS number_hire
527. s in the declarative part of any PL SQL block subprogram or package Declarations allocate storage space for a value specify its datatype and name the storage location so that you can reference it A couple of examples follow birthday DATE emp_count SMALLINT 0 2 28 PL SQL User s Guide and Reference Declarations The first declaration names a variable of type DATE The second declaration names a variable of type SMALLINT and uses the assignment operator to assign an initial value of zero to the variable The next examples show that the expression following the assignment operator can be arbitrarily complex and can refer to previously initialized variables pi REAL 3 14159 radius REAL 1 area REAL pi radius 2 By default variables are initialized to NULL For example the following declarations are equivalent birthday DATE birthday DATE NULL In constant declarations the keyword CONSTANT must precede the type specifier as the following example shows credit_limit CONSTANT REAL 5000 00 This declaration names a constant of type REAL and assigns an initial also final value of 5000 to the constant A constant must be initialized in its declaration Otherwise you get a compilation error when the declaration is elaborated The processing of a declaration by the PL SQL compiler is called elaboration Using DEFAULT You can use the keyword DEFAULT instead of
528. s particular Version 2 behavior You can do that by setting the PLSQL_V2_COMPATIBILITY flag On the server side you can set the flag in two ways Add the following line to the Oracle initialization file PLSOL_V2_COMPATIBILITY TRUE a Execute one of the following SOL statements AL AL ER SESSION S ER SYST EM S ET PLSQL V2 CO ET PLSOL V2 COMPATIBILITY TRI PALIBILITY TRUI If you specify FALSE the default only Version 8 behavior is allowed On the client side a command line option sets the flag For example in the Oracle Precompilers environment you specify the runtime option DBMS on the command line as follows DBMS V7 5 62 PL SQL User s Guide and Reference 6 There is nothing more exhilarating than to be shot at without result Error Handling Winston Churchill Runtime errors arise from design faults coding mistakes hardware failures and many other sources Although you cannot anticipate all possible errors you can plan to handle certain kinds of errors meaningful to your PL SQL program With many programming languages unless you disable error checking a runtime error such as stack overflow or division by zero stops normal processing and returns control to the operating system With PL SQL a mechanism called exception handling lets you bulletproof your program so that it can continue operating in the presence of err
529. s passed to it In the following example you pass six elements to constructor CourseList which returns a nested table containing those elements DECLARE my_courses CourseList BEGIN my_courses CourseList Econ 2010 Acct 3401 Mgmt 3100 PoSc 3141 Mktg 3312 Engl 2005 In the next example you pass three objects to constructor ProjectList which returns a varray containing those objects DECLARE accounting_projects ProjectList BEGIN accounting_projects ProjectList Project 1 Design New Expense Report 3250 Project 2 Outsource Payroll 12350 Project 3 Audit Accounts Payable 1425 You need not initialize the whole varray For example if a varray has a maximum size of 50 you can pass fewer than 50 elements to its constructor If you did not impose the NOT NULL constraint or specify a record type for elements you can pass null elements to a constructor An example follows BEGIN my_courses CourseList Math 3010 NULL NULL Stat 3202 Collections and Records 4 9 Initializing and Referencing Collections The next example shows that you can initialize a collection in its declaration which is a good programming practice DECLARE my_courses CourseList CourseList Art 1111 Hist 3100 If you call a constructor without arguments you get an empty but non null collection
530. s useful information about the execution of an INSERT statement An INSERT statement might insert one or more rows or no rows If one or more rows are inserted you get the following results SQL NOTFOUND yields FALSE SQL FOUND yields TRU El SQL SROWCOUNT yields the number of rows inserted If no rows are inserted you get these results SQL NOTFOUND yields TRUE SQL FOUND yields FALS El SOLSROWCOUNT yields 0 Examples The following examples show various forms of INSERT statement INSERT INTO bonus SELECT ename job sal comm FROM emp WHERE comm gt sal 0 25 INSERT INTO emp empno ename job sal comm deptno VALUES 4160 STURDEVIN SECURITY GUARD 2045 NULL 30 INSERT INTO dept VALUES my_deptno UPPER my_dname CHICAGO Related Topics SELECT Statement 11 90 PL SQL User s Guide and Reference Literals Literals Syntax A literal is an explicit numeric character string or Boolean value not represented by an identifier The numeric literal 135 and the string literal hello world are examples For more information see Literals on page 2 7 numeric_literal real_number integer Lan real_number gt string_literal Gai VES Language Elements 11 91 Literals boolean_literal Keyword and Paramet
531. se a user defined exception which is Oracle error 20100 and return a null terminated error message if OCIExtProcRaiseExcpWithMsg ctx int 20100 divisor is zero 0 OCIEXTPROC_SUCCESS return else Incorrect parameters were passed assert 0 result dividend divisor OCIExtProcGetEnv This service routine enables OCI callbacks to the database during an external procedure call Use the OCI handles obtained by this function only for callbacks If you use them for standard OCI calls the handles establish a new connection to the database and cannot be used for callbacks in the same transaction In other words during an external procedure call you can use OCI handles for callbacks or a new connection but not for both The C prototype for this function follows sword OCIExtProcGetEnv OCIExtProcContext with_context OCTEnv envh OCISvcCtx svch OCIError errh External Procedures 10 21 Doing Callbacks The parameter with_context is the context pointer and the parameters envh svch and errh are the OCI environment service and error handles respectively The return values OCIEXTPROC_SUCCESS and OCIEXTPROC_ERROR indicate success or failure The next section shows how OCIExtProcGetEnv might be used in callbacks For a working example see Demo Program on page 10 24 Doing Callbacks An external procedure executing on the Oracle serv
532. se column into a PL SQL character variable whether the value is blank padded or not depends on the variable type not on the column type When you select a column value into a CHAR variable if the value is shorter than the declared length of the variable PL SQL blank pads the value to the declared length As a result information about trailing blanks is lost If the character value is longer than the declared length of the variable PL SQL aborts the assignment and raises the exception VALUE_ERROR C 4 PL SQL User s Guide and Reference Selecting Character Values When you select a column value into a VARCHAR2 variable if the value is shorter than the declared length of the variable PL SQL neither blank pads the value nor strips trailing blanks Character values are stored intact so no information is lost For example when you select a blank padded CHAR column value into a VARCHAR2 variable the trailing blanks are not stripped If the character value is longer than the declared length of the VARCHAR2 variable PL SQL aborts the assignment and raises VALUE_ERROR The same rules apply when fetching CHAR versus VARCHAR2 Semantics C 5 Selecting Character Values C 6 PL SQL User s Guide and Reference D PL SQL Wrapper This appendix shows you how to run the PL SQL Wrapper a stand alone utility that converts PL SQL source code into portable object code You can use the Wrapper to deliver PL SQL
533. se table Only rows that meet the search condition are updated If you omit the search condition all rows in the table are updated WHERE CURRENT OF cursor_name This clause refers to the latest row processed by the FETCH statement associated with the cursor identified by cursor_name The cursor must be FOR UPDATE and must be open and positioned on a row If the cursor is not open the CURRENT OF clause causes an error If the cursor is open but no rows have been fetched or the last fetch returned no rows PL SQL raises the predefined exception NO_DATA_FOUND RETURNING This clause lets you return values from the updated row thereby eliminating the need to SELECT the row afterward You can retrieve the column values into variables and or host variables You can use the UPDATE WHERE CURRENT OF statement after a fetch from an open cursor this includes implicit fetches executed in a cursor FOR loop provided the associated query is FOR UPDATE This statement updates the current row that is the one just fetched Language Elements 11 153 UPDATE Statement The implicit SOL cursor and the cursor attributes SNOTFOUND FOUND ROWCOUNT and ISOPEN let you access useful information about the execution of an UPDATE statement An UPDATE statement might update one or more rows or no rows If one or more rows are updated you get the following results SQL NOTFOUND yields FALSE SQ
534. seat NA THEN DBMS_OUTPUT PUT_LINE flight_info passengers i name RAISE seat_not_available END IF CHAR CHAR END LOOP END LOOP CLOSE cl EXCEPTION WHEN seat_not_available THEN END Collections and Records 4 37 Manipulating Records 4 38 PL SQL User s Guide and Reference 9 Interaction with Oracle Knowledge is of two kinds We know a subject ourselves or we know where we can find information upon it Samuel Johnson This chapter helps you harness the power of Oracle You learn how PL SQL supports the SQL commands functions and operators that let you manipulate Oracle data You also learn how to manage cursors use cursor variables and process transactions Major Topics SQL Support Using DDL and Dynamic SQL Managing Cursors Packaging Cursors Using Cursor FOR Loops Using Cursor Variables Using Cursor Attributes Processing Transactions Interaction with Oracle 5 1 SQL Support SQL Support By extending SQL PL SQL offers a unique combination of power and ease of use You can manipulate Oracle data flexibly and safely because PL SQL supports all SQL data manipulation commands except EXPLAIN PLAN transaction control commands functions pseudocolumns and operators Also PL SQL conforms to SQL92 the current ANSI ISO SOL standard Note PL SQL does not
535. signate a routine already in the DLL 4 Register the External Procedure Before you can call the external procedure you must register it That is you must tell PL SQL where to find the procedure how to call it and what to pass it After registering the external procedure you can call it from any PL SQL program It executes with the privileges granted to your userid Registering an External Procedure You do that by writing a special kind of PL SQL stand alone or packaged subprogram which acts like a proxy for the external procedure By default they have the same name You write the PL SQL stored subprogram in the usual way except that in its body instead of declarations and a BEGIN END block you code the EXTERNAL clause This clause records information about the external procedure such as its location its name the programming language in which it was written and the calling standard under which it was compiled The syntax follows EXTERNAL LIBRARY library_name NAME external_procedure_name LANGUAGE language_name CALLING STANDARD C PASCAL WITH CONTEXT PARAMETERS external _parameter external _prameter External Procedures 10 3 Registering an External Procedure where external_parameter stands for CONTEXT parameter_name RETURN property BY REF external_datatype and property stands for INDICATOR LENGTH MA
536. sing also occurs when the same actual parameter appears twice in a subprogram call Unless both formal parameters are IN parameters the result is indeterminate as the following example shows DECLARE emp_cv EmpCurTyp emp_rec empSROWIYPE se YPE EmpCurTyp IS REF CURSOR RETURI PROCEDURE open emp cv cvl IN OU EmpCurTyp cv2 IN OU BEGI OPEN cvl FOR SELECT FROM emp OPEN cv2 FOR SELECT FROM emp END open_emp_cv BEGIN open_emp_cv emp_cv emp_cv EmpCurTyp WHERE ename WHERE ename FETCH emp_cv INTO emp_rec indeterminate row for KING 5 36 PL SQL User s Guide and Reference empSROWTYPE se IS KING BLACK might return or BLACK Using Cursor Variables Restrictions Currently cursor variables are subject to the following restrictions some of which future releases of PL SQL will remove You cannot declare cursor variables in a package because they do not have persistent state Remote subprograms on another server cannot accept the values of cursor variables Therefore you cannot use RPCs to pass cursor variables from one server to another If you pass a host cursor variable to PL SQL you cannot fetch from it on the server side unless you also open it there on the same server call The query associated with a cursor variable in an
537. size of a collection So if TRIM encounters deleted elements it includes them in its tally You cannot use collection methods in a SQL statement If you try you get a compilation error Only EXISTS can be applied to atomically null collections If you apply another method to such collections PL SQL raises COLLECTION_IS_NULL You can use PRIOR or NEXT to traverse collections indexed by any series of subscripts For example you can use PRIOR or NEXT to traverse a nested table from which some elements have been deleted 11 18 PL SQL User s Guide and Reference Collection Methods Examples EXTEND operates on the internal size of a collection which includes deleted elements You cannot use EXTEND to initialize an atomically null collection Also if you impose the NOT NULL constraint on a TABLE or VARRAY type you cannot apply the first two forms of EXTEND to collections of that type If an element to be deleted does not exist DELETE simply skips it no exception is raised Varrays are dense so you cannot delete their individual elements PL SQL keeps placeholders for deleted elements So you can replace a deleted element simply by assigning it a new value However PL SQL does not keep placeholders for trimmed elements The amount of memory allocated to a nested table can increase or decrease dynamically As you delete elements memory is freed page by page If you delete
538. sor ID cid DBMS_SOL OPEN_CURSOR Parse and immediately execute dynamic SQL statement built by concatenating table name to DROP TABLE command DBMS_SOL PARSE cid DROP TABLE table_name dbms_sql v7 Close cursor DBMS_SOL CLOSE_CURSOR cid EXCEPTION If an exception is raised close cursor before exiting WHEN OTHERS THEN DBMS_SOL CLOSE_CURSOR cid RAISE reraise the exception END drop_table For more information about package DBMS_SQL see Oracle8 Application Developer s Guide Managing Cursors Recall from Chapter 1 that PL SQL uses two types of cursors implicit and explicit PL SQL declares a cursor implicitly for all SQL data manipulation statements including queries that return only one row However for queries that return more than one row you must declare an explicit cursor or use a cursor FOR loop Explicit Cursors The set of rows returned by a query can consist of zero one or multiple rows depending on how many rows meet your search criteria When a query returns multiple rows you can explicitly declare a cursor to process the rows You can declare a cursor in the declarative part of any PL SQL block subprogram or package You use three commands to control a cursor OPEN FETCH and CLOSE First you initialize the cursor with the OPEN statement which identifies the result set Then you use th
539. sor_declaration is redundant and invalid The scope of cursor parameters is local to the cursor meaning that they can be referenced only within the query used in the cursor declaration The values of cursor parameters are used by the associated query when the cursor is opened The query can also reference other PL SQL variables within its scope The datatype of a cursor parameter must be specified without constraints For example the following parameter declarations are illegal CURSOR cl emp id NUMBER NOT NULL dept_no NUMBER 2 illegal Examples Some examples of cursor declarations follow CURSOR cl IS SELECT empno ename job sal FROM emp WHERE sal gt 2000 CURSOR c2 RETURN dept ROWTYPE IS SELECT FROM dept WHERE deptno 10 CURSOR c3 start_date DATE IS SELECT empno sal FROM emp WHERE hiredate gt start_date Related Topics CLOSE Statement FETCH Statement OPEN Statement SELECT INTO Statement 11 48 PL SQL User s Guide and Reference DELETE Statement DELETE Statement Syntax The DELETE statement removes entire rows of data from a specified table or view For a full description of the DELETE statement see Oracle8 SQL Reference delete_statement table_reference f row_expression variable_name O host_variable_name O
540. ssing THEN INSERT INTO emp_audit VALUES emp_id Salary is null END raise_salary 7 4 PL SQL User s Guide and Reference Functions Functions When called this procedure accepts an employee number and a salary increase amount It uses the employee number to select the current salary from the emp database table If the employee number is not found or if the current salary is null an exception is raised Otherwise the salary is updated A procedure is called as a PL SQL statement For example you might call the procedure raise_salary as follows raise_salary emp_num amount A function is a subprogram that computes a value Functions and procedures are structured alike except that functions have a RETURN clause You write functions using the syntax FUNCTION name parameter parameter RETURN datatype IS local declarations BEGI xecutable statements EXCEPTION exception handlers END name where parameter stands for the following syntax parameter_name IN OUT IN OUT datatype DEFAULT expression Remember you cannot impose the NOT NULL constraint on a parameter and you cannot specify a constraint on the datatype Like a procedure a function has two parts the specification and the body The function specificat
541. ssion This is an expression that yields a date time value numeric_expression This is an expression that yields an integer or real value 11 62 PL SQL User s Guide and Reference Expressions NOT AND OR These are logical operators which follow the tri state logic of Table 2 3 on page 2 43 AND returns the value TRUE only if both its operands are true OR returns the value TRUE if either of its operands is true NOT returns the opposite value logical negation of its operand NOT NULL returns NULL because nulls are indeterminate For more information see Logical Operators on page 2 43 boolean_constant_name This identifies a constant of type BOOLEAN which must be initialized to the value TRUE or FALSE or the non value NULL Arithmetic operations on Boolean constants are illegal boolean_function_call This is any function call that returns a Boolean value boolean_literal This is the predefined value TRUE or FALSE or the non value NULL which stands for a missing unknown or inapplicable value You cannot insert the value TRUE or FALSE into a database column boolean_variable_name This identifies a variable of type BOOLEAN Only the values TRUE and FALSE and the non value NULL can be assigned to a BOOLEAN variable You cannot select or fetch column values into a BOOLEAN variable Also arithmetic operations on Boolean variables are illegal relational_operator This operato
542. store the logical values TRUE and FALSE and the non value NULL which stands for a missing inapplicable or unknown value Only logic operations are allowed on BOOLEAN variables The BOOLEAN datatype takes no parameters Only the values TRUE and FALSE and the non value NULL can be assigned to a BOOLEAN variable You cannot insert the values TRUE and FALSE into a database column Also you cannot select or fetch column values into a BOOLEAN variable DATE You use the DATE datatype to store fixed length date time values DATE values include the time of day in seconds since midnight The date portion defaults to the first day of the current month the time portion defaults to midnight The date function SYSDATE returns the current date and time Valid dates range from January 1 4712 BC to December 31 4712 AD A Julian date is the number of days since January 1 4712 BC Julian dates allow continuous dating from a common reference You can use the date format model J with date functions TO_DATE and TO_CHAR to convert between DATE values and their Julian equivalents Fundamentals 2 21 User Defined Subtypes In date expressions PL SQL automatically converts character values in the default date format to DATE values The default date format is set by the Oracle initialization parameter NLS_DATE_FORMAT For example the default might be DD MON YY which includes a two digit number f
543. support data definition commands such as ALTER and CREATE For an explanation and workaround see Using DDL and Dynamic SQL on page 5 7 Data Manipulation To manipulate Oracle data you use the INSERT UPDATE DELETE SELECT and LOCK TABLE commands INSERT adds new rows of data to database tables UPDATE modifies rows DELETE removes unwanted rows SELECT retrieves rows that meet your search criteria and LOCK TABLE temporarily limits access to a table Transaction Control Oracle is transaction oriented that is Oracle uses transactions to ensure data integrity A transaction is a series of SQL data manipulation statements that does a logical unit of work For example two UPDATE statements might credit one bank account and debit another Simultaneously Oracle makes permanent or undoes all database changes made by a transaction If your program fails in the middle of a transaction Oracle detects the error and rolls back the transaction Thus the database is restored to its former state automatically You use the COMMIT ROLLBACK SAVEPOINT and SET TRANSACTION commands to control transactions COMMIT makes permanent any database changes made during the current transaction ROLLBACK ends the current transaction and undoes any changes made since the transaction began SAVEPOINT marks the current point in the processing of a transaction Used with ROLLBACK SAVEPOI
544. supports just one character set called the database character set which is used for identifiers and source code But PL SQL V8 supports a second character set called the national character set which is used for NLS data The datatypes NCHAR and NVARCHAR2 store character strings formed from the national character set NCHAR You use the NCHAR datatype to store fixed length blank padded if necessary NLS character data How the data is represented internally depends on the national character set which might use a fixed width encoding such as US7ASCII or a variable width encoding such as JA16SJIS The NCHAR datatype takes an optional parameter that lets you specify a maximum length up to 32767 bytes The syntax follows NCHAR maximum_length You cannot use a constant or variable to specify the maximum length you must use an integer literal in the range 1 32767 If you do not specify a maximum length it defaults to 1 How you specify the maximum length depends on the national character set For fixed width character sets you specify the maximum length in characters For variable width character sets you specify it in bytes In the following example the character set is JA16EUCFIXED which is fixed width so you specify the maximum length in characters my_string NCHAR 100 maximum length is 100 characters The maximum width of an NCHAR database column is 2000 bytes So you cannot insert NCHAR values longer than 2000
545. t in subprogram declaration s match es found multiple matches resolve call generate syntax error 7 22 PL SQL User s Guide and Reference Recursion Recursion Avoiding Errors PL SQL declares built in functions globally in package STANDARD Redeclaring them locally is error prone because your local declaration overrides the global declaration Consider the following example in which you declare a function named sign then within the scope of that declaration try to call the built in function SIGN DECLARE x BER BEGI DECLARE FUNCTION sign n NUMBER RETURN NUMBER IS BEGIN IF n lt 0 THEN RETURN 1 ELSE RETURN 1 END IF END BEGI x SIGN 0 assigns 1 to x END x SIGN 0 assigns 0 to x END Inside the sub block PL SQL uses your function definition not the built in definition To call the built in function from inside the sub block you must use dot notation as follows x STANDARD SIGN 0 assigns 0 to x Recursion is a powerful technique for simplifying the design of algorithms Basically recursion means self reference In a recursive mathematical sequence each term is derived by applying a formula to preceding terms The Fibonacci sequence 1 1 2 3 5 8 13 21 which was first used to model the growth of a rabbit colony is an example Each term
546. t offers the following advantages a support for SQL support for object oriented programming a better performance portability a higher productivity integration with Oracle Support for SQL SQL has become the standard database language because it is flexible powerful and easy to learn A few English like commands such as INSERT UPDATE and DELETE make it easy to manipulate the data stored in a relational database SQL is non procedural meaning that you can state what you want done without stating how to do it Oracle determines the best way to carry out your request There is no necessary connection between consecutive statements because Oracle executes SQL statements one at a time PL SQL lets you use all the SOL data manipulation cursor control and transaction control commands as well as all the SQL functions operators and pseudocolumns So you can manipulate Oracle data flexibly and safely Also PL SQL fully supports SQL datatypes That reduces the need to convert data passed between your applications and the database Support for Object Oriented Programming Object types are an ideal object oriented modeling tool which you can use to reduce the cost and time required to build complex applications Besides allowing you to create software components that are modular maintainable and reusable object types allow different teams of programmers to develop software components concurrently By enca
547. t the data as a logical unit Thus records make it easier to organize and represent information The attribute SROWTYPE lets you declare a record that represents a row in a database table However you cannot specify the datatypes of fields in the record or declare fields of your own The datatype RECORD lifts those restrictions and lets you define your own records 4 28 PL SQL User s Guide and Reference Defining and Declaring Records Defining and Declaring Records To create records you define a RECORD type then declare records of that type You can define RECORD types in the declarative part of any PL SQL block subprogram or package using the syntax TYPE type_name IS RECORD field_declaration field_declaration where field_declaration stands for field_name field type NOT NULL DEFAULT expression and where type_nameis a type specifier used later to declare records field_type is any PL SQL datatype except REF CURSOR and expression yields a value of type field_type Note Unlike TABLE and VARRAY types RECORD types cannot be CREATEd and stored in the database You can use TYPE and SROWTYPE to specify field types In the following example you define a RECORD type named Dept Rec DECLARE YPE DeptRec IS RECORD dept_id dept deptno TYPE dept_name VARCHAR2 15 dept_loc VARCHAR2 15 Notice that field declarat
548. t the end of a declarative section after all other program items For example the following procedure declaration is misplaced DECLARE PROCEDURE award_bonus IS misplaced must come last BEGI END rating NUMBER CURSOR cl IS SELECT FROM emp Forward Declarations PL SQL requires that you declare an identifier before using it Therefore you must declare a subprogram before calling it For example the following declaration of procedure award_bonus is illegal because award_bonus calls procedure calc_rating which is not yet declared when the call is made DECLARE PROCEDURE award_bonus IS BEGIN calc_rating undeclared identifier END PROCEDURE calc_rating IS BEGIN END In this case you can solve the problem easily by placing procedure calc_rating before procedure award_bonus However the easy solution does not always work For example suppose the procedures are mutually recursive call each other or you want to define them in alphabetical order PL SQL solves this problem by providing a special subprogram declaration called a forward declaration You can use forward declarations to a define subprograms in logical or alphabetical order a define mutually recursive subprograms see Recursion on page 7 23 group subprograms in a package 7 8 PL SQL User s Guide and Reference De
549. tabase column empno is defined as NOT NULL you can assign a null to the variable my_empno DECLARE my_empno emp empnosTYPE BEGIN my_empno NULL this works Using ROWTYPE The SROWTYPE attribute provides a record type that represents a row in a table or view The record can store an entire row of data selected from the table or fetched from a cursor or strongly typed cursor variable In the example below you declare two records The first record stores a row selected from the emp table The second record stores a row fetched from cursor c1 DECLARE emp_rec emp ROWTYPE CURSOR cl IS SELECT deptno dname loc FROM dept dept_rec cl ROWTYPE Columns in a row and corresponding fields in a record have the same names and datatypes In the following example you select column values into a record named emp_rec DECLARE emp_rec empSROWIYPE se BEGI SELECT INTO emp_rec FROM emp WHERE Fa Fundamentals 2 31 Declarations The column values returned by the SELECT statement are stored in fields To reference a field you use dot notation For example you might reference the dept no field as follows IF emp_rec deptno 20 THEN Also you can assign the value of an expression to a specific field as the following examples show mp_rec ename JOHNSON mp_rec sal emp_rec sal 1 15 I
550. table alias s which is visible in the outer scope of the query Suppose you add a column named a to table s tab2 which appears in the inner subquery When the query is processed an inner capture will occur because the reference to s tab2 a will resolve to column a of table tab2 in schema s You can avoid inner captures by following the rules given in Avoiding Capture on page E 10 According to those rules you should recode the above query as follows SELECT FROM s tabl pl WHERE EXISTS SELECT FROM s tab2 p2 WHERE p2 x pl tab2 a Same Scope Capture Outer Capture In SQL scope a same scope capture occurs when a column is added to one of two tables in the same scope and that column has the same name as a column in the other table Consider the following query and refer to the previous example PROCEDURE proc IS CURSOR cl IS SELECT FROM tabl tab2 WHERE col2 10 In the last example the reference to co12 in the query binds to column col2 in table tab1 If you add a column named co12 to table tab2 the query compiles with errors Thus the reference to co12 is captured by an error An outer capture occurs when a name in an inner scope which once resolved to an entity in an inner scope gets resolved to an entity in an outer scope Fortunately SQL and PL SQL are designed to prevent outer captures Name Resolution E 9 Avoiding Captur
551. table characters including spaces but excluding double quotes Thus the following identifiers are legal XE Y last name on off switch employee s xxx header info The maximum length of a quoted identifier is 30 characters not counting the double quotes Though allowed using PL SQL reserved words as quoted identifiers is a poor programming practice Some PL SQL reserved words are not reserved by SQL For example you can use the PL SOL reserved word TYPE in a CREATE TABLE statement to name a database column But if a SQL statement in your program refers to that column you get a compilation error as the following example shows SELECT acct type bal INTO causes compilation error To prevent the error enclose the uppercase column name in double quotes as follows SELECT acct TYPE bal INTO The column name cannot appear in lower or mixed case unless it was defined that way in the CREATE TABLE statement For example the following statement is invalid SELECT acct type bal INTO causes compilation error Alternatively you can create a view that renames the troublesome column then use the view instead of the base table in SOL statements 2 6 PL SQL User s Guide and Reference Lexical Units Literals A literal is an explicit numeric character string or Boolean value not represented by an
552. table_reference schema_name gt db table name EC dblink_name Keyword and Parameter Description table_reference This specifies a table or view which must be accessible when you execute the DELETE statement and for which you must have DELETE privileges Language Elements 11 49 DELETE Statement Usage Notes THE The operand of THE is a subquery that returns a single column value to the DELETE statement The column value must be a nested table Operator THE informs Oracle that the value is a nested table not a scalar value subquery This is a select statement that provides a value or set of values to the DELETE statement Its syntax is like that of select_into_statement without the INTO clause See SELECT INTO Statement on page 11 139 alias This is another usually short name for the referenced table or view and is typically used in the WHERE clause WHERE search_condition This clause conditionally chooses rows to be deleted from the referenced table or view Only rows that meet the search condition are deleted If you omit the WHERE clause all rows in the table or view are deleted WHERE CURRENT OF cursor_name This clause refers to the latest row processed by the FETCH statement associated with the cursor identified by cursor_name The cursor must be FOR UPDATE and must be open and positioned on a row If the curso
553. tatement allows resources held by an open cursor or cursor variable to be reused No more rows can be fetched from a closed cursor or cursor variable For more information see Managing Cursors on page 5 9 Syntax close_statement gt Keyword and Parameter Description cursor_name This identifies an explicit cursor previously declared within the current scope and currently open cursor_variable_name This identifies a PL SQL cursor variable or parameter previously declared within the current scope and currently open host_cursor_variable_ name This identifies a cursor variable declared in a PL SQL host environment and passed to PL SQL as a bind variable The datatype of the host cursor variable is compatible with the return type of any PL SQL cursor variable Host variables must be prefixed with a colon Usage Notes Once a cursor or cursor variable is closed you can reopen it using the OPEN or OPEN FOR statement respectively If you reopen a cursor without closing it first PL SQL raises the predefined exception CURSOR_ALREADY_OPEN However you need not close a cursor variable before reopening it 11 14 PL SQL User s Guide and Reference CLOSE Statement Example Related Topics If you try to close an already closed or never opened cursor or cursor variable PL SQL raises the predefined exception INVALID_CURSOR In the following example after the last row is fetched and processed
554. ted tables but not index by tables a Nested tables are initially dense but index by tables are initially sparse The following element types are allowed for index by tables but not for nested tables BINARY_INTEGER BOOL PLS_INTEGER POSITIVE POS EAN LONG LONG RAW NATURAL NATURALN TIVEN SIGNTYPE and STRING a Unlike nested table types index by table types are defined using the clause INDEX BY BINARY_INTEG ER a An uninitialized nested table is atomically null that is the table itself is null not its elements but an uninitialized index by table is merely empty So you can apply the IS NULL comparison operator to nested tables but not to index by tables a Atrun time index by tables become non null automatically But nested tables become non null only when explicitly assigned a value a Nested tables can be null but index by tables cannot So the predefined exception COLLECTION_IS_NULL applies only to nested tables Collections and Records 4 3 What Is a Collection a For nested tables the legal subscript range is 1 2147483647 But for index by tables the range is 2147483647 2147483647 So unlike nested tables index by tables can have negative subscripts a Subscripts for a nested table are constrained but subscripts for an index by table are not So the predefined exceptions SUBSCRIPT_OUTSIDE_LIMIT and SUBSCRIPT_BEYOND_COUNT ap
555. tement When evaluated the subquery provides a value or set of values to the statement Often subqueries are used in the WHERE clause For example the following query returns employees not located in Chicago DECLARE CURSOR cl IS SELECT empno ename FROM emp WHERE deptno IN SELECT deptno FROM dept WHERE loc lt gt CHICAGO Using a subquery in the FROM clause the following query returns the number and name of each department with five or more employees DECLARE CURSOR cl IS SELECT tl deptno dname STAFF FROM dept t1 SELECT deptno COUNT STAFF FROM emp GROUP BY deptno t2 WHERE t1 deptno t2 deptno AND STAFF gt 5 Whereas a subquery is evaluated only once per table a correlated subquery is evaluated once per row Consider the query below which returns the name and salary of each employee whose salary exceeds the departmental average For each row in the emp table the correlated subquery computes the average salary for that row s department The row is returned if that row s salary exceeds the average DECLARE CURSOR cl IS SELECT deptno ename sal FROM emp t WHERE sal gt SELECT AVG sal FROM emp WHERE t deptno deptno ORDER BY deptno Implicit Cursors Oracle implicitly opens a cursor to p
556. terless method require an empty parameter list In procedural statements an empty parameter list is optional unless you chain calls in which case it is required for all but the last call You can declare a map method or an order method but not both If you declare either method you can compare objects in SQL and procedural statements However if you declare neither method you can compare objects only in SQL statements and only for equality or inequality Two objects of the same type are equal only if the values of their corresponding attributes are equal Language Elements 11 107 Object Types Like packaged subprograms methods of the same kind functions or procedures can be overloaded That is you can use the same name for different methods if their formal parameters differ in number order or datatype family Every object type has a constructor method constructor for short which is a system defined function with the same name as the object type You use the constructor to initialize and return an instance of that object type PL SQL never calls a constructor implicitly so you must call it explicitly Constructor calls are allowed wherever function calls are allowed Examples In the SQL Plus script below an object type for a stack is defined The last item added to a stack is the first item removed The operations push and pop update the stack while preserving last in first out LIFO behavior The simplest implementation
557. the assignment operator to initialize variables For example the declarations blood_type CHAR 0 valid BOOLEAN FALSE can be rewritten as follows blood_type CHAR DEFAULT 0 valid BOOLEAN DEFAULT FALSE Use DEFAULT for variables that have a typical value Use the assignment operator for variables such as counters and accumulators that have no typical value A couple of examples follow hours_worked INTEGER DEFAULT 40 employee_count INTEGER 0 Fundamentals 2 29 Declarations You can also use DEFAULT to initialize subprogram parameters cursor parameters and fields in a user defined record Using NOT NULL Besides assigning an initial value declarations can impose the NOT NULL constraint as the following example shows acct_id INTEGER 4 NOT NULL 9999 You cannot assign nulls to a variable defined as NOT NULL If you try PL SQL raises the predefined exception VALUE_ERROR The NOT NULL constraint must be followed by an initialization clause For example the following declaration is illegal acct_id INTEGER 5 NOT NULL illegal not initialized Recall that the subtypes NATURALN and POSITIVEN are predefined as NOT NULL For instance the following declarations are equivalent emp_count NATURAL NOT NULL 0 emp_count NATURALN 0 In NATURALN and POSITIVEN declarations the type spe
558. the context pointer is the first parameter passed to the external procedure If you include the PARAMETERS clause and the external routine is a function you must specify the parameter RETURN not RETURN property in the last position For every formal parameter there must be a corresponding parameter in the PARAMETERS clause Also make sure that the datatypes of parameters in the PARAMETERS clause are compatible with those in the C prototype because no implicit conversions are done To check the value of an indicator you can use the constants OCI_IND_NULL and OCI_IND_NOTNULL If the indicator equals OCI_IND_NULL the associated parameter or function result is null If the indicator equals OCI_IND_NOTNULL the parameter or function result is not null With a parameter of type RAW or LONG RAW you must use the property LENGTH Also if that parameter is IN OUT or OUT and null you must set the length of the corresponding C parameter to zero Currently the following restrictions apply to external procedures Language Elements 11 73 External Procedures a This feature is available only on platforms that support DLLs a Only routines callable from C code not C code are supported a You cannot pass PL SQL cursor variables records collections or instances of an object type to an external procedure a Inthe LIBRARY clause you cannot use a database link to specify a remote library
559. the datatype of a cursor variable result value You can use the SROWTYPE attribute in the RETURN clause to provide a record type that represents a row in a database table or a row returned by a cursor or strongly typed cursor variable Also you can use the STYPE attribute to provide the datatype of a previously declared record cursor_name This identifies an explicit cursor previously declared within the current scope cursor_variable_name This identifies a PL SQL cursor variable previously declared within the current scope record_name This identifies a user defined record previously declared within the current scope record_type_name This identifies a RECORD type previously defined within the current scope db_table_name This identifies a database table or view that must be accessible when the declaration is elaborated ROWTYPE This attribute provides a record type that represents a row in a database table or a row fetched from a cursor or strongly typed cursor variable Fields in the record and corresponding columns in the row have the same names and datatypes TYPE This attribute provides the datatype of a previously declared user defined record Language Elements 11 39 Cursor Variables Usage Notes Cursor variables are available to every PL SQL client For example you can declare a cursor variable in a PL SQL host environment such as an OCI or Pro C program then pass it as a bind variable t
560. the entire table all the memory is freed In general do not depend on the interaction between TRIM and DELETE It is better to treat nested tables like fixed size arrays and use only DELETE or to treat them like stacks and use only TRIM and EXTEND Within a subprogram a collection parameter assumes the properties of the argument bound to it So you can apply methods FIRST LAST COUNT and so on to such parameters For varray parameters the value of LIMIT is always derived from the parameter type definition regardless of the parameter mode In the following example you use NEXT to traverse a nested table from which some elements have been deleted i courses FIRST get subscript of first element WHILE i IS NOT NULL LOOP do something with courses i i courses NEXT i get subscript of next element END LOOP In the following example PL SQL executes the assignment statement only if element i exists IF courses EXISTS i THEN courses i new_course END IF Language Elements 11 19 Collection Methods The next example shows that you can use FIRST and LAST to specify the lower and upper bounds of a loop range provided each element in that range exists FOR i IN courses FIRST courses LAST LOOP In the following example you delete elements 2 through 5 from a nested table courses DELETE 2 5 In the next exampl
561. the loop unconditionally available online in file examp12 DECLARE CURSOR numl_cur IS SELECT num FROM numl_tab ORDER BY sequence CURSOR num2_cur IS SELECT num FROM num2_tab ORDER BY sequence numl numl_tab numsTYPE num2 num2_tab numsTYPE pair_num NUMBER 0 BEGIN OPEN numl_cur OPEN num2_cur LOOP loop through the two tables and get pairs of numbers FETCH numl_cur INTO numl FETCH num2_cur INTO num2 IF numl_cur SFOUND AND num2_curSFOUND THEN pair_num pair_num 1 INSERT INTO sum_tab VALUES pair_num numl num2 ELSE EXIT E Language Elements 11 35 Cursor Attributes Si END IF END LOOP CLOSE numl_cur CLOSE num2_cur END The next example uses the same block However instead of using FOUND in an IF statement it uses 3NOTFOUND in an EXIT WHEN statement available online in file examp13 DECLARE CURSOR numl_cur IS SELECT num FROM numl_tab ORDER BY sequence CURSOR num2_cur IS SELECT num FROM num2_tab ORDER BY sequence numl numl_tab numsTYPE num2 num2_tab num TYPE pair_num NUMBER 0 BEGIN OPEN numl_cur OPEN num2_cur LOOP loop through the two tables and get pairs of numbers FETCH numl_cur INTO numl FETCH
562. tifiers to be different lastname last_name Identifiers should be descriptive So avoid obscure names such as cpm Instead use meaningful names such as cost_per_thousand Reserved Words Some identifiers called reserved words have a special syntactic meaning to PL SQL and so should not be redefined For example the words BEGIN and END which bracket the executable part of a block or subprogram are reserved As the next example shows if you try to redefine a reserved word you get a compilation error DECLARE end BOOLEAN illegal causes compilation error However you can embed reserved words in an identifier as the following example shows DECLARE end_of_ game BOOLEAN legal Often reserved words are written in upper case to promote readability However like other PL SOL identifiers reserved words can be written in lower or mixed case For a list of reserved words see Appendix F Fundamentals 2 5 Lexical Units Predefined Identifiers Identifiers globally declared in package STANDARD such as the exception INVALID_NUMBER can be redeclared However redeclaring predefined identifiers is error prone because your local declaration overrides the global declaration Quoted Identifiers For flexibility PL SQL lets you enclose identifiers within double quotes Quoted identifiers are seldom needed but occasionally they can be useful They can contain any sequence of prin
563. tion ccccccccssecssessecseceseceecssesecssesecesessesesseeecseeesecseesaecaueseenees 7 12 Positional Notation cin iaa 7 12 Natned Noti A Hisense 7 12 Mixed Notations ia is 7 12 Parameter Modesto a ecient ic Re a das 7 13 INiModernr rin a 7 13 OUT Moderna aid ld aire is ened 7 13 IN QUT AA A AN 7 14 Parameter Default Vales ad dees hisses eee ees 7 15 Parameter Ali asin A a A dada 7 17 Oyerloading nenea n e p T e csesupden E E veces Seles voreenbenenedosbbes 7 18 IELTS LELO ASIAA E T A E S SE 7 19 How Cals Are Resolved cic a it tists wae oli dicas 7 21 Recursi on iaa ara ida leas 7 23 Recursive S bprogranis ma i roiste aes eiri eea eane tae aa Sha e aE ae aE a Seaia eiei 7 24 Mutual Recurso ie doi 7 26 Recursion versus IteratiON cccessesesscssscsssecesccessecsscecuesessececcessecescecsecessecessecaeeeaseseseesseceseecs 7 27 8 Packages What Is a Package conoci At ta dt AA da bi ici caia 8 2 Advantages of Packages iii iaa lada diia teca e 8 4 Th Package Specification cui daa bites 8 5 Referencing Package Content ccccccccesccssesssssssnsnesesesseesesescecesesssesnenaneseseseeseneseecenesesssnananenens 8 6 Whe Package BOd Yeti in a tio Ted 8 7 vii Some Exam ples sar eA taa dd AA A AAA 8 8 Private versus Public Tlems cito aiii tit oi i de tt 8 14 Overloading ci ii tdi acess oa Se 8 14 Package STAN DARD 0s ciisescssdecessseaneossticisis ess enema ras 8 15 Product specific Packages coi toa 8 16 DBMS STA
564. tion Rules Example 1 BEGIN BEGIN IF X 1 THEN RAISE A ELSIF X 2 THEN RAISE B ELSE RAISE C END IF EXCEPTION WHEN A THEN Exception A is handled See locally then execution resumes END in the enclosing block EXCEPTION WHEN B THEN END 6 12 PL SQL User s Guide and Reference How Exceptions Propagate Figure 6 2 Propagation Rules Example 2 BEGIN BEGIN IF X 1 THEN RAISE A ELSIF X 2 THEN RAISE B ELSE RAISE C END IF EXCEPTION WHEN A THEN Exception B propagates to the first enclosing block with an appropriate handler END EXCEPTION WHEN B THEN Exception B is handled then control passes to the END host environment Figure 6 3 Propagation Rules Example 3 BEGIN BEGIN IF X 1 THEN RAISE A ELSIF X 2 THEN RAISE B ELSE RAISE C END IF EXCEPTION WHEN A THEN END EXCEPTION WHEN B THEN Exception C has no handler so an unhandled exception is returned to the host environment END Error Handling 6 13 Reraising an Exception An exception can propagate beyond its scope that is beyond the block in which it was declared Consider the following example BEGI DECLARE sub block begins past_due EXCEPTION BEGIN IF THEN RAISE past_due END IF END sub block ends X
565. tion can call raise_application_error only from an executing stored subprogram When called raise_application_error ends the subprogram and returns a user defined error number and message to the application The error number and message can be trapped like any Oracle error In the following example you call raise_application_error if an employee s salary is missing CREATE PROCEDURE raise_salary emp_id NUMBER increase NUMBER AS current_salary NUMBER BEGI SELECT sal INTO current_salary FROM emp WHERE empno emp_id IF current_salary IS NULL THEN Issue user defined error message raise_application_error 20101 Salary is missing ELSE UPDATE emp SET sal current_salary increase WHERE empno emp_id END IF END raise_salary Error Handling 6 9 User Defined Exceptions The calling application gets a PL SQL exception which it can process using the error reporting functions SQLCODE and SQLERRM in an OTHERS handler Also it can use the pragma EXCEPTION_INIT to map specific error numbers returned by raise_application_error to exceptions of its own as follows EC SQL EXECUTE DECLARE null_salary EXCEPTION Map error number returned by raise_application_error to user defined exception PRAGMA EXCEPTION_INIT null_salary 20101 BEGIN
566. tion is an ordered group of elements all of the same type Each element has a unique subscript that determines its position in the collection To reference an element you use standard subscripting syntax For example the following call references the fifth element in the nested table of type Staff returned by function new_hires DECLARE YPE Staff IS TABLE OF Employee staffer Employee FUNCTION new_hires hiredate DATE BEGIN ETURN Staff IS vs END BEGI staffer new_hires 10 NOV 96 5 END Collections work like the arrays found in most third generation programming languages They can store instances of an object type and conversely can be attributes of an object type Also collections can be passed as parameters So you can use them to move columns of data into and out of database tables or between client side applications and stored subprograms 1 14 PL SQL User s Guide and Reference Main Features Records You can use the SROWTYPE attribute to declare a record that represents a row in a table or a row fetched from a cursor But with a user defined record you can declare fields of your own Records contain uniquely named fields which can have different datatypes Suppose you have various data about an employee such as name salary and hire date These items are dissimilar in type but logically related A record containing a field f
567. to a collection 1 EXT END n appends n null elements to a collection EXTEND n i appends n copies of the ith element to a collection For example the following statement appends 5 copies of element 1 to nested table courses courses EXTEND 5 1 You cannot use EXTEND to initialize an atomically null collection Also if you impose the NOT NULL constraint on a TABLE or VARRAY type you cannot apply the first two forms of EXTEND to collections of that type EXTEND operates on the internal size of a collection which includes any deleted elements So if EXTEND encounters deleted elements it includes them in its tally PL SQL keeps placeholders for deleted elements so that you can replace them if you wish Consider the following example DECLARE YPE CourseList IS TABLE OF VARCHAR2 10 courses CourseList BEGIN courses CourseList Biol 4412 Psyc 3112 Anth 3001 courses DELETE 3 delete element 3 PL SQL keeps a placeholder for element 3 So the next statement appends element 4 not element 3 courses EXTEND append one null element 4 24 PL SQL User s Guide and Reference El Using Collection Methods Using TRIM Now element 4 exists so the next statement does not raise SUBSCRIPT_BEYOND_COUNT courses 4 Engl 2005
568. to fields in the record and closes the cursor when all rows have been processed Thus the sequence of statements in the loop is executed once for each row that satisfies the query associated with cursor_name cursor_name This identifies an explicit cursor previously declared within the current scope When the cursor FOR loop is entered cursor_name cannot refer to a cursor already opened by an OPEN statement or an enclosing cursor FOR loop record_name This identifies an implicitly declared record The record has the same structure as a row retrieved by cursor_name and is equivalent to a record declared as follows record_name cursor_name SROWTYPE The record is defined only inside the loop You cannot refer to its fields outside the loop The implicit declaration of record_name overrides any other declaration outside the loop So another record with the same name cannot be referenced inside the loop unless a label is used Fields in the record store column values from the implicitly fetched row The fields have the same names and datatypes as their corresponding columns To access field values you use dot notation as follows record_name field_name Select items fetched from the FOR loop cursor must have simple names or if they are expressions must have aliases In the following example wages is an alias for the select item sal NVL comm 0 CURSOR cl IS SELECT empno sal NVL comm 0 wages job
569. trol transfers to its exception handling part which is formatted as follows EXCEPTION WHEN exception_namel THEN handler sequence _of_statementsl WHEN exception_name2 THEN another handler sequence _of_ statement s2 WHEN OTHERS THEN optional handler sequence_of_statements3 To catch raised exceptions you must write exception handlers Each handler consists of a WHEN clause which specifies an exception followed by a sequence of statements to be executed when that exception is raised These statements complete execution of the block or subprogram control does not return to where the exception was raised In other words you cannot resume processing where you left off The optional OTHERS exception handler which is always the last handler in a block or subprogram acts as the handler for all exceptions not named specifically Thus a block or subprogram can have only one OTHERS handler Error Handling 6 15 Handling Raised Exceptions As the following example shows use of the OTHERS handler guarantees that no exception will go unhandled EXCEPTION WHEN THEN handle the error WHEN HEN handle the error WHEN OTHERS THEN handle all other errors END If you want two or more exceptions to execute the same sequence of statements list the exception names in the WHEN clause separating them by the keywo
570. ttribute is required the maximum is 1000 methods are optional Like a variable an attribute is declared with a name and datatype The name must be unique within the object type but can be reused in other object types The datatype can be any Oracle type except LONG and LONG RAW a NCHAR NCLOB and NVARCHAR2 a MLSLABEL and ROWID a the PL SQL specific types BINARY_INTEGER and its subtypes BOOLEAN PLS_INTEGER RECORD REF CURSOR TYPE and SROWTYPE a types defined inside a PL SQL package For example the REAL variables rpart and ipart are attributes of object type Complex defined in the previous section You cannot initialize an attribute in its declaration using the assignment operator or DEFAULT clause Also you cannot impose the NOT NULL constraint on an attribute However objects can be stored in database tables on which you can impose constraints The kind of data structure formed by a set of attributes depends on the real world object being modeled For example to represent a rational number which has a numerator and a denominator you need only two INTEGER variables On the other hand to represent a college student you need several VARCHAR2 variables to hold a name address phone number status and so on plus a VARRAY variable to hold courses and grades The data structure can be very complex For example the datatype of an attribute can be another object type
571. turning unhandled exceptions For an example see Using raise_application_error on page 6 9 DBMS_OUTPUT Package DBMS_OUTPUT enables you to display output from PL SQL blocks and subprograms which makes it easier to test and debug them The procedure put_line outputs information to a buffer in the SGA You display the information by calling the procedure get_Jline or by setting SERVEROUTPUT ON in SQL Plus or Enterprise Manager For example suppose you create the following stored procedure CREATE PROCEDURE calc_payroll payroll IN OUT REAL AS CURSOR cl IS SELECT sal comm FROM emp BEGIN payroll 0 FOR clrec IN cl LOOP clrec comm NVL clrec comm 0 payroll payroll clrec sal clrec comm END LOOP Display debug info dbms_output put_line payroll TO_CHAR payroll END calc_payroll When you issue the following commands SQL Plus displays the value of payroll calculated by the procedure SQL gt SET SERVEROUTPUT ON SQL gt VARIABLE num NUMBER SQL gt EXECUTE calc payroll num 8 16 PL SQL User s Guide and Reference Product specific Packages DBMS_PIPE UTL_FILE UTL_HTTP DBMS_SQL Package DBMS_PIPE allows different sessions to communicate over named pipes A pipe is an area of memory used by one process to pass information to another You can use the procedures pack_message and send
572. uals the higher bound the sequence of statements is executed once FOR i IN 3 3 LOOP assign the value 3 to i sequence_of_statements xecutes one tim END LOOP By default iteration proceeds upward from the lower bound to the higher bound However if you use the keyword REVERSE iteration proceeds downward from the higher bound to the lower bound as the example below shows After each iteration the loop counter is decremented FOR i IN REVERSE 1 3 LOOP assign the values 3 2 1 to i sequence_of_statements xecutes thr times END LOOP Nevertheless you write the range bounds in ascending not descending order Inside a FOR loop the loop counter can be referenced like a constant So the loop counter can appear in expressions but cannot be assigned values as the following example shows FOR ctr IN 1 10 LOOP IF NOT finished THEN INSERT INTO VALUES ctr legal factor ctr 2 legal ELSE ctr 10 illegal END IF END LOOP Iteration Schemes The bounds of a loop range can be literals variables or expressions but must evaluate to integers For example the following iteration schemes are legal J EN 35 545 k IN REVERSE first last step IN 0 TRUNC high low 2 code IN ASCII A ASCII J Control Structures 3 11 Iterative Control LOOP and EXIT Statements As you can see the lower boun
573. ubprograms in the declarative part of any block However you can call local subprograms only from the block in which they are defined Variables and Constants PL SQL allows you to declare constants and variables then use them in SQL and procedural statements anywhere an expression can be used However forward references are not allowed So you must declare a constant or variable before referencing it in other statements including other declarative statements Overview 1 3 Main Features Declaring Variables Variables can have any SQL datatype such as CHAR DATE and NUMBER or any PL SQL datatype such as BOOLEAN and BINARY_INTEGER For example assume that you want to declare a variable named part_no to hold 4 digit numbers and a variable named in_stock to hold the Boolean value TRUE or FALSE You declare these variables as follows part_no NUMBER 4 in_stock BOOLEAN You can also declare nested tables variable size arrays varrays for short and records using the TABLE VARRAY and RECORD composite datatypes Assigning Values to a Variable You can assign values to a variable in two ways The first way uses the assignment operator a colon followed by an equal sign You place the variable to the left of the operator and an expression to the right Some examples follow tax price tax_rate bonus current_salary 0 10 amount TO BER
574. ubtype is derived A subtype associates a base type with a constraint and so defines a subset of values For your convenience PL SQL predefines the following BINARY_INTEGER subtypes NATURAL NATURALN POSITIVE POSITIVEN SIGNTYPE The subtypes NATURAL and POSITIVE let you restrict an integer variable to non negative or positive values respectively NATURALN and POSITIVEN prevent the assigning of nulls to an integer variable SIGNTYPE lets you restrict an integer variable to the values 1 0 and 1 which is useful in programming tri state logic NUMBER You use the NUMBER datatype to store fixed point or floating point numbers of virtually any size Its magnitude range is 1 0E 130 9 99E125 You can specify precision which is the total number of digits and scale which is the number of digits to the right of the decimal point The syntax follows NUMBER precision scale To declare fixed point numbers for which you must specify scale use the following form NUMBER precision scale To declare floating point numbers for which you cannot specify precision or scale because the decimal point can float to any position use the following form NUMBER To declare integers which have no decimal point use this form NUMBER precision same as NUMBER precision 0 You cannot use constants or variables to specify precision and scale you must
575. ubtype when declaring variables of that type DECLARE SUBTYPE Accumulator IS NUMBER total Accumulator 7 2 Subtypes can increase reliability by detecting out of range values In the example below you restrict the subtype Scale to storing integers in the range 9 9 If your program tries to store a number outside that range in a Scale variable PL SQL raises an exception DECLARE temp BER 1 0 SUBTYPE Scale IS temp TYPE x_axis Scale magnitude range is 9 9 y_axis Scale BEGIN x_ axis 10 raises VALUE ERROR Type Compatibility An unconstrained subtype is interchangeable with its base type For example given the following declarations the value of amount can be assigned to total without conversion DECLARE SUBTYPE Accumulator IS NUMBER amount NUMBER 7 2 total Accumulator BEGIN total amount 2 24 PL SQL User s Guide and Reference Datatype Conversion Different subtypes are interchangeable if they have the same base type For instance given the following declarations the value of finished can be assigned to debugging DECLARE SUBTYPE Sentinel IS BOOLEAN SUBTYPE Switch IS BOOLEAN finished Sentinel debugging Switch BEGI debugging finished Different subtypes are also interchangeable if their base types are in the sa
576. uery associated with an explicit cursor It also allocates resources used by Oracle to process the query and identifies the result set which consists of all rows that meet the query search criteria The cursor is positioned before the first row in the result set For more information see Managing Cursors on page 5 9 open_statement cursor_parameter_name cursor_name Keyword and Parameter Description Usage Notes cursor_name This identifies an explicit cursor previously declared within the current scope and not currently open cursor_parameter_name This identifies a cursor parameter that is a variable declared as the formal parameter of a cursor A cursor parameter can appear in a query wherever a constant can appear For the syntax of cursor_parameter_ declaration see Cursors on page 11 45 Generally PL SQL parses an explicit cursor only the first time it is opened and parses a SOL statement thereby creating an implicit cursor only the first time the statement is executed All the parsed SQL statements are cached A SQL statement must be reparsed only if it is bumped out of the cache by a new SQL statement So although you must close a cursor before you can reopen it PL SQL need not reparse the associated SELECT statement If you close then immediately reopen the cursor a reparse is definitely not needed Language Elements 11 111 OPEN Statement Examples Related Topics
577. umns tables or indexes Reserved Words F 1 ABORT ACCEPT ACCESS ADD ALL ALTER AND ANY ARRAY ARRAYLEN AS ASC ASSERT ASSIGN AT AUDIT AUTHORIZATION AVG BASE TABLE BEGIN BETWEEN BINARY_INTEGER BODY BOOLEAN BY CASE CHAR CHAR_BASE CHECK CLOSE CLUSTER CLUSTERS COLAUTH COLUMN COMMENT COMMIT COMPRESS CONNECT CONSTANT CRASH CREATE CURRENT CURRVAL CURSOR DATABASE DATA_BASE DATE BA EBUGOET EBUGON ECLARE ECIMAL EFAULT EFINTION ELAY ygyyyyyygyyyg E DIGITS DISPOSE DISTINCI DO DROP ELSE ELSIF END ENTRY EXCEPTION EXCEPTION_INIT EXCLUSIVE EXISTS EXIT FALSE FETCH FILE FLOAT FOR FORI F F GENERIC GROUP HAVING IDENTIF TED F IMEDIATE T F 2 PL SQL User s Guide and Reference INCREMENT INDEX INDEXES INDICATOR INI TIAL INSERT INTEGER INTERFACE INTERSECT INTO IS IN LEVI EXTENTS US MLSLABEL OD ODE IATURAL IATURALN EW EXTVAL OAUDIT IOCOMPRE SS OT OWAIT ULL BER BER_BASE OF OFF ON LINI El ONLINE OPE OPT OR ORD ION ER OTHERS OUT SOL PACKAGE SOLCODE PARTITION SQLERRI PCTFREE START PLS_INTEGE
578. unt computer screen rational number or data structure such as a queue stack or list This section gives several complete examples which teach you a lot about the design of object types and prepare you to start writing your own Currently you cannot define object types in a PL SQL block subprogram or package However you can define them interactively in SQL Plus or Enterprise Manager using the following syntax CREATE TYPE type_name IS AS OBJECT attribute_name datatype attribute_name datatype MAP ORDER MEMBER function specification BER procedure_specification function_specification restrict_references_pragma B ER procedure_specification function_specification rict_references_pragma CREATE TYPE BODY type_name IS AS MAP ORDER MEMBER function_body MEMBER procedure_body function_body MEMBER procedure_body function_body END Object Type Stack A stack holds an ordered collection of data items As the name implies stacks have a top and a bottom But items can be added or removed only at the top So the last item added to a stack is the first item removed Think of the stack of clean serving trays in a cafeteria The operations push and pop update the stack while preserving last in first out LIFO behavior Stacks have many appl
579. unts account_id number 4 not null bal number 11 2 create unique index accounts_index on accounts account_id drop table action create table action account_id number 4 not null oper_type char 1 not null new_valu number 11 2 status char 45 time tag date not null drop table bins create table bins bin_num number 2 not null part_num number 4 amt_in bin number 4 drop table data_table jf create table data_table exper_num number 2 nl number 5 n2 number 5 n3 number 5 Sample Programs B 3 Running the Programs drop table emp Us create table emp empno number 4 not null ename varchar2 10 job varchar2 9 mgr number 4 hiredate date sal number 7 2 comm number 7 2 deptno number 2 drop table inventory create table inventory prod_id number 5 not null product char 15 quantity number 5 drop table journal create table journal account_id number 4 not null action char 45 not null amount number 11 2 date_tag date not null drop table numl_tab create table numl_tab sequence number 3 not null num number 4 drop table num2_tab create table num2_tab sequence number 3 not null num number 4 drop table purchase_record B 4 PL SQL User s Guide and Reference Running the Programs create table purchase_record mesg char 45 purch_date
580. urTyp declare cursor variable Interaction with Oracle 5 21 Using Cursor Variables As Parameters You can declare cursor variables as the formal parameters of functions and procedures In the following example you define the REF CURSOR type EmpCurTyp then declare a cursor variable of that type as the formal parameter of a procedure DECLARE YPE EmpCurTyp IS REF CURSOR RETURN emp ROWTYPE PROCEDURE open_emp cv emp cv IN OUT EmpCurTyp IS Controlling Cursor Variables You use three statements to control a cursor variable OPEN FOR FETCH and CLOSE First you OPEN a cursor variable FOR a multi row query Then you FETCH rows from the result set one at a time When all the rows are processed you CLOSE the cursor variable Opening a Cursor Variable The OPEN FOR statement associates a cursor variable with a multi row query executes the query and identifies the result set The statement syntax is OPEN cursor_variable_name host_cursor variable name FOR select_ statement where host_cursor_variable_name identifies a cursor variable declared in a PL SQL host environment such as an OCI or Pro C program Unlike cursors cursor variables do not take parameters No flexibility is lost however because you can pass whole queries not just parameters to a cursor var
581. urn product of SELF x r Rational 9 22 PL SQL User s Guide and Reference Declaring and Initializing Objects BEGI r Rational num x num den x den r normalize RETURN r ID times E EMBER FUNCTION divby x Rational RETURN Rational IS return quotient of SELF x r Rational BEGI r Rational num x den den x num r normalize RETURN r END divby END Declaring and Initializing Objects Once an object type is defined and installed in the schema you can use it to declare objects in any PL SQL block subprogram or package For example you can use the object type to specify the datatype of an attribute column variable bind variable record field table element formal parameter or function result At run time instances of the object type are created that is objects of that type are instantiated Each object can hold different values Such objects follow the usual scope and instantiation rules In a block or subprogram local objects are instantiated when you enter the block or subprogram and cease to exist when you exit In a package objects are instantiated when you first reference the package and cease to exist when you end the database session Declaring Objects You can use object types wherever built in types such as CHAR or NUMBER can be used In the block below you declare object r of type Rational Then you call the constru
582. ursor variables to pass query result sets between PL SQL stored subprograms and various clients Neither PL SQL nor any of its clients owns a result set they simply share a pointer to the query work area in which the result set is stored For example an OCI client Oracle Forms application and Oracle server can all refer to the same work area A query work area remains accessible as long as any cursor variable points to it Therefore you can pass the value of a cursor variable freely from one scope to another For example if you pass a host cursor variable to a PL SQL block embedded in a Pro C program the work area to which the cursor variable points remains accessible after the block completes If you have a PL SQL engine on the client side calls from client to server impose no restrictions For example you can declare a cursor variable on the client side open and fetch from it on the server side then continue to fetch from it back on the client side Interaction with Oracle 5 19 Using Cursor Variables Also you can reduce network traffic by having a PL SQL block open or close several host cursor variables in a single round trip Defining REF CURSOR Types To create cursor variables you take two steps First you define a REF CURSOR type then declare cursor variables of that type You can define REF CURSOR types in any PL SQL block subprogram or package using the syntax TYPE ref_type_name IS REF CURSOR RETURN retu
583. use of UGA memory Also Oracle ages out work areas not in use if it needs to reclaim SGA memory For packages without a body you code the pragma in the package specification using the following syntax PRAGMA SERIALLY REUSABLE For packages with a body you must code the pragma in the specification and body You cannot code the pragma only in the body The following example shows how a public variable in a serially reusable package behaves across call boundaries CREATE OR REPLACE PACKAGE sr_pkg IS PRAGMA SERIALLY REUSABLE num NUMBER 0 PROCEDURE init_pkg_state n NUMBI PROCEDURE print_pkg state END sr_pkg El 2 CREATE OR REPLACE PACKAGE BODY sr pkg IS PRAGMA SERIALLY REUSABLE Initialize package state PROCEDURE init_pkg _state n BER IS BEGIN sr_pkg num n END Print package state PROCEDURE print_pkg_state IS BEGI DBMS_OUTPUT PUT_LINE Num is sr_pkg num END END sr_pkg BEGIN Initialize package state sr_pkg init_pkg_state 4 On same server call print package state sr_pkg print_pkg_ state prints 4 END 5 56 PL SQL User s Guide and Reference Processing Transactions subsequent server call BEGIN package s public variable will be initialized to its default value autom
584. ut can be written in any language At run time PL SQL loads the library dynamically then calls the routine as if it were a PL SQL subprogram To safeguard your database the routine runs in a separate address space But it participates fully in the current transaction Furthermore the routine can call back to the database to do SQL operations External procedures promote reusability efficiency and modularity DLLs already written and available in other languages can be called from PL SQL programs The DLLs are loaded only when needed so memory is conserved Moreover the DLLs can be enhanced without affecting the calling programs Typically external procedures are used to interface with embedded systems solve scientific and engineering problems analyze data or control real time devices and processes For example you might use external procedures to send instructions to a robot solve partial differential equations process signals analyze time series or create animation on a video display Moreover external procedures enable you to move computation bound programs from client to server where they will execute faster thanks to more computing power and less across network communication a interface the database server with external systems and data sources a extend the functionality of the database server itself Note This feature is available only on platforms that support DLLs or dynamically loadable shared librari
585. v FOR SELECT FROM dept ELSIF choice 3 THEN OPEN generic_cv FOR SELECT FROM salgrade END IF 1 6 PL SQL User s Guide and Reference Main Features Attributes PL SQL variables and cursors have attributes which are properties that let you reference the datatype and structure of an item without repeating its definition Database columns and tables have similar attributes which you can use to ease maintenance A percent sign serves as the attribute indicator TYPE The TYPE attribute provides the datatype of a variable or database column This is particularly useful when declaring variables that will hold database values For example assume there is a column named title ina table named books To declare a variable named my_tit le that has the same datatype as column title you use dot notation and the TYPE attribute as follows my_title books titlesTYPE se Declaring my_tit le with TYPE has two advantages First you need not know the exact datatype of title Second if you change the database definition of title make it a longer character string for example the datatype of my_title changes accordingly at run time ROWTYPE In PL SQL records are used to group data A record consists of a number of related fields in which data values can be stored The SROWTYPE attribute provides a record type that represents a row in a table The recor
586. variable to a stored subprogram the return types of the actual and formal parameters must be compatible PL SQL runs out of memory or memory is corrupted you reference a nested table or varray element using an index number larger than the number of elements in the collection you reference a nested table or varray element using an index number that is outside the legal range 1 for example a time out occurs while Oracle is waiting for a resource a SELECT INTO statement returns more than one row an arithmetic conversion truncation or size constraint error occurs For example when you select a column value into a character variable if the value is longer than the declared length of the variable PL SQL aborts the assignment and raises VALUE_ERROR In procedural statements VALUE_ERROR is raised if the conversion of a character string to a number fails In SQL statements INVALID_NUMBER is raised you try to divide a number by zero User Defined Exceptions PL SQL lets you define exceptions of your own Unlike predefined exceptions user defined exceptions must be declared and must be raised explicitly by RAIS statements Declaring Exceptions Exceptions can be declared only in the declarative part of a PL SQL block subprogram or package You declare an exception by introducing its name followed by the keyword EXCEPTION In the following example you declare an exception
587. vent the parallelization of a query yield order dependent and therefore indeterminate results or require that package state be maintained across user sessions which is not allowed So the following rules apply to a member function called from SQL statements a Itcannot insert into update or delete from database tables a It cannot be executed remotely or in parallel if it reads or writes the values of packaged variables It cannot write the values of packaged variables unless it is called from a SELECT VALUES or SET clause It cannot call another method or subprogram that breaks one of the foregoing rules Also it cannot reference a view that breaks one of the rules Oracle replaces references to a view with a stored SELECT operation which can include function calls 9 12 PL SQL User s Guide and Reference Components of an Object Type You use the pragma compiler directive RESTRICT_REFERENCES to enforce these rules The pragma tells the PL SQL compiler to deny the member function read write access to database tables packaged variables or both In the object type specification you code the pragma somewhere after the method to which it applies The syntax follows PRAGMA RESTRICT_REFERENCES DEFAULT method_name RNDS WNDS RNPS WNPS RNDS WNDS RNPS WNPS For example the following pragma constrains map method con
588. veral alternatives in a conditional control statement When called the procedure opens the cursor variable emp_ cv for the chosen query CREATE PACKAGE emp_data AS YPE GenericCurTyp IS REF CURSOR YPE EmpCurTyp IS REF CURSOR RETURN empSROWTYP PROCEDURE open_emp_cv emp_cv IN OUT EmpCurTyp choice IN BER E E 4 D emp_data CREATE PACKAGE BODY emp_data AS PROCEDURE open emp cv emp cv IN OUT EmpCurTyp choice IN N ER IS UY BEGI IF choice 1 THEN OPEN emp_cv FOR SELECT FROM emp WHERE comm IS NOT NULL SIF choice 2 THE OPEN emp_cv FOR SELECT FROM emp WHERE sal gt 2500 ELSIF choice 3 THE OPEN emp_cv FOR SELECT FROM emp WHERE deptno 20 ND IF END open_emp_cv END emp_data 1 E For more flexibility you can pass a cursor variable and selector to a stored procedure that executes queries with different return types Consider the following example CREATE PACKAGE BODY emp_data AS PROCEDURE open_cv generic_cv IN OUT GenericCurTyp choice IN BER IS BEGIN IF choice 1 THEN OPEN generic_cv FOR SELECT FROM emp 5 24 PL SQL User s Guide and Reference Using Cursor Variables Tj E OPI y
589. veral examples follow Fundamentals 2 7 Lexical Units Character literals include all the printable characters in the PL SQL character set letters numerals spaces and special symbols PL SQL is case sensitive within character literals For example PL SQL considers the literals Z and z to be different The character literals 0 9 are not equivalent to integer literals but can be used in arithmetic expressions because they are implicitly convertible to integers String Literals A character value can be represented by an identifier or explicitly written as a string literal which is a sequence of zero or more characters enclosed by single quotes Several examples follow Hello world XYZ Corporation 10 NOV 91 He said Life is like licking honey from a thorn 1 000 000 All string literals except the null string have datatype CHAR Given that apostrophes single quotes delimit string literals how do you represent an apostrophe within a string As the next example shows you write two single quotes which is not the same as writing a double quote Don t leave without saving your work PL SQL is case sensitive within string literals For example PL SQL considers the following literals to be different baker Baker Boolean Literals Boolean literals are the predefined values TRUE and FALSE and the non value NULL which stands for a
590. vert to read no database state RNDS write no database state WNDS read no package state RNPS and write no package state WNP S CREATE TYPE Rational AS OBJECT num INTEGER den INTEGER MAP MEMBER FUNCTION convert RETURN REAL PRAGMA RESTRICT_REFERENCES convert RNDS WNDS RNPS WNPS y You can specify up to four constraints in any order To call the method from parallel queries you must specify all four constraints No constraint implies another For example WNPS does not imply RNPS If you specify the keyword DEFAULT instead of a method name the pragma applies to all member functions including the system defined constructor For example the following pragma constrains all member functions to write no database or package state PRAGMA RESTRICT_REFERENCES DEFAULT WNDS WNPS You can declare the pragma for any member function Such pragmas override the default pragma However a non default pragma can apply to only one method So among overloaded methods the pragma always applies to the nearest preceding method For more information about pragma RESTRICT_REFERENCES see Oracle8 Application Developer s Guide Object Types 9 13 Defining Object Types Defining Object Types An object type can represent any real world entity For example an object type can represent a student bank acco
591. xecutes the assignment statement only if element i exists IF courses EXISTS i THEN courses i new_course When passed an out of range subscript EXISTS returns FALSE instead of raising SUBSCRIPT_OUTSIDE_LIMIT COUNT returns the number of elements that a collection currently contains For instance if varray projects contains 15 elements the following IF condition is true IF projects COUNT 15 THEN COUNT is useful because the current size of a collection is not always known For example if you fetch a column of Oracle data into a nested table how many elements does the table contain COUNT gives you the answer You can use COUNT wherever an integer expression is allowed In the next example you use COUNT to specify the upper bound of a loop range FOR i IN 1 courses COUNT LOOP For varrays COUNT always equals LAST For nested tables COUNT normally equals LAST But if you delete elements from the middle of a nested table COUNT becomes smaller than LAST When tallying elements COUNT ignores deleted elements For nested tables which have no maximum size LIMIT returns NULL For varrays LIMIT returns the maximum number of elements that a varray can contain which you specify in its type definition For instance if the maximum size of varray projects is 25 elements the following IF condition is true IF projects LIMIT 25 THEN 4 22 PL SQL User
592. y by allowing for realistic data modeling Complex real world entities and relationships map directly into object types And a well constructed object model can improve application performance by eliminating table joins reducing round trips and so on Client programs including PL SQL programs can declare objects and collections pass them as parameters store them in the database retrieve them and so on Also by encapsulating operations with data object types let you move data maintenance code out of SQL scripts and PL SQL blocks into methods 5 54 PL SQL User s Guide and Reference Processing Transactions Objects and collections are more efficient to store and retrieve because they can be manipulated as a whole Also object support is integrated architecturally with the database so it can take advantage of the many scalability and performance improvements built into Oracle8 Use the RETURNING Clause Often applications need information about the row affected by a SQL operation for example to generate a report or take a subsequent action The INSERT UPDATE and DELETE statements can include a RETURNING clause which returns column values from the affected row into PL SQL variables or host variables This eliminates the need to SELECT the row after an insert or update or before a delete The results are fewer network round trips less server CPU use and because fewer cursors are used less server memory use
593. y to complete the application Information Hiding With packages you can specify which types items and subprograms are public visible and accessible or private hidden and inaccessible For example if a package contains four subprograms three might be public and one private The package hides the definition of the private subprogram so that only the package not your application is affected if the definition changes This simplifies maintenance and enhancement Also by hiding implementation details from users you protect the integrity of the package Added Functionality Packaged public variables and cursors persist for the duration of a session So they can be shared by all subprograms that execute in the environment Also they allow you to maintain data across transactions without having to store it in the database 8 4 PL SQL User s Guide and Reference The Package Specification Better Performance When you call a packaged subprogram for the first time the whole package is loaded into memory So later calls to related subprograms in the package require no disk I O Also packages stop cascading dependencies and so avoid unnecessary recompiling For example if you change the definition of a packaged function Oracle need not recompile the calling subprograms because they do not depend on the package body The Package Specification The package specification contains public declarations The scope of these declaratio
594. you assign the non value NULL to an object the object becomes atomically null as the following example shows DECLARE r Rational BEGIN r Rational Rational 1 2 r becomes 1 2 r NULL r becomes atomically null IF r IS NULL THEN condition yields TRUE A good programming practice is to initialize an object in its declaration as shown in the following example DECLARE r Rational Rational 2 3 r becomes 2 3 9 24 PL SQL User s Guide and Reference Accessing Attributes How PL SQL Treats Uninitialized Objects In an expression attributes of an uninitialized object evaluate to NULL Trying to assign values to attributes of an uninitialized object raises the predefined exception ACCESS_INTO_NULL When applied to an uninitialized object or its attributes the IS NULL comparison operator yields TRU E The following example illustrates the difference between null objects and objects with null attributes DECLARE r Rational r is atomically null BEGIN IF r IS NULL THEN yields TRUE IF r num IS NULL THEN yields TRUE r Rational NULL NULL initializes r r num 4 succeeds because r is no longer atomically null even though all its attributes are null r NULL r becomes atomically null again r num 4 raises ACCESS_INTO_NULL EXCEPTION WHEN ACCESS_I
595. ype Rational inits rows Such tables having rows of objects are called object tables Each column ina row corresponds to an attribute of the object type Rows can have different column values CREATE TABLE rational_nums OF Rational Each row in an object table has an object identifier which uniquely identifies the object stored in that row and serves as a reference to the object Object Types 9 31 Manipulating Objects Selecting Objects Assume that you have run the following SOL Plus script which creates object type Person and object table persons and that you have populated the table CREATE TYPE Person AS OBJECT first_name VARCHARZ2 15 last_name VARCHAR2 15 birthday DATE home_address Address phone_number VARCHAR2 15 CREATE TABLE persons OF Person The following subquery produces a result set of rows containing only the attributes of Person objects BEGIN INSERT INTO employees another object table of type Person SELECT FROM persons p WHERE p last_name LIKE Smith To return a result set of objects you must use the operator VALUE which is discussed in the next section Using Operator VALUE As you might expect the operator VALUE returns the value of an object VALUE takes as its argument a correlation variable In this context a correlation variable is a row variable or table alias associated with a
596. ystem generated store table in which Oracle stores data out of line in another tablespace Now you can populate database table department In the following example notice how table constructor CourseList provides values for column courses B EGIN INSERT INTO department VALUES Psychology Irene Friedman Fulton Hall 133 CourseList Course 1000 Course 2100 Course 2200 Course 2250 Course 3540 Course 3552 Course 4210 Course 4320 Course 4410 INSERT INTO department General Psychology 5 Experimental Psychology 4 Psychological Tests 3 Behavior Modification 4 Groups and Organizations 3 Human Factors in the Workplace 4 Theories of Learning 4 Cognitive Processes 4 Abnormal Psychology 4 VALUES History John Whalen Applegate Hall 142 CourseList Course 1011 Course 1012 Course 1202 Course 2130 Course 2132 Course 3105 Course 3321 Course 3601 Course 3702 INSERT INTO department History of Europe I 4 History of Europe II 4 American History 5 The Renaissance 3 The Reformation 3 History of Ancient Greece 4 Early Japan 4 Latin America Since 1825 4 Medieval Islamic History 4 VALUES English Lynn Saunders Breakstone Hall 205 CourseList Course 1002 Course 2020 Course 2418 Course 2810
Download Pdf Manuals
Related Search
Related Contents
Desa VTGF33NRA User's Manual Casio MA0611-EC User's Manual Dell G2410 User's Manual Samsung PE46C NIプライマー DVD-A11 ACUPNL-7920 Series Manual Manual de Aplicación USER MANUAL - Project Magenta Copyright © All rights reserved.
Failed to retrieve file