By Steven Feuerstein, Bill Pribyl & Chip Dawes; ISBN 1-56592-457-6E First Edition, published 1999-04-01. (See the catalog page for this book.)
Search the text of Oracle PL/SQL Language Pocket Reference.
Table of Contents Chapter 1: Oracle PL/SQL Language Pocket Reference 1.1: Introduction 1.2: Acknowledgments 1.3: Conventions 1.4: PL/SQL Language Fundamentals 1.5: Variables and Program Data 1.6: Conditional and Sequential Control 1.7: Loops 1.8: Database Interaction and Cursors 1.9: Cursors in PL/SQL 1.10: Exception Handling 1.11: Records in PL/SQL 1.12: Named Program Units 1.13: Triggers 1.14: Packages 1.15: Calling PL/SQL Functions in SQL 1.16: Oracle8 Objects 1.17: Collections 1.18: External Procedures 1.19: Java Language Integration
The Oracle PL/SQL CD Bookshelf Navigation Copyright © 2000 O'Reilly & Associates. All Rights Reserved.
Full Text Search
If you are having difficulty searching, or if you have not used this search utility before, please read this.
The Oracle PL/SQL CD Bookshelf Navigation
Chapter 1
Next: 1.2 Acknowledgments
1. Oracle PL/SQL Language Pocket Reference Contents: Introduction Acknowledgments Conventions PL/SQL Language Fundamentals Variables and Program Data Conditional and Sequential Control Loops Database Interaction and Cursors Cursors in PL/SQL Exception Handling Records in PL/SQL Named Program Units Triggers Packages Calling PL/SQL Functions in SQL Oracle8 Objects Collections External Procedures Java Language Integration
1.1 Introduction The Oracle PL/SQL Language Pocket Reference is a quick reference guide to the PL/SQL programming language, which provides procedural extensions to the SQL relational database language and a range of Oracle development tools. Where a package, program, or function is supported only for a particular version of Oracle (e.g., Oracle8i), we indicate this in the text.
The purpose of this pocket reference is to help PL/SQL users find the syntax of specific language elements. It is not a self-contained user guide; basic knowledge of the PL/SQL programming language is required. For more information, see the following books: Oracle PL/SQL Programming, 2nd Edition, by Steven Feuerstein with Bill Pribyl (O'Reilly & Associates, 1997). Oracle Built-in Packages, by Steven Feuerstein, Charles Dye, and John Beresniewicz (O'Reilly & Associates, 1998). Oracle PL/SQL Built-ins Pocket Reference, by Steven Feuerstein, John Beresniewicz, and Chip Dawes (O'Reilly & Associates, 1998).
Oracle PL/SQL Language Pocket Reference
The Oracle Library Navigation Copyright (c) 2000 O'Reilly & Associates. All rights reserved.
Next: 1.2 Acknowledgments 1.2 Acknowledgments
Previous: 1.1 Introduction
Chapter 1 Oracle PL/SQL Language Pocket Reference
Next: 1.3 Conventions
1.2 Acknowledgments We would like to thank our reviewers: Eric J. Givler, Department of Environmental Protection, Harrisburg, Pennsylvania; and Stephen Nelson, HK Systems, New Berlin, Wisconsin.
Previous: 1.1 Introduction
Oracle PL/SQL Language Pocket Reference
1.1 Introduction The Oracle Library Navigation Copyright (c) 2000 O'Reilly & Associates. All rights reserved.
Next: 1.3 Conventions 1.3 Conventions
Previous: 1.2 Acknowledgments
Chapter 1 Oracle PL/SQL Language Pocket Reference
Next: 1.4 PL/SQL Language Fundamentals
1.3 Conventions UPPERCASE indicates PL/SQL keywords. lowercase indicates user-defined items such as parameters. Italic indicates file names and parameters within text. Constant width is used for code examples. [] enclose optional items in syntax descriptions. { } enclose a list of items in syntax descriptions; you must choose one item from the list. | separates bracketed list items in syntax descriptions.
Previous: 1.2 Acknowledgments 1.2 Acknowledgments
Oracle PL/SQL Language Pocket Reference
The Oracle Library Navigation Copyright (c) 2000 O'Reilly & Associates. All rights reserved.
Next: 1.4 PL/SQL Language Fundamentals 1.4 PL/SQL Language Fundamentals
Previous: 1.3 Conventions
Chapter 1 Oracle PL/SQL Language Pocket Reference
Next: 1.5 Variables and Program Data
1.4 PL/SQL Language Fundamentals 1.4.1 The PL/SQL Character Set The PL/SQL language is constructed from letters, digits, symbols, and whitespace, as defined in the following table. Type
Characters
Letters
A-Z, a-z
Digits
0-9
Symbols
~!@#$%&*()_-+=|[ ]{ }:;"'< >?/
Whitespace space, tab, carriage return Characters are grouped together into the four lexical units: identifiers, literals, delimiters, and comments. 1.4.1.1 Identifiers Identifiers are names for PL/SQL objects such as constants, variables, exceptions, procedures, cursors, and reserved words. Identifiers: ● ● ● ● ●
Can be up to 30 characters in length Cannot include whitespace (space, tab, carriage return) Must start with a letter Can include a dollar sign ($), an underscore ( _ ), and a pound sign (#) Are not case-sensitive
If you enclose an identifier within double quotes, then all but the first of these rules are ignored. For
example, the following declaration is valid: DECLARE "1 ^abc" VARCHAR2(100); BEGIN IF "1 ^abc" IS NULL THEN ... END; 1.4.1.2 Literals Literals are specific values not represented by identifiers. For example, TRUE, 3.14159, 6.63E-34, `Moby Dick', and NULL are all literals of type Boolean, number, or string. There are no date or complex datatype literals as they are internal representations. Unlike the rest of PL/SQL, literals are case-sensitive. To embed single quotes within a string literal, place two single quotes next to each other. See the following table for examples. Literal
Actual Value
'That''s Entertainment!' That's Entertainment! '"The Raven"'
"The Raven"
'TZ="CDT6CST"'
TZ='CDT6CST'
''''
'
'''hello world'''
'hello world'
''''''
''
1.4.1.3 Delimiters Delimiters are symbols with special meaning, such as := (assignment operator), || (concatenation operator), and ; (statement delimiter). The following table lists delimiters. Delimiter
Description
;
Statement terminator
+
Addition operator
-
Subtraction operator
*
Multiplication operator
/
Division operator
**
Exponentiation operator
||
Concatenation operator
:=
Assignment operator
=
Equality operator
<> and != Inequality operators ^= and ~= Inequality operators <
"Less than" operator
<=
"Less than or equal to" operator
>
"Greater than" operator
>=
"Greater than or equal to" operator
( and )
Expression or list delimiters
<< and >> Label delimiters ,
Item separator
`
Literal delimiter
"
Quoted literal delimiter
:
Host variable indicator
%
Attribute indicator
.
Component indicator (as in record.field or package.element)
@
Remote database indicator (database link)
=>
Association operator (named notation)
..
Range operator (used in the FOR loop)
--
Single-line comment indicator
/* and */ Multiline comment delimiters 1.4.1.4 Comments Comments are sections of the code that exist to aid readability. The compiler ignores them. A single-line comment begins with a double hyphen (‐‐) and ends with a new line. The compiler ignores all characters between the ‐‐ and the new line. Multiline comments begin with slash asterisk (/*) and end with asterisk slash (*/). The /* */ comment
delimiters can also be used on a single-line comment. The following block demonstrates both kinds of comments: DECLARE -- Two dashes comment out only the physical line. /* Everything is a comment until the compiler encounters the following symbol */ You cannot embed multiline comments within a multiline comment, so care needs to be exercised during development if you comment out portions of code that include comments. The following code demonstrates: DECLARE /* Everything is a comment until the compiler /* This comment inside another WON'T work!*/ encounters the following symbol. */ /* Everything is a comment until the compiler -- This comment inside another WILL work! encounters the following symbol. */ 1.4.1.5 Pragmas The PRAGMA keyword is used to give instructions to the compiler. There are four types of pragmas in PL/SQL: EXCEPTION_INIT Tells the compiler to associate the specified error number with an identifier that has been declared an EXCEPTION in your current program or an accessible package. See the Section 1.10, "Exception Handling " section for more information on this pragma. RESTRICT_REFERENCES Tells the compiler the purity level of a packaged program. The purity level is the degree to which a program does not read/write database tables and/or package variables. See the Section 1.15, "Calling PL/SQL Functions in SQL" section for more information on this pragma. SERIALLY_REUSABLE Tells the runtime engine that package data should not persist between references. This is used to reduce per-user memory requirements when the package data is only needed for the duration of the call and not for the duration of the session. See the Section 1.14, "Packages" section for more information on this pragma. AUTONOMOUS_TRANSACTION (Oracle8i )
Tells the compiler that the function, procedure, top-level anonymous PL/SQL block, object method, or database trigger executes in its own transaction space. See the Section 1.8, "Database Interaction and Cursors " section for more information on this pragma. 1.4.1.6 Statements A PL/SQL program is composed of one or more logical statements. A statement is terminated by a semicolon delimiter. The physical end-of-line marker in a PL/SQL program is ignored by the compiler, except to terminate a single-line comment (initiated by the ‐‐ symbol). 1.4.1.7 Block structure Each PL/SQL program is a block consisting of a standard set of elements, identified by keywords (see Figure 1.1). The block determines the scope of declared elements, and how exceptions are handled and propagated. A block can be anonymous or named. Named blocks include functions, procedures, packages, and triggers. Here is an example of an anonymous block: DECLARE whoops NUMBER DEFAULT 99; BEGIN -- Display a two-digit year number. DBMS_OUTPUT.PUT_LINE ('What century? END;
' || whoops);
Here is a named block that performs the same action: CREATE OR REPLACE PROCEDURE show_the_problem IS whoops NUMBER DEFAULT 99; BEGIN -- Display a two-digit year number. DBMS_OUTPUT.PUT_LINE ('What century? ' || whoops); END show_the_problem; Figure 1.1: The PL/SQL block structure
The following table describes the sections of a PL/SQL block: Section
Description
Header
Required for named blocks. Specifies the way the program is called by outer PL/ SQL blocks. Anonymous blocks do not have a header. They start with the DECLARE keyword if there is a declaration section, or with the BEGIN keyword if there are no declarations.
Declaration Optional; declares variables, cursors, TYPEs, and local programs that are used in the block's execution and exception sections. Execution
Optional in package and type specifications; contains statements that are executed when the block is run.
Exception
Optional; describes error handling behavior for exceptions raised in the executable section.
Previous: 1.3 Conventions
Oracle PL/SQL Language Pocket Reference
1.3 Conventions
The Oracle Library Navigation Copyright (c) 2000 O'Reilly & Associates. All rights reserved.
Next: 1.5 Variables and Program Data 1.5 Variables and Program Data
Previous: 1.4 PL/SQL Language Fundamentals
Chapter 1 Oracle PL/SQL Language Pocket Reference
Next: 1.6 Conditional and Sequential Control
1.5 Variables and Program Data PL/SQL programs are normally used to manipulate database information. You commonly do this by declaring variables and data structures in your programs, and then working with that PL/SQL-specific data. A variable is a named instantiation of a data structure declared in a PL/SQL block (either locally or in a package). Unless you declare a variable as a CONSTANT, its value can be changed at any time in your program. The following table describes several types of program data. Type
Description
Scalar
Variables made up of a single value, such as a number, date, or Boolean.
Composite Variables made up of multiple values, such as a record or collection. Reference Pointers to values. LOB
Variables containing Large OBject (LOB) locators.
1.5.1 Scalar Datatypes Scalar datatypes divide into four families: number, character, date-time, and Boolean. 1.5.1.1 Numeric datatypes Numeric datatypes are further divided into decimal, binary integer, and PLS_INTEGER storage types. Decimal numeric datatypes store fixed and floating-point numbers of just about any size. They
include NUMBER, DEC, DECIMAL, NUMERIC, FLOAT, REAL, and DOUBLE PRECISION. The maximum precision of a variable with type NUMBER is 38 digits, which yields a range of values from 1.0E-129 through 9.999E125. This range of numbers would include the mass of an electron over the mass of the universe or the size of the universe in angstroms. Variables of type NUMBER can be declared with precision and scale, as follows: NUMBER(precision, scale) Precision is the number of digits, and scale denotes the number of digits to the right (positive scale) or left (negative scale) of the decimal point at which rounding occurs. Legal values for the scale range from -84 to 127. The following table shows examples of precision and scale. Declaration
Assigned Value Stored Value
NUMBER
6.02
6.02
NUMBER(4)
8675
8675
NUMBER(4)
8675309
Error
NUMBER(12,5)
3.14159265
3.14159
NUMBER(12,-5) 8675309
8700000
Binary integer numeric datatypes store whole numbers. They include BINARY_INTEGER, INTEGER, INT, SMALLINT, NATURAL, NATURALN, POSITIVE, POSITIVEN, and SIGNTYPE. Binary integer datatypes store signed integers in the range of -231 + 1 to 231 - 1. The subtypes include NATURAL (0 through 231) and POSITIVE (1 through 231) together with the NOT NULL variations NATURALN and POSITIVEN. SIGNTYPE is restricted to three values (-1, 0, 1). PLS_INTEGER datatypes have the same range as the BINARY_INTEGER datatype, but use machine arithmetic instead of library arithmetic, so are slightly faster for computation-heavy processing. The following table lists the PL/SQL numeric datatypes with ANSI and IBM compatibility. PL/SQL Datatype
Compatibility Oracle RDNMS Datatype
DEC(prec,scale)
ANSI
NUMBER(prec,scale)
DECIMAL(prec,scale) IBM
NUMBER(prec,scale)
DOUBLE PRECISION ANSI
NUMBER
FLOAT(binary)
ANSI, IBM
NUMBER
INT
ANSI
NUMBER(38)
INTEGER
ANSI, IBM
NUMBER(38)
NUMERIC(prec,scale) ANSI
NUMBER(prec,scale)
REAL
ANSI
NUMBER
SMALLINT
ANSI, IBM
NUMBER(38)
In the preceding table: ● ● ●
prec is the precision for the subtype. scale is the scale of the subtype. binary is the binary precision of the subtype.
1.5.1.2 Character datatypes Character datatypes store alphanumeric text and are manipulated by character functions. As with the numeric family, there are several subtypes in the character family, shown in the following table. Family
Description
CHAR
Fixed-length alphanumeric strings. Valid sizes are 1 to 32767 bytes (which is larger than the Oracle7 limit of 2000 and the Oracle8 limit of 4000).
VARCHAR2
Variable-length alphanumeric strings. Valid sizes are 1 to 32767 bytes (which is larger than the Oracle7 limit of 2000 and the Oracle8 limit of 4000).
LONG
Variable-length alphanumeric strings. Valid sizes are 1 to 32760 bytes. LONG is included primarily for backward compatibility since longer strings can now be stored in VARCHAR2 variables.
RAW
Variable-length binary strings. Valid sizes are 1 to 32767 bytes (which is larger than the Oracle7 and Oracle8 limit of 2000). RAW data do not undergo character set conversion when selected from a remote database.
LONG RAW
Variable-length binary strings. Valid sizes are 1 to 32760 bytes. LONG RAW is included primarily for backward compatibility since longer strings can now be stored in RAW variables.
ROWID
Fixed-length binary data. Every row in a database has a physical address or ROWID. An Oracle7 (restricted) ROWID has 3 parts in base 16 (hex): BBBBBBBB.RRRR.FFFF. An Oracle8 (extended) ROWID has 4 parts in base 64: OOOOOOFFFBBBBBBRRR. where: OOOOOO is the object number. FFFF (FFF) is the absolute (Oracle 7) or relative (Oracle8) file number. BBBBBBBB (BBBBBB) is the block number within the file. RRRR (RRR) is the row number within the block.
UROWID (Oracle8i) Universal ROWID. Variable-length hexadecimal string depicting a logical ROWID. Valid sizes are up to 4000 bytes. Used to store the addresses of rows in index organized tables or IBM DB2 tables via Gateway. 1.5.1.3 Date-time datatypes DATE values are fixed-length, date-plus-time values. The DATE datatype can store dates from January 1, 4712 B.C. to December 31, 4712 A.D. Each DATE includes the century, year, month, day, hour, minute, and second. Sub-second granularity is not supported via the DATE datatype. The time portion of a DATE defaults to midnight (12:00:00 AM) if it is not included explicitly. The internal calendar follows the Papal standard of Julian to Gregorian conversion in 1582 rather than the English standard (1752) found in many operating systems. 1.5.1.4 Boolean datatype The BOOLEAN datatype can store one of only three values: TRUE, FALSE, or NULL. BOOLEAN variables are usually used in logical control structures such as IF...THEN or LOOP statements. Following are truth tables showing the results of logical AND, OR, and NOT operations with PL/ SQL's three-value Boolean model.
AND
TRUE FALSE NULL
TRUE
TRUE
FALSE NULL
FALSE FALSE FALSE FALSE NULL
NULL
FALSE NULL
OR
TRUE FALSE NULL
TRUE
TRUE TRUE
TRUE
FALSE TRUE FALSE NULL NULL
TRUE NULL
NULL
NOT (TRUE) NOT (FALSE) NOT (NULL) FALSE
TRUE
NULL
1.5.2 NLS Character Datatypes The standard ASCII character set does not support some languages, such as Chinese, Japanese, or Korean. To support these multibyte character sets, PL/SQL8 supports two character sets, the database character set and the national character set (NLS). There are two datatypes, NCHAR and NVARCHAR2, that can be used to store data in the national character set. NCHAR values are fixed-length NLS character data; the maximum length is 32767 bytes. For variable-length character sets (like JA16SJIS), the length specification is in bytes; for fixed-length character sets, it is in characters. NVARCHAR2 values are variable-length NLS character data. The maximum length is 32767 bytes, and the length specification follows the same fixed/variable-length rule as NCHAR values.
1.5.3 LOB Datatypes PL/SQL8 supports a number of Large OBject (LOB) datatypes, which can store objects of up to four gigabytes of data. Unlike the scalar datatypes, variables declared for LOBs use locators, or pointers to the actual data. LOBs are manipulated in PL/SQL using the built-in package DBMS_LOB. BFILE
File locators pointing to read-only large binary objects in operating system files. With BFILEs, the large objects are outside the database. BLOB LOB locators that point to large binary objects inside the database. CLOB LOB locators that point to large "character" (alphanumeric) objects inside the database. NCLOB LOB locators that point to large national character set objects inside the database.
1.5.4 NULLs in PL/SQL PL/SQL represents unknown values as NULL values. Since a NULL is unknown, a NULL is never equal or not equal to anything (including another NULL value). Additionally, most functions return a NULL when passed a NULL argument -- the notable exceptions are NVL, CONCAT, and REPLACE. You cannot check for equality or inequality to NULL; therefore, you must use the IS NULL or IS NOT NULL syntax to check for NULL values. Here is an example of the IS NULL syntax to check the value of a variable: BEGIN IF myvar IS NULL THEN ...
1.5.5 Declaring Variables Before you can use a variable, you must first declare it in the declaration section of your PL/SQL block or in a package as a global. When you declare a variable, PL/SQL allocates memory for the variable's value and names the storage location so that the value can be retrieved and changed. The syntax for a variable declaration is: variable_name datatype [CONSTANT] [NOT NULL] [:= | DEFAULT initial_value] 1.5.5.1 Constrained declarations The datatype in a declaration can be constrained or unconstrained. Constrained datatypes have a size, scale, or precision limit that is less than the unconstrained datatype. For example: total_sales emp_id
NUMBER(15,2); VARCHAR2(9);
-- Constrained. -- Constrained.
company_number NUMBER; book_title VARCHAR2;
-- Unconstrained. -- Not valid.
Constrained declarations require less memory than unconstrained declarations. Not all datatypes can be specified as unconstrained. You cannot, for example, declare a variable to be of type VARCHAR2. You must always specify the maximum size of a variable-length string. 1.5.5.2 Constants The CONSTANT keyword in a declaration requires an initial value and does not allow that value to be changed. For example: min_order_qty
NUMBER(1) CONSTANT := 5;
1.5.5.3 Default values Whenever you declare a variable, it is assigned a default value of NULL. Initializing all variables is distinctive to PL/SQL; in this way, PL/SQL differs from languages such as C and Ada. If you want to initialize a variable to a value other than NULL, you do so in the declaration with either the assignment operator (:=) or the DEFAULT keyword: counter priority
BINARY_INTEGER := 0; VARCHAR2(8) DEFAULT 'LOW';
A NOT NULL constraint can be appended to the variable's datatype declaration to indicate that NULL is not a valid value. If you add the NOT NULL constraint, you must explicitly assign an initial value for that variable.
1.5.6 Anchored Declarations Use the %TYPE attribute to anchor the datatype of a scalar variable to either another variable or to a column in a database table or view. Use %ROWTYPE to anchor a record's declaration to a cursor or table (see the Section 1.11, "Records in PL/SQL" section for more detail on the %ROWTYPE attribute). The following block shows several variations of anchored declarations: DECLARE tot_sales NUMBER(20,2); -- Anchor to a PL/SQL variable. monthly_sales tot_sales%TYPE; -- Anchor to a database column. v_ename employee.last_name%TYPE;
CURSOR mycur IS SELECT * FROM employee; -- Anchor to a cursor. myrec mycur%ROWTYPE; The NOT NULL clause on a variable declaration (but not on a database column definition) follows the %TYPE anchoring and requires anchored declarations to have a default in their declaration. The default value for an anchored declaration can be different from that for the base declaration: tot_sales monthly_sales
NUMBER(20,2) NOT NULL DEFAULT 0; tot_sales%TYPE DEFAULT 10;
1.5.7 Programmer-Defined Subtypes PL/SQL allows you to define unconstrained scalar subtypes. An unconstrained subtype provides an alias to the original underlying datatype, for example: CREATE OR REPLACE PACKAGE std_types IS -- Declare standard types as globals. TYPE dollar_amt_t IS NUMBER; END std_types; CREATE OR REPLACE PROCEDURE process_money IS -- Use the global type declared above. credit std_types.dollar_amt_t; ... A constrained subtype limits or constrains the new datatype to a subset of the original datatype. For example, POSITIVE is a constrained subtype of BINARY_INTEGER. The declaration for POSITIVE in the STANDARD package is: SUBTYPE POSITIVE IS BINARY_INTEGER RANGE 1..2147483647; You cannot define constrained subtypes in your own programs; this capability is reserved for Oracle itself. You can, however, achieve the same effect as a constrained subtype by using %TYPE. Here is a rewriting of the previous subtype that enforces a constraint on the size of dollar amount variables: PACKAGE std_types IS v_dollar NUMBER (10, 2);
TYPE dollar_amt_t IS v_dollar%TYPE; END;
Previous: 1.4 PL/SQL Language Fundamentals 1.4 PL/SQL Language Fundamentals
Oracle PL/SQL Language Pocket Reference
The Oracle Library Navigation Copyright (c) 2000 O'Reilly & Associates. All rights reserved.
Next: 1.6 Conditional and Sequential Control 1.6 Conditional and Sequential Control
Previous: 1.5 Variables and Program Data
Chapter 1 Oracle PL/SQL Language Pocket Reference
Next: 1.7 Loops
1.6 Conditional and Sequential Control PL/SQL includes conditional (IF) structures as well as sequential control (GOTO, NULL) constructs.
1.6.1 Conditional Control Statements 1.6.1.1 IF-THEN combination IF condition THEN executable statement(s) END IF; For example: IF caller_type = 'VIP' THEN generate_response('GOLD'); END IF; 1.6.1.2 IF-THEN-ELSE combination IF condition THEN TRUE sequence_of_executable_statement(s) ELSE FALSE/NULL sequence_of_executable_statement(s) END IF; For example: IF caller_type = 'VIP' THEN generate_response('GOLD'); ELSE generate_response('BRONZE');
END IF; 1.6.1.3 IF-THEN-ELSIF combination IF condition-1 THEN statements-1 ELSIF condition-N THEN statements-N [ELSE else statements] END IF; For example: IF caller_type = 'VIP' THEN generate_response('GOLD'); ELSIF priority_client THEN generate_response('SILVER'); ELSE generate_response('BRONZE'); END IF;
1.6.2 Sequential Control Statements The GOTO statement performs unconditional branching to a named label. It should be used rarely. At least one executable statement must follow the label (the NULL statement can be this necessary executable statement). The format of a GOTO statement is: GOTO label_name; The format of the label is: <
> There are a number of scope restrictions on where a GOTO can branch control. A GOTO: ● ● ●
● ● ●
Can branch out of an IF statement, LOOP, or sub-block Cannot branch into an IF statement, LOOP, or sub-block Cannot branch from one section of an IF statement to another (from the IF/THEN section to the ELSE section is illegal) Cannot branch into or out of a subprogram Cannot branch from the exception section to the executable section of a PL/SQL block Cannot branch from the executable section to the exception section of a PL/SQL block, although a RAISE does this
The NULL statement is an executable statement that does nothing. It is useful when an executable statement must follow a GOTO label or to aid readability in an IF-THEN-ELSE structure. For example: IF :report.selection = 'DETAIL' THEN exec_detail_report; ELSE NULL; END IF;
Previous: 1.5 Variables and Program Data 1.5 Variables and Program Data
Oracle PL/SQL Language Pocket Reference
The Oracle Library Navigation Copyright (c) 2000 O'Reilly & Associates. All rights reserved.
Next: 1.7 Loops 1.7 Loops
Previous: 1.6 Conditional and Sequential Control
Chapter 1 Oracle PL/SQL Language Pocket Reference
Next: 1.8 Database Interaction and Cursors
1.7 Loops The LOOP construct allows you to repeatedly execute a sequence of statements. There are three kind of loops: simple, WHILE, and FOR. Use the EXIT statement to break out of LOOP and pass control to the statement following the END LOOP.
1.7.1 The Simple Loop The syntax for a simple loop is: LOOP executable_statement(s) END LOOP; The simple loop should contain an EXIT or EXIT WHEN statement so as not to execute infinitely. Use the simple loop when you want the body of the loop to execute at least once. For example: LOOP FETCH company_cur INTO company_rec; EXIT WHEN company_cur%ROWCOUNT > 5 OR company_cur%NOTFOUND; process_company(company_cur); END LOOP;
1.7.2 The Numeric FOR Loop The syntax for a numeric FOR loop is:
FOR loop_index IN [REVERSE] lowest_number.. highest_number LOOP executable_statement(s) END LOOP; The PL/SQL runtime engine automatically declares the loop index a PLS_INTEGER variable; never declare a variable with that name yourself. The lowest_number and highest_number ranges can be variables, but are evaluated only once -- on initial entry into the loop. The REVERSE keyword causes PL/SQL to start with the highest_number and decrement down to the lowest_number. For example: BEGIN DBMS_OUTPUT.PUT_LINE('Beginning Forward'); FOR counter IN 1 .. 4 LOOP DBMS_OUTPUT.PUT_LINE('counter='||counter); END LOOP; DBMS_OUTPUT.PUT_LINE('Beginning REVERSE'); FOR counter IN REVERSE 1 .. 4 LOOP DBMS_OUTPUT.PUT_LINE('counter='||counter); END LOOP; END;
1.7.3 The Cursor FOR Loop The syntax for a cursor FOR loop is: FOR record_index IN [cursor_name | (SELECT statement)] LOOP executable_statement(s) END LOOP; The PL/SQL runtime engine automatically declares the loop index a record of cursor_name% ROWTYPE; never declare a variable with that name yourself. The cursor FOR loop automatically opens the cursor, fetches all rows identified by the cursor, and then closes the cursor. You can embed the SELECT statement directly in the cursor FOR loop. For example: FOR emp_rec IN emp_cur LOOP IF emp_rec.title = 'Oracle Programmer'
THEN give_raise(emp_rec.emp_id,30) END IF; END LOOP;
1.7.4 The WHILE Loop The syntax for a WHILE loop is: WHILE condition LOOP executable_statement(s) END LOOP; Use the WHILE loop when, depending on the entry condition, you don't want the loop body to execute even once: WHILE NOT end_of_analysis LOOP perform_analysis; get_next_record; IF analysis_cursor%NOTFOUND AND next_step IS NULL THEN end_of_analysis := TRUE; END IF; END LOOP;
1.7.5 The REPEAT UNTIL Loop Emulation PL/SQL does not directly support a REPEAT UNTIL construct, but a modified simple loop can emulate one. The syntax for this emulated REPEAT UNTIL loop is: LOOP executable_statement(s) EXIT WHEN Boolean_condition; END LOOP; Use the emulated REPEAT UNTIL loop when executing iterations indefinitely before conditionally terminating the loop.
1.7.6 The EXIT Statement The syntax for the EXIT statement is:
EXIT [WHEN Boolean_condition]; If you do not include a WHEN clause in the EXIT statement, it will terminate the loop unconditionally. Otherwise, the loop terminates only if Boolean_condition evaluates to TRUE. The EXIT statement is optional and can appear anywhere in the loop.
1.7.7 Loop Labels Loops can be optionally labeled to improve readability and execution control. The label must appear immediately in front of the statement that initiates the loop. The following example demonstrates the use of loop labels to qualify variables within a loop and also to terminate nested and outer loops: <> FOR yearind IN 1 .. 20 LOOP <<month_loop>> LOOP ... IF year_loop.yearind > 10 THEN EXIT year_loop; END IF; END LOOP month_loop; END LOOP year_loop;
Previous: 1.6 Conditional and Sequential Control 1.6 Conditional and Sequential Control
Oracle PL/SQL Language Pocket Reference
The Oracle Library Navigation Copyright (c) 2000 O'Reilly & Associates. All rights reserved.
Next: 1.8 Database Interaction and Cursors 1.8 Database Interaction and Cursors
Previous: 1.7 Loops
Chapter 1 Oracle PL/SQL Language Pocket Reference
Next: 1.9 Cursors in PL/ SQL
1.8 Database Interaction and Cursors PL/SQL is tightly integrated with the underlying SQL layer of the Oracle database. You can execute SQL statements (UPDATE, INSERT, DELETE, and SELECT) directly in PL/SQL programs. You can also execute Data Definition Language (DDL) statements through the use of dynamic SQL (DBMS_SQL in Oracle7 and Oracle8, native dynamic SQL in Oracle8i). In addition, you can manage transactions with COMMIT, ROLLBACK, and other Data Control Language (DCL) statements.
1.8.1 Transaction Management The Oracle RDBMS provides a transaction model based on a unit of work. The PL/SQL language supports most, but not all, of the database model for transactions (you cannot, for example, ROLLBACK FORCE). Transactions begin with the first change to data and end with either a COMMIT or ROLLBACK. Transactions are independent of PL/SQL blocks. Transactions can span multiple PL/SQL blocks, or there can be multiple transactions in a single PL/SQL block. The PL/ SQL supported transaction statements are: COMMIT, ROLLBACK, SAVEPOINT, SET TRANSACTION, and LOCK TABLE. Each is detailed here: 1.8.1.1 COMMIT COMMIT [WORK] [COMMENT text]; COMMIT makes the database changes permanent and visible to other database sessions. The WORK keyword is optional and only aids readability -- it is rarely used. The COMMENT text is optional and can be up to 50 characters in length. It is only germane to in-doubt distributed (two-phase commit) transactions. The database statement COMMIT FORCE for distributed transactions is not supported in PL/SQL. 1.8.1.2 ROLLBACK ROLLBACK [WORK] [TO [SAVEPOINT] savepoint_name];
ROLLBACK undoes the changes made in the current transaction either to the beginning of the transaction or to a savepoint. A savepoint is a named processing point in a transaction, created with the SAVEPOINT statement. Rolling back to a savepoint is a partial rollback of a transaction, wiping out all changes (and savepoints) that occurred later than the named savepoint. 1.8.1.3 SAVEPOINT SAVEPOINT savepoint_name; SAVEPOINT establishes a savepoint in the current transaction. savepoint_name is an undeclared identifier -- you do not declare it. More than one savepoint can be established within a transaction. If you reuse a savepoint name, that savepoint is moved to the later position and you will not be able to rollback to the initial savepoint position. 1.8.1.4 SET TRANSACTION SET TRANSACTION READ ONLY; SET TRANSACTION ISOLATION LEVEL SERIALIZABLE; SET TRANSACTION USE ROLLBACK SEGMENT rbseg_name; SET TRANSACTION has three transaction control functions: READ ONLY Marks the beginning of a read-only transaction. This indicates to the RDBMS that a readconsistent view of the database is to be enforced for the transaction (the default is for the statement). This read-consistent view means that only changes committed before the transaction begins are visible for the duration of the transaction. The transaction is ended with either a COMMIT or ROLLBACK. Only LOCK TABLE, SELECT, SELECT INTO, OPEN, FETCH, CLOSE, COMMIT, or ROLLBACK statements are permitted during a read-only transaction. Issuing other statements, such as INSERT or UPDATE, in a read-only transaction results in an ORA-1456 error. ISOLATION LEVEL SERIALIZABLE Similar to a READ ONLY transaction in that transaction-level read consistency is enforced instead of the default statement-level read consistency. Serializable transactions do allow changes to data, however. USE ROLLBACK SEGMENT Tells the RDBMS to use the specifically named rollback segment rbseg_name. This statement is useful when only one rollback segment is large and a program knows that it needs to use the large rollback segment, such as during a month-end close operation. For example, if we know our large rollback segment is named rbs_large, we can tell the database to use it by issuing the following statement before our first change to data:
SET TRANSACTION USE ROLLBACK SEGMENT rbs_large; 1.8.1.5 LOCK TABLE LOCK TABLE table_list IN lock_mode MODE [NOWAIT]; This statement bypasses the implicit database row-level locks by explicitly locking one or more tables in the specified mode. The table_list is a comma-delimited list of tables. The lock_mode is one of ROW SHARE, ROW EXCLUSIVE, SHARE UPDATE, SHARE, SHARE ROW EXCLUSIVE, or EXCLUSIVE. The NOWAIT keyword specifies that the RDBMS should not wait for a lock to be released. If there is a lock when NOWAIT is specified, the RDBMS raises the exception "ORA00054: resource busy and acquire with NOWAIT specified". The default RDBMS locking behavior is to wait indefinitely.
1.8.2 Native Dynamic SQL (Oracle8i) Native dynamic SQL introduces a new PL/SQL statement, EXECUTE IMMEDIATE, and new semantics for the OPEN FOR, FETCH, and CLOSE statement family. The former applies to singlerow queries and DDL, while the latter supports dynamic multi-row queries. The syntax for these statements is: EXECUTE IMMEDIATE SQL_statement_string [INTO { define_variable_list | record | object_variable }] [USING [IN | OUT | IN OUT] bind_argument_list]; OPEN cursor_variable FOR SELECT_statement_string; FETCH cursor_variable INTO {define_variable_list | record | object_variable}; CLOSE cursor_variable; The EXECUTE IMMEDIATE statement parses and executes the SQL statement in a single step. It can be used for any SQL statement except a multi-row query. define_variable_list is a commadelimited list of variable names; the bind_argument_list is a comma-delimited list of bind arguments. The parameter mode is optional and defaults to IN. Do not place a trailing semicolon in the SQL_statement_string. This is the statement that can be used to execute DDL without the DBMS_SQL package. For example: EXECUTE IMMEDIATE 'TRUNCATE TABLE foo'; EXECUTE IMMEDIATE 'GRANT SELECT ON '|| tabname_v || ' TO ' || grantee_list;
The OPEN FOR statement assigns a multi-row query to a weakly typed cursor variable. The rows are then FETCHed and the cursor CLOSEd. DECLARE TYPE cv_typ IS REF CURSOR; cv cv_typ; laccount_no NUMBER; lbalance NUMBER; BEGIN OPEN cv FOR 'SELECT account_no, balance FROM accounts WHERE balance < 500'; LOOP FETCH cv INTO laccount_no, lbalance; EXIT WHEN cv%NOTFOUND; -- Process the row. END LOOP; CLOSE cv; END;
1.8.3 Autonomous Transactions (Oracle8i) Autonomous transactions execute within a block of code as separate transactions from the outer (main) transaction. Changes can be committed or rolled back in an autonomous transaction without committing or rolling back the main transaction. Changes committed in an autonomous transaction are visible to the main transaction, even though they occur after the start of the main transaction. Changes committed in an autonomous transaction are visible to other transactions as well. The RDBMS suspends the main transaction while the autonomous transaction executes: PROCEDURE main IS BEGIN UPDATE ...-- Main transaction begins here. DELETE ... at_proc; -- Call the autonomous transaction. SELECT ... INSERT ... COMMIT; -- Main transaction ends here. END; PROCEDURE at_proc IS PRAGMA AUTONOMOUS_TRANSACTION; BEGIN -- Main transaction suspends here. SELECT ...
INSERT ...-- Autonomous transaction begins here. UPDATE ... DELETE ... COMMIT; -- Autonomous transaction ends here. END; -- Main transaction resumes here. So, changes made in the main transaction are not visible to the autonomous transaction and if the main transaction holds any locks that the autonomous transaction waits for, a deadlock occurs. Using the NOWAIT option on UPDATE statements in autonomous transactions can help to minimize this kind of deadlock. Functions and procedures (local program, standalone, or packaged), database triggers, top-level anonymous PL/SQL blocks, and object methods can be declared autonomous via the compiler directive PRAGMA AUTONOMOUS_TRANSACTION. In the example below, the COMMIT does not make permanent pending changes in the calling program. Any rollback in the calling program would also have no effect on the changes committed in this autonomous procedure: CREATE OR REPLACE PROCEDURE add_company ( name_in company.name%TYPE ) IS PRAGMA AUTONOMOUS_TRANSACTION; BEGIN determine_credit(name); create_account(name); ... COMMIT; -- Only commit this procedure's changes. END add_company;
Previous: 1.7 Loops
Oracle PL/SQL Language Pocket Reference
1.7 Loops The Oracle Library Navigation Copyright (c) 2000 O'Reilly & Associates. All rights reserved.
Next: 1.9 Cursors in PL/ SQL 1.9 Cursors in PL/SQL
Previous: 1.8 Database Interaction and Cursors
Chapter 1 Oracle PL/SQL Language Pocket Reference
Next: 1.10 Exception Handling
1.9 Cursors in PL/SQL Every SQL statement executed by the RDBMS has a private SQL area that contains information about the SQL statement and the set of data returned. In PL/SQL, a cursor is a name assigned to a specific private SQL area for a specific SQL statement. There can be either static cursors, whose SQL statement is determined at compile time, or dynamic cursors, whose SQL statement is determined at runtime. Static cursors are covered in greater detail in this section. Dynamic cursors in PL/SQL are implemented via the built-in package DBMS_SQL. See the book Oracle Built-in Packages and the corresponding Oracle PL/SQL Built-ins Pocket Reference, both from O'Reilly & Associates, for full coverage on DBMS_SQL and the other built-in packages.
1.9.1 Explicit Cursors Explicit cursors are SELECT statements that are DECLAREd explicitly in the declaration section of the current block or in a package specification. Use OPEN, FETCH, and CLOSE in the execution or exception sections of your programs. 1.9.1.1 Declaring explicit cursors To use an explicit cursor, you must first declare it in the declaration section of a block or package. There are three types of explicit cursor declarations: ●
A cursor without parameters, such as: CURSOR company_cur IS SELECT company_id FROM company;
●
A cursor that accepts arguments through a parameter list: CURSOR company_cur (id_in IN NUMBER) IS SELECT name FROM company
WHERE ●
company_id = id_in;
A cursor header that contains a RETURN clause in place of the SELECT statement: CURSOR company_cur (id_in IN NUMBER) RETURN company%ROWTYPE IS SELECT * FROM company;
This technique can be used in packages to hide the implementation of the cursor in the package body. See the Section 1.14" section for more information. 1.9.1.2 Opening explicit cursors To open a cursor, use the following syntax: OPEN cursor_name [(argument [,argument ...])]; where cursor_name is the name of the cursor as declared in the declaration section. The arguments are required if the definition of the cursor contains a parameter list. You must open an explicit cursor before you can fetch rows from that cursor. When the cursor is opened, the processing includes the PARSE, BIND, OPEN, and EXECUTE statements. This OPEN processing includes: determining an execution plan, associating host variables and cursor parameters with the placeholders in the SQL statement, determining the result set, and, finally, setting the current row pointer to the first row in the result set. When using a cursor FOR loop, the OPEN is implicit in the FOR statement. If you try to open a cursor that is already open, PL/SQL will raise an "ORA-06511: PL/SQL: cursor already open" exception. 1.9.1.3 Fetching from explicit cursors The FETCH statement places the contents of the current row into local variables. To retrieve all rows in a result set, each row needs to be fetched. The syntax for a FETCH statement is: FETCH cursor_name INTO record_or_variable_list; where cursor_name is the name of the cursor as declared and opened. 1.9.1.4 Closing explicit cursors The syntax of the CLOSE statement is: CLOSE cursor_name;
where cursor_name is the name of the cursor declared and opened. After all rows have been fetched, a cursor needs to be closed. Closing a cursor releases the private SQL area used by the cursor, freeing the memory used by that cursor. If you declare a cursor in a local anonymous, procedure, or function block, that cursor will automatically close when the block terminates. Package-based cursors must be closed explicitly, or they stay open for the duration of your session. Closing a cursor that is not open raises an INVALID CURSOR exception. 1.9.1.5 Explicit cursor attributes There are four attributes associated with cursors: ISOPEN, FOUND, NOTFOUND, and ROWCOUNT. These attributes can be accessed with the % delimiter to obtain information about the state of the cursor. The syntax for a cursor attribute is: cursor_name%attribute where cursor_name is the name of the explicit cursor. The behaviors of the explicit cursor attributes are described in the following table. Attribute
Description
%ISOPEN
TRUE if cursor is open. FALSE if cursor is not open.
%FOUND
INVALID_CURSOR is raised if cursor has not been OPENed. NULL before the first fetch. TRUE if record was fetched successfully. FALSE if no row was returned. INVALID_CURSOR if cursor has been CLOSEd.
%NOTFOUND INVALID_CURSOR is raised if cursor has not been OPENed. NULL before the first fetch. FALSE if record was fetched successfully. TRUE if no row was returned. INVALID_CURSOR if cursor has been CLOSEd. %ROWCOUNT INVALID_CURSOR is raised if cursor has not been OPENed. The number of rows fetched from the cursor. INVALID_CURSOR if cursor has been CLOSEd. Frequently a cursor attribute is checked as part of a WHILE loop that fetches rows from a cursor: DECLARE caller_rec caller_pkg.caller_cur%ROWTYPE; BEGIN OPEN caller_pkg.caller_cur; LOOP FETCH caller_pkg.caller_cur into caller_rec; EXIT WHEN caller_pkg.caller_cur%NOTFOUND OR caller_pkg.caller_cur%ROWCOUNT > 10; UPDATE call SET caller_id = caller_rec.caller_id WHERE call_timestamp < SYSDATE; END LOOP; CLOSE caller_pkg.caller_cur; END;
1.9.2 Implicit Cursors Whenever a SQL statement is directly in the execution or exception section of a PL/SQL block, you are working with implicit cursors. These statements include INSERT, UPDATE, DELETE, and SELECT INTO statements. Unlike explicit cursors, implicit cursors do not need to be declared, OPENed, FETCHed, or CLOSEd. SELECT statements handle the %FOUND and %NOTFOUND attributes differently from explicit cursors. When an implicit SELECT statement does not return any rows, PL/SQL immediately raises
the NO_DATA_FOUND exception and control passes to the exception section. When an implicit SELECT returns more than one row, PL/SQL immediately raises the TOO_MANY_ROWS exception and control passes to the exception section. Implicit cursor attributes are referenced via the SQL cursor. For example: BEGIN UPDATE activity SET last_accessed := SYSDATE WHERE UID = user_id; IF SQL%NOTFOUND THEN INSERT INTO activity_log (uid,last_accessed) VALUES (user_id,SYSDATE); END IF END; SQL Attributes
Description
%ISOPEN
Always FALSE since the cursor is opened implicitly and closed immediately after the statement is executed.
%FOUND
NULL before the statement. TRUE if one or more rows were inserted, updated, or deleted or if only one row was selected. FALSE if no row was selected, updated, inserted, or deleted.
%NOTFOUND
NULL before the statement. TRUE if no row was selected, updated, inserted, or deleted. FALSE if one or more rows were inserted, updated, or deleted.
%ROWCOUNT
The number of rows affected by the cursor.
%BULK_ROWCOUNT (Oracle8i) A pseudo index-by table containing the numbers of rows affected by the statements executed in bulk bind operations. See the "Bulk Binds (Oracle8i)" section for more information on %BULK_ROWCOUNT. Use the RETURNING clause in INSERT, UPDATE, and DELETE statements to obtain data modified by the associated DML statement. This clause allows you to avoid an additional SELECT statement to query the results of the DML statement. For example:
BEGIN UPDATE activity SET last_accessed := SYSDATE WHERE UID = user_id RETURNING last_accessed, cost_center INTO timestamp, chargeback_acct; 1.9.2.1 The SELECT FOR UPDATE clause By default, the Oracle RDBMS locks rows as they are changed. To lock all rows in a result set, use the FOR UPDATE clause in your SELECT statement when you OPEN the cursor, instead of when you change the data. Using the FOR UPDATE clause does not require you to actually make changes to the data; it only locks the rows when opening the cursor. These locks are released on the next COMMIT or ROLLBACK. As always, these row locks do not affect other SELECT statements unless they, too, are FOR UPDATE. The FOR UPDATE clause is appended to the end of the SELECT statement and has the following syntax: SELECT ... FROM ... FOR UPDATE [OF column_reference] [NOWAIT]; where column_reference is a comma-delimited list of columns that appear in the SELECT clause. The NOWAIT keyword tells the RDBMS to not wait for other blocking locks to be released. The default is to wait forever. In the following example, only columns from the inventory (pet) table are referenced FOR UPDATE, so no rows in the dog_breeds (dog) table are locked when hounds_in_stock_cur is opened: DECLARE CURSOR hounds_in_stock_cur IS SELECT pet.stock_no, pet.breeder, dog.size FROM dog_breeds dog ,inventory pet WHERE dog.breed = pet.breed AND dog.class = 'HOUND' FOR UPDATE OF pet.stock_no, pet.breeder; BEGIN 1.9.2.2 The WHERE CURRENT OF clause UPDATE and DELETE statements can use a WHERE CURRENT OF clause if they reference a cursor declared FOR UPDATE. This syntax indicates that the UPDATE or DELETE should modify the current row identified by the FOR UPDATE cursor. The syntax is: [UPDATE | DELETE ] ... WHERE CURRENT OF cursor_name;
By using WHERE CURRENT OF, you do not have to repeat the WHERE clause in the SELECT statement. For example: DECLARE CURSOR wip_cur IS SELECT acct_no, enter_date FROM wip WHERE enter_date < SYSDATE -7 FOR UPDATE; BEGIN FOR wip_rec IN wip_cur LOOP INSERT INTO acct_log (acct_no, order_date) VALUES (wip_rec.acct_no, wip_rec.enter_ date); DELETE FROM wip WHERE CURRENT OF wip_cur; END LOOP; END;
1.9.3 Cursor Variables A cursor variable is a data structure that points to a cursor object, which in turn points to the cursor's result set. You can use cursor variables to more easily retrieve rows in a result set from client and server programs. You can also use cursor variables to hide minor variations in queries. The syntax for a REF_CURSOR type is: TYPE ref_cursor_name IS REF CURSOR [RETURN record_type]; If you do not include a RETURN clause, then you are declaring a weak REF CURSOR. Cursor variables declared from weak REF CURSORs can be associated with any query at runtime. A REF CURSOR declaration with a RETURN clause defines a "strong" REF CURSOR. A cursor variable based on a strong REF CURSOR can be associated with queries whose result sets match the number and datatype of the record structure after the RETURN at runtime. To use cursor variables, you must first create a REF_CURSOR type, then declare a cursor variable based on that type. The following example shows the use of both weak and strong REF CURSORs: DECLARE -- Create a cursor type based on the companies table.
TYPE company_curtype IS REF CURSOR RETURN companies%ROWTYPE; -- Create the variable based on the REF CURSOR. company_cur company_curtype; -- And now the weak, general approach. TYPE any_curtype IS REF CURSOR; generic_curvar any_curtype; The syntax to OPEN a cursor variable is: OPEN cursor_name FOR select_statement; FETCH and CLOSE a cursor variable using the same syntax as for explicit cursors. There are a number of restrictions on cursor variables: ● ● ●
● ● ●
Cursor variables cannot be declared in a package since they do not have a persistent state. You cannot use the FOR UPDATE clause with cursor variables. You cannot assign NULLs to a cursor variable nor use comparison operators to test for equality, inequality, or nullity. Neither database columns nor collections can store cursor variables. You cannot use RPCs to pass cursor variables from one server to another. Cursor variables cannot be used with the dynamic SQL built-in package DBMS_SQL.
Previous: 1.8 Database Interaction and Cursors 1.8 Database Interaction and Cursors
Oracle PL/SQL Language Pocket Reference
The Oracle Library Navigation Copyright (c) 2000 O'Reilly & Associates. All rights reserved.
Next: 1.10 Exception Handling 1.10 Exception Handling
Previous: 1.9 Cursors in PL/ SQL
Chapter 1 Oracle PL/SQL Language Pocket Reference
Next: 1.11 Records in PL/ SQL
1.10 Exception Handling PL/SQL allows developers to raise and handle errors (exceptions) in a very flexible and powerful way. Each PL/SQL block can have its own exception section, in which exceptions can be trapped and handled (resolved or passed on to the enclosing block). When an exception occurs (is raised) in a PL/SQL block, its execution section immediately terminates. Control is passed to the exception section. Every exception in PL/SQL has an error number and error message; some exceptions also have names.
1.10.1 Declaring Exceptions Some exceptions (see the following table) have been pre-defined by Oracle in the STANDARD package. You can also declare your own exceptions as follows: DECLARE exception_name EXCEPTION; Error
Named Exception
ORA-00001 DUP_VAL_ON_INDEX ORA00051
TIMEOUT_ON_RESOURCE
ORA01001
INVALID_CURSOR
ORA01012
NOT_LOGGED_ON
ORA01017
LOGIN_DENIED
ORA01403
NO_DATA_FOUND
ORA01410
SYS_INVALID_ROWID
ORA01422
TOO_MANY_ROWS
ORA01476
ZERO_DIVIDE
ORA01722
INVALID_NUMBER
ORA06500
STORAGE_ERROR
ORA06501
PROGRAM_ERROR
ORA06502
VALUE_ERROR
ORA06504
ROWTYPE_MISMATCH
ORA06511
CURSOR_ALREADY_OPEN
ORA06530
ACCESS_INTO_NULL
ORA06531
COLLECTION_IS_NULL
ORA06532
SUBSCRIPT_OUTSIDE_LIMIT
ORA06533
SUBSCRIPT_BEYOND_COUNT
An exception can be declared only once in a block, but nested blocks can declare an exception with the same name as an outer block. If this multiple declaration occurs, scope takes precedence over name when handling the exception. The inner block's declaration takes precedence over a global declaration. When you declare your own exception, you must RAISE it explicitly. All declared exceptions have
an error code of 1 and the error message "User-defined exception," unless you use the EXCEPTION_INIT pragma. You can associate an error number with a declared exception with the PRAGMA EXCEPTION_INIT statement: DECLARE exception_name EXCEPTION; PRAGMA EXCEPTION_INIT (exception_name, error_number); where error_number is a literal value (variable references are not allowed). This number can be an Oracle error, such as -1855, or an error in the user-definable -20000 to -20999 range.
1.10.2 Raising Exceptions An exception can be raised in three ways: ● ● ●
By the PL/SQL runtime engine By an explicit RAISE statement in your code By a call to the built-in function RAISE_APPLICATION_ERROR
The syntax for the RAISE statement is: RAISE exception_name; where exception_name is the name of an exception that you have declared, or that is declared in the STANDARD package. If you use the RAISE statement inside an exception handler, you can leave off an exception name to re-raise the current exception: RAISE; This syntax is not valid outside the exception section. The RAISE_APPLICATION_ERROR built-in has the following header: RAISE_APPLICATION_ERROR ( num BINARY_INTEGER, msg VARCHAR2, keeperrorstack BOOLEAN DEFAULT FALSE); where num is the error number (an integer between -20999 and -20000), msg is the associated error
message, and keeperrorstack controls the contents of the error stack.
1.10.3 Scope The scope of an exception section is that portion of the code that is "covered" by the exception section. An exception handler will only handle or attempt to handle exceptions raised in the executable section of the PL/SQL block. Exceptions raised in the declaration or exception sections are automatically passed to the outer block. Any line or set of PL/SQL code can be placed inside its own block and given its own exception section. This allows you to limit the propagation of an exception.
1.10.4 Propagation Exceptions raised in a PL/SQL block propagate to an outer block if they are unhandled or re-raised in the exception section. When an exception occurs, PL/SQL looks for an exception handler that checks for the exception (or is the WHEN OTHERS clause) in the current block. If a match is not found, then PL/SQL propagates the exception to the enclosing block or calling program. This propagation continues until the exception is handled or propagated out of the outermost block, back to the calling program. In this case, the exception is "unhandled" and (1) stops the calling program, and (2) causes an automatic rollback of any outstanding transactions. Once an exception is handled, it will not propagate upward. If you want to trap an exception, display a meaningful error message, and have the exception propagate upward as an error, you must re-raise the exception. The RAISE statement can re-raise the current exception or raise a new exception: PROCEDURE delete_dept(deptno_in IN NUMBER) DECLARE still_have_employees EXCEPTION PRAGMA EXCEPTION_INIT(still_have_employees. -2292) BEGIN DELETE FROM dept WHERE deptno = deptno_in; EXCEPTION WHEN still_have_employees THEN DBMS_OUTPUT.PUT_LINE ('Please delete employees in dept first'); ROLLBACK; RAISE; /* Re-raise the current exception. */ END; 1.10.4.1 The WHEN OTHERS clause EXCEPTION
WHEN OTHERS THEN ... Use the WHEN OTHERS clause in the exception handler as a catch-all to trap any exceptions that are not handled by specific WHEN clauses in the exception section. If present, this clause must be the last exception handler in the exception section. 1.10.4.2 SQLCODE and SQLERRM SQLCODE and SQLERRM are built-in functions that provide the SQL error code and message for the current exception. Use these functions inside the exception section's WHEN OTHERS clause to handle specific errors by number. The EXCEPTION_INIT pragma allows you to handle errors by name. CREATE TABLE err_test (widget_name VARCHAR2(100) ,widget_count NUMBER ,CONSTRAINT no_small_numbers CHECK (widget_count > 1000)); BEGIN INSERT INTO err_test (widget_name, widget_count) VALUES ('Athena',2); EXCEPTION WHEN OTHERS THEN IF SQLCODE = -2290 AND SQLERRM LIKE '%NO_SMALL_NUMBERS%' THEN DBMS_OUTPUT.PUT_LINE('widget_count is too small'); ELSE DBMS_OUTPUT.PUT_LINE('Exception not hooked,' ||'SQLcode='||SQLCODE); DBMS_OUTPUT.PUT_LINE(SQLERRM); END IF; END; Gives the output of: widget_count is too small The DBMS_UTILITY.FORMAT_ERROR_STACK and DBMS_UTILITY. FORMAT_CALL_STACK procedures can be used to capture the full error stack and call stack. See the O'Reilly & Associates book Oracle PL/SQL Built-in Packages for more information on DBMS_UTILITY.
1.10.4.3 Exceptions and DML When an exception is raised in a PL/SQL block, it does not rollback your current transaction, even if the block itself issued an INSERT, UPDATE, or DELETE. You must issue your own ROLLBACK statement if you want to clean up your transaction due to the exception. If your exception goes unhandled (propagates out of the outermost block), however, most host environments will then force an automatic, unqualified rollback of any outstanding changes in your session.
Previous: 1.9 Cursors in PL/ SQL 1.9 Cursors in PL/SQL
Oracle PL/SQL Language Pocket Reference
The Oracle Library Navigation Copyright (c) 2000 O'Reilly & Associates. All rights reserved.
Next: 1.11 Records in PL/ SQL 1.11 Records in PL/SQL
Previous: 1.10 Exception Handling
Chapter 1 Oracle PL/SQL Language Pocket Reference
Next: 1.12 Named Program Units
1.11 Records in PL/SQL A PL/SQL record is a data structure composed of multiple pieces of information called fields. To use a record, you must first define it and declare a variable of this type. There are three types of records: table-based, cursor-based, and programmer-defined.
1.11.1 Declaring Records You define and declare records either in the declaration section of a PL/SQL block, or globally, via a package specification. You do not have to explicitly define table-based or cursor-based records, as they are implicitly defined with the same structure as a table or cursor. Variables of these types are declared via the % ROWTYPE attribute. The record's fields correspond to the table's columns or the columns in the SELECT list. For example: DECLARE -- Declare table-based record for company table. comp_rec company%ROWTYPE CURSOR comp_summary_cur IS SELECT C.company_id,SUM(S.gross_sales) gross FROM company C ,sales S WHERE C.company_id = S.company_id; -- Declare a cursor-based record. comp_summary_rec comp_summary_cur%ROWTYPE; Programmer-defined records must be explicitly defined in the PL/SQL block or a package specification with the TYPE statement. Variables of this type can then be declared: DECLARE
TYPE name_rectype IS RECORD( prefix VARCHAR2(15) ,first_name VARCHAR2(30) ,middle_name VARCHAR2(30) ,sur_name VARCHAR2(30) ,suffix VARCHAR2(10) ); TYPE employee_rectype IS RECORD ( emp_id NUMBER(10) NOT NULL ,mgr_id NUMBER(10) ,dept_no dept.deptno%TYPE ,title VARCHAR2(20) ,name empname_rectype ,hire_date DATE := SYSDATE ,fresh_out BOOLEAN ); -- Declare a variable of this type. new_emp_rec employee_rectype; BEGIN
1.11.2 Referencing Fields of Records Individual fields are referenced via dot notation: record_name.field_name For example: employee.first_name Individual fields within a record can be read from or written to. They can appear on either the left or right side of the assignment operator: BEGIN insurance_start_date := new_emp_rec.hire_date + 30; new_emp_rec.fresh_out := FALSE; ...
1.11.3 Record Assignment An entire record can be assigned to another record of the same type, but one record cannot be compared to another record via Boolean operators. This is a valid assignment:
shipto_address_rec := customer_address_rec This is not a valid comparison: IF shipto_address_rec = customer_address_rec THEN ... END IF; The individual fields of the records need to be compared instead. Values can be assigned to records or to the fields within a record in four different ways: ●
The assignment operator can be used to assign a value to a field: new_emp_rec.hire_date := SYSDATE;
●
You can SELECT INTO a whole record or the individual fields: SELECT INTO FROM WHERE
●
emp_id,dept,title,hire_date,college_recruit new_emp_rec emp surname = 'LI'
You can FETCH INTO a whole record or the individual fields: FETCH emp_cur INTO new_emp_rec; FETCH emp_cur INTO new_emp_rec.emp_id, new_emp_rec.name;
●
You can assign all of the fields of one record variable to another record variable of the same type: IF rehire THEN new_emp_rec := former_emp_rec; ENDIF; This aggregate assignment technique works only for records declared with the same TYPE statement.
1.11.4 Nested Records Nested records are records contained in fields that are records themselves. Nesting records is a powerful way to normalize data structures and hide complexity within PL/SQL programs. For
example: DECLARE -- Define a record. TYPE phone_rectype IS RECORD ( area_code VARCHAR2(3), exchange VARCHAR2(3), phn_number VARCHAR2(4), extension VARCHAR2(4)); -- Define a record composed of records. TYPE contact_rectype IS RECORD ( day_phone# phone_rectype, eve_phone# phone_rectype, cell_phone# phone_rectype); -- Declare a variable for the nested record. auth_rep_info_rec contact_rectype; BEGIN
Previous: 1.10 Exception Handling 1.10 Exception Handling
Oracle PL/SQL Language Pocket Reference
The Oracle Library Navigation Copyright (c) 2000 O'Reilly & Associates. All rights reserved.
Next: 1.12 Named Program Units 1.12 Named Program Units
Previous: 1.11 Records in PL/SQL
Chapter 1 Oracle PL/SQL Language Pocket Reference
Next: 1.13 Triggers
1.12 Named Program Units The PL/SQL programming language allows you to create a variety of named program units (containers for code). They include: Procedure A program that executes one or more statements Function A program that returns a value Package A container for procedures, functions, and data structures Triggers Programs that execute in response to database changes Object type Oracle8's version of a SQL3 named row type; object types can contain member procedures and functions
1.12.1 Procedures Procedures are program units that execute one or more statements and can receive or return zero or more values through their parameter lists. The syntax of a procedure is: CREATE [OR REPLACE] PROCEDURE name [ (parameter [,parameter]) ] [AUTHID CURRENT_USER | DEFINER ] -- Oracle8i [DETERMINISTIC] -- Oracle8i IS | AS
declaration_section BEGIN executable_section [EXCEPTION exception_section] END [name]; A procedure is called as a standalone executable PL/SQL statement: apply_discount(new_company_id, 0.15) --15% discount
1.12.2 Functions Functions are program units that execute one or more statements and return a value through the RETURN clause. Functions can also receive or return zero or more values through their parameter lists. The syntax of a function is: CREATE [OR REPLACE] FUNCTION name [ (parameter [,parameter]) ] RETURN return_datatype [AUTHID CURRENT_USER | DEFINER ] -- Oracle8i [DETERMINISTIC] -- Oracle8i [PARALLEL_ENABLE] -- Oracle8i IS | AS [declaration_section] BEGIN executable_section [EXCEPTION exception_section] END [name]; A function must have at least one RETURN statement in the execution section. The RETURN clause in the function header specifies the datatype of the returned value. See the Section 1.12.3.8, "Compiling stored PL/SQL programs" section for information on the key words OR REPLACE, AUTHID, DETERMINISTIC, and PARALLEL_ENABLE. See the Section 1.12.3.9, "Privileges and stored PL/SQL" section for additional information on the key word AUTHID. A function can be called anywhere an expression of the same type can be used. You can call a function: ●
In an assignment statement:
sales95 := tot_sales(1995,'C'); ●
To set a default value: DECLARE sales95 NUMBER DEFAULT tot_sales(1995,'C'); BEGIN
●
In a Boolean expression: IF tot_sales(1995,'C') > 10000 THEN ...
●
In a SQL statement: SELECT first_name ,surname FROM sellers WHERE tot_sales(1995,'C') > 1000;
●
As an argument in another program unit's parameter list.
Here, for example, max_discount is a programmer-defined function and SYSDATE is a built-in function: apply_discount(company_id, max_discount(SYSDATE));
1.12.3 Parameters Procedures, functions, and cursors may have a parameter list. This list contains one or more parameters that allow you to pass information back and forth between the subprogram and the calling program. Each parameter is defined by its name, datatype, mode, and optional default value. The syntax for a parameter is: parameter_name [mode] [NOCOPY] datatype [(:= | DEFAULT) value] 1.12.3.1 Datatype The datatype can be any PL/SQL or programmer-defined datatype, but cannot be constrained by a size (NUMBER is valid, NUMBER(10) is not valid). The actual size of the parameter is determined from the calling program or via a %TYPE constraint. CREATE OR REPLACE PROCEDURE empid_to_name
(in_id ,out_last_name ,out_first_name ) IS ...
emp.emp_id%TYPE -- Compiles OK. VARCHAR2 -- Compiles OK. VARCHAR2(10) -- Won't compile.
The lengths of out_last_name and out_first_name are determined by the calling program: DECLARE surname VARCHAR2(10); first_name VARCHAR2(10); BEGIN empid_to_name(10, surname, first_name); END; 1.12.3.2 Mode The mode of a parameter specifies whether the parameter can be read from or written to, as shown in the following table. Mode
Description Parameter Usage
IN
Read-only
The value of the actual parameter can be referenced inside the program, but the parameter cannot be changed.
OUT
Write-only
The program can assign a value to the parameter, but the parameter's value cannot be referenced.
IN OUT Read/write
The program can both reference (read) and modify (write) the parameter.
If the mode is not explicitly defined, it defaults to IN. OUT parameters can be written to. In Oracle7, OUT parameters can appear only on the left side of an assignment operation. In Oracle8 and above, OUT parameters are read/write and hence can appear on either side of an assignment. If an exception is raised during execution of a procedure or function, assignments made to OUT or IN OUT parameters get rolled back. The NOCOPY (Oracle8i) compiler hint for parameters makes the parameter a call by reference instead of a call by value. Normally, PL/SQL passes IN/OUT parameters by value -- a copy of the parameter is created for the subprogram. When parameter items get large, like collections or objects, the copy can eat memory and slow the processing. NOCOPY directs PL/SQL to pass the parameter by reference, using a pointer to the single copy of the parameter. The disadvantage of NOCOPY is that when an exception is raised during execution of a program that has modified an OUT or IN OUT parameter, the changes to the actual parameters are not rolled back because the parameters were
passed by reference instead of being copied. 1.12.3.3 Default values IN parameters can be given default values. If an IN parameter has a default value, then you do not need to supply an argument for that parameter when you call the program unit. It automatically uses the default value. For example: CREATE OR REPLACE PROCEDURE hire_employee (emp_id IN VARCHAR2 ,hire_date IN DATE := SYSDATE ,company_id IN NUMBER := 1 ) IS ... -- Example calls to the procedure. -- Use two default values. hire_employee(new_empno); -- Use one default value. hire_employee(new_empno,'12-Jan-1999'); -- Use non-trailing default value, named notation. hire_employee(emp_id=>new_empno, comp_id=>12); 1.12.3.4 Parameter-passing notations Formal parameters are the names that are declared in the header of a procedure or function. Actual parameters are the values or expressions placed in the parameter list when a procedure or function is called. In the empid_to_name example shown earlier in the Section 1.12.3.1, "Datatype" section, the actual parameters to the procedure are in_id, out_last_name, and out_first_name. The formal parameters used in the call to this procedure are 10, surname, and first_name. PL/SQL lets you use either of two styles for passing arguments in parameter lists: positional or named notation. Positional notation This is the default. Each value in the list of arguments supplied in the program call is associated with the parameter in the corresponding position. Named notation This explicitly associates the argument value with its parameter by name (not position). When you use named notation, you can supply the arguments in any order and you can skip over IN arguments that have default values. The call to the empid_to_name procedure is shown here with both notations:
BEGIN -- Implicit positional notation. empid_to_name(10, surname, first_name); -- Explicit named notation. empid_to_name(in_id=>10 ,out_last_name=>surname ,out_first_name=>first_name); END; When calling stored functions from SQL, named notation is not supported. 1.12.3.5 Local program A local program is a procedure or function that is defined in the declaration section of a PL/SQL block. The declaration of a local program must appear at the end of the declaration section, after the declarations of any types, records, cursors, variables, and exceptions. A program defined in a declaration section may only be referenced within that block's executable and exception sections. It is not defined outside that block. The following program defines a local procedure and function: PROCEDURE track_revenue IS PROCEDURE calc_total (year_in IN INTEGER) IS BEGIN calculations here ... END; FUNCTION below_minimum (comp_id IN INTEGER) RETURN BOOLEAN IS BEGIN ... END; Local programs may be overloaded with the same restrictions as overloaded packaged programs. 1.12.3.6 Program overloading PL/SQL allows you to define two or more programs with the same name within any declaration section, including a package specification or body. This is called overloading. If two or more programs have the same name, they must be different in some other way so that the compiler can determine which program should be used.
Here is an example of overloaded programs in a built-in package specification: PACKAGE DBMS_OUTPUT IS PROCEDURE PUT_LINE (a VARCHAR2); PROCEDURE PUT_LINE (a NUMBER); PROCEDURE PUT_LINE (a DATE); END; Each PUT_LINE procedure is identical, except for the datatype of the parameter. That is enough difference for the compiler. To overload programs successfully, one or more of the following conditions must be true: ● ●
●
Parameters must differ by datatype family (number, character, datetime, or Boolean). The program type must be different (you can overload a function and a procedure of the same name and identical parameter list). The numbers of parameters must be different.
You cannot overload programs if: ● ●
●
Only the datatypes of the functions' RETURN clauses are different. Parameter datatypes are within the same family (CHAR and VARCHAR2, NUMBER and INTEGER, etc.). Only the modes of the parameters are different.
1.12.3.7 Forward declarations Programs must be declared before they can be used. PL/SQL supports mutual recursion, in which program A calls program B, whereupon program B calls program A. To implement this mutual recursion, you must use a forward declaration of the programs. This technique declares a program in advance of the program definition, thus making it available for other programs to use. The forward declaration is the program header up to the IS/AS keyword: PROCEDURE perform_calc(year_in IN NUMBER) IS /* Forward declaration for total_cost function. */ FUNCTION total_cost (...) RETURN NUMBER; /* The net_profit function can now use total_cost. */ FUNCTION net_profit(...) RETURN NUMBER IS
BEGIN RETURN total_sales(...) - total_cost(...); END; /* The Total_cost function calls net_profit. */ FUNCTION total_cost (...) RETURN NUMBER IS BEGIN IF net_profit(...) < 0 THEN RETURN 0; ELSE RETURN...; END IF; END; BEGIN /* procedure perform_calc */ ... END perform_calc; 1.12.3.8 Compiling stored PL/SQL programs The following keywords are new with Oracle8i: OR REPLACE Used to rebuild an existing program unit, preserving its privileges. AUTHID Defines whether the program will execute with the privileges of, and resolve names like, the object owner (DEFINER), or as the user executing the function (CURRENT_USER). Prior to Oracle8i, only the built-in packages DBMS_SQL and DBMS_UTILITY executed as CURRENT_USER. The default AUTHID is DEFINER. REPEATABLE Required for functions and any dependent programs used in domain (application-defined) indexes. DETERMINISTIC Required for function-based indexes. A function is DETERMINISTIC if it does not meaningfully reference package variables or the database. PARALLEL_ENABLED Tells the optimizer that a function is safe for parallel execution. It replaces the statement: PRAGMA RESTRICT REFERENCES (function_name, wnps,
rnps, wnds, rnds); 1.12.3.9 Privileges and stored PL/SQL Unless you're using an invoker's rights program in Oracle8i, roles cannot provide object or system privileges that can be used inside stored PL/SQL. You must have privileges granted directly to you for objects that, rather than owning, you reference in stored SQL or PL/SQL (procedures, functions, packages, triggers, and views). This restriction arises from the manner in which the database obtains privileges and checks for objects referenced from SQL. Direct GRANT and REVOKE privileges cannot be different for two concurrent sessions of the same user, while roles can be disabled in only one session. Privileges are checked when stored PL/SQL is compiled, and since only GRANT and REVOKE privileges can be relied upon to remain enabled, they are the only privileges checked. This direct GRANT restriction does not apply for anonymous PL/SQL blocks because such blocks are compiled at runtime when all privileges are known. It also does not apply for procedures and functions with the AUTHID of CURRENT_USER (Oracle8i).
Previous: 1.11 Records in PL/SQL 1.11 Records in PL/SQL
Oracle PL/SQL Language Pocket Reference
The Oracle Library Navigation Copyright (c) 2000 O'Reilly & Associates. All rights reserved.
Next: 1.13 Triggers 1.13 Triggers
Previous: 1.12 Named Program Units
Chapter 1 Oracle PL/SQL Language Pocket Reference
Next: 1.14 Packages
1.13 Triggers Triggers are programs that execute in response to changes in table data or certain database events. There is a predefined set of events that can be "hooked" with a trigger, enabling you to integrate your own processing with that of the database. A triggering event fires or executes the trigger.
1.13.1 Creating Triggers The syntax for creating a trigger is: BEFORE | AFTER | INSTEAD OF trigger_event ON [ NESTED TABLE nested_table_column OF view ] | table_or_view_reference | DATABASE trigger_body; INSTEAD OF triggers are valid on only Oracle8 views. Oracle8i must create a trigger on a nested table column. Trigger events are defined in the following table. Trigger Event
Description
INSERT
Fires whenever a row is added to the table_reference.
UPDATE
Fires whenever an UPDATE changes the table_reference. UPDATE triggers can additionally specify an OF clause to restrict firing to updates OF certain columns. See the following examples.
DELETE
Fires whenever a row is deleted from the table_reference. Does not fire on TRUNCATE of the table.
CREATE (Oracle8i)
Fires whenever a CREATE statement adds a new object to the database. In this context, objects are things like tables or packages (found in ALL_OBJECTS). Can apply to a single schema or the entire database.
ALTER (Oracle8i)
Fires whenever an ALTER statement changes a database object. In this context, objects are things like tables or packages (found in ALL_OBJECTS). Can apply to single schema or the entire database.
DROP (Oracle8i)
Fires whenever a DROP statement removes an object from the database. In this context, objects are things like tables or packages (found in ALL_OBJECTS). Can apply to a single schema or the entire database.
SERVERERROR (Oracle8i) Fires whenever a server error message is logged. Only AFTER triggers are allowed in this context. LOGON (Oracle8i)
Fires whenever a session is created (a user connects to the database). Only AFTER triggers are allowed in this context.
LOGOFF (Oracle8i)
Fires whenever a session is terminated (a user disconnects from the database). Only BEFORE triggers are allowed in this context.
STARTUP (Oracle8i)
Fires when the database is opened. Only AFTER triggers are allowed in this context.
SHUTDOWN (Oracle8i)
Fires when the database is closed. Only BEFORE triggers are allowed in this context.
Triggers can fire BEFORE or AFTER the triggering event. AFTER data triggers are slightly more efficient than BEFORE triggers. The referencing_clause is only allowed for the data events INSERT, UPDATE, and DELETE. It lets you give a non-default name to the old and new pseudo-records. These pseudo-records give the program visibility to the pre- and post-change values in row-level triggers. These records are defined like %ROWTYPE records, except that columns of type LONG or LONG RAW cannot be referenced. They are prefixed with a colon in the trigger body, and referenced with dot notation. Unlike other records, these fields can only be assigned individually -- aggregate assignment is not allowed. All old fields are NULL within INSERT triggers, and all new fields are NULL within DELETE triggers. FOR EACH ROW defines the trigger to be a row-level trigger. Row-level triggers fire once for each row affected. The default is a statement-level trigger, which fires only once for each triggering statement. The WHEN trigger_condition specifies the conditions that must be met for the trigger to fire. Stored functions and object methods are not allowed in the trigger condition. The trigger body is a standard PL/SQL block. For example:
CREATE OR REPLACE TRIGGER add_uid BEFORE INSERT ON emp REFERENCING NEW as new_row FOR EACH ROW BEGIN -- Automatically timestamp the entry. SELECT SYSDATE INTO :new_row.entry_date FROM dual; END add_uid; Triggers are enabled on creation, and can be disabled (so they do not fire) with an ALTER statement: ALTER TRIGGER trigger_name ENABLE | DISABLE; ALTER TABLE table_name ENABLE | DISABLE ALL TRIGGERS;
1.13.2 Trigger Predicates When using a single trigger for multiple events, use the trigger predicates INSERTING, UPDATING, and DELETING in the trigger condition to identify the triggering event: CREATE OR REPLACE TRIGGER emp_log_t AFTER INSERT OR UPDATE OR DELETE ON emp FOR EACH ROW DECLARE dmltype CHAR(1); BEGIN IF INSERTING THEN dmltype := 'I'; INSERT INTO emp_log (emp_no, who, operation) VALUES (:new.empno, USER, dmltype); ELSIF UPDATING THEN dmltype := 'U'; INSERT INTO emp_log (emp_no, who, operation) VALUES (:new.empno, USER, dmltype); END IF; END;
1.13.3 DML Events The DML events include INSERT, UPDATE, or DELETE statements on a table or view. Triggers on these events can be statement- (table only) or row-level triggers and can fire BEFORE or AFTER the triggering event. BEFORE triggers can modify the data in affected rows, but perform an additional
logical read. AFTER triggers do not perform this additional logical read, and therefore perform slightly better, but are not able to change the :new values. Triggers cannot be created on SYS-owned objects. The order in which these triggers fire, if present, is as follows: 1. BEFORE statement-level trigger 2. For each row affected by the statement: a. BEFORE row-level trigger b. The triggering statement c. AFTER row-level trigger 3. AFTER statement-level trigger
1.13.4 DDL Events (Oracle8i) The DDL events are CREATE, ALTER, and DROP. These triggers fire whenever the respective DDL statement is executed. DDL triggers can apply to either a single schema or the entire database.
1.13.5 Database Events (Oracle8i) The database events are SERVERERROR, LOGON, LOGOFF, STARTUP, and SHUTDOWN. Only BEFORE triggers are allowed for LOGOFF and SHUTDOWN events. Only AFTER triggers are allowed for LOGON, STARTUP, and SERVERERROR events. A SHUTDOWN trigger will fire on a SHUTDOWN NORMAL and a SHUTDOWN IMMEDIATE, but not on a SHUTDOWN ABORT.
Previous: 1.12 Named Program Units 1.12 Named Program Units
Oracle PL/SQL Language Pocket Reference
The Oracle Library Navigation Copyright (c) 2000 O'Reilly & Associates. All rights reserved.
Next: 1.14 Packages 1.14 Packages
Previous: 1.13 Triggers
Chapter 1 Oracle PL/SQL Language Pocket Reference
Next: 1.15 Calling PL/SQL Functions in SQL
1.14 Packages A package is a collection of PL/SQL objects that are grouped together. There are a number of benefits to using packages, including information hiding, object-oriented design, top-down design, object persistence across transactions, and improved performance. Elements that can be placed in a package include procedures, functions, constants, variables, cursors, exception names, and TYPE statements (for index-by tables, records, REF CURSORs, etc.).
1.14.1 Overview of Package Structure A package can have two parts: the specification and the body. The package specification is required and lists all the objects that are publicly available (may be referenced from outside the package) for use in applications. It also provides all the information a developer needs in order to use objects in the package; essentially, it is the package's API. The package body contains all code needed to implement procedures, functions, and cursors listed in the specification, as well as any private objects (accessible only to other elements defined in that package), and an optional initialization section. If a package specification does not contain any procedures or functions and no private code is needed, then that package does not need to have a package body. The syntax for the package specification is: CREATE [OR REPLACE] PACKAGE package_name [ AUTHID CURRENT_USER | DEFINER ] -- Oracle8i IS | AS [definitions of public TYPEs ,declarations of public variables, types and
objects ,declarations of exceptions ,pragmas ,declarations of cursors, procedures and functions ,headers of procedures and functions] END [package_name]; The syntax for the package body is: CREATE [OR REPLACE] PACKAGE BODY package_name IS | AS [definitions of private TYPEs ,declarations of private variables, types and objects ,full definitions of cursors ,full definitions of procedures and functions] [BEGIN executable_statements [EXCEPTION exception_handlers ] ] END [package_name]; The optional OR REPLACE keywords are used to rebuild an existing package, preserving its privileges. The declarations in the specifications cannot be repeated in the body. Both the executable section and the exception section are optional in a package body. If the executable section is present, it is called the initialization section and executes only once -- the first time any package element is referenced during a session. You must compile the package specification before the body specification. When you grant EXECUTE authority on a package to another schema or to PUBLIC, you are giving access only to the specification; the body remains hidden. Here's an example of a package: CREATE OR REPLACE PACKAGE time_pkg IS FUNCTION GetTimestamp RETURN DATE; PRAGMA RESTRICT_REFERENCES (GetTimestamp, WNDS); PROCEDURE ResetTimestamp;
END time_pkg; CREATE OR REPLACE PACKAGE BODY time_pkg IS StartTimeStamp DATE := SYSDATE; -- StartTimeStamp is package data. FUNCTION GetTimestamp RETURN DATE IS BEGIN RETURN StartTimeStamp; END GetTimestamp; PROCEDURE ResetTimestamp IS BEGIN StartTimeStamp := SYSDATE; END ResetTimestamp; END time_pkg;
1.14.2 Referencing Package Elements The elements declared in the specification are referenced from the calling application via dot notation: package_name.package_element For example, the built-in package DBMS_OUTPUT has a procedure PUT_LINE, so a call to this package would look like this: DBMS_OUTPUT.PUT_LINE('This is parameter data');
1.14.3 Package Data Data structures declared within a package specification or body, but outside any procedure or function in the package, are package data. The scope of package data is your entire session; it spans transaction boundaries, acting as globals for your programs. Keep the following guidelines in mind as you work with package data: ● ●
●
The state of your package variables is not affected by COMMITs and ROLLBACKs. A cursor declared in a package has global scope. It remains OPEN until you close it explicitly or your session ends. A good practice is to hide your data structures in the package body and provide "get and set" programs to read and write that data. This technique protects your data.
1.14.3.1 The SERIALLY_REUSABLE pragma
If you need package data to exist only during a call to the packaged functions or procedures, and not between calls of the current session, you can save runtime memory by using the pragma SERIALLY_REUSABLE. After each call, PL/SQL closes the cursors and releases the memory used in the package. This technique is applicable only to large user communities executing the same routine. Normally, the database server's memory requirements grow linearly with the number of users; with SERIALLY_REUSABLE, this growth can be less than linear, since work areas for package states are kept in a pool in the SGA (System Global Area) and are shared among all users. This pragma must appear in both the specification and the body: CREATE OR REPLACE PACKAGE my_pkg IS PRAGMA SERIALLY_REUSABLE; PROCEDURE foo; END my_pkg; CREATE OR REPLACE PACKAGE BODY my_pkg IS PRAGMA SERIALLY_REUSABLE; PROCEDURE foo IS ... END my_pkg;
1.14.4 Package Initialization The first time a user references a package element, the entire package is loaded into the SGA of the database instance to which the user is connected. That code is then shared by all sessions that have EXECUTE authority on the package. Any package data are then instantiated into the session's UGA (User Global Area), a private area in either the SGA or PGA (Program Global Area). If the package body contains an initialization section, that code will be executed. The initialization section is optional and appears at the end of the package body, beginning with a BEGIN statement and ending with the EXCEPTION section (if present) or the END of the package. The following package initialization section runs a query to transfer the user's minimum balance into a global package variable. Programs can then reference the packaged variable (via the function) to retrieve the balance, rather than executing the query repeatedly: CREATE OR REPLACE PACKAGE usrinfo IS FUNCTION minbal RETURN VARCHAR2; END usrinfo; / CREATE OR REPLACE PACKAGE BODY usrinfo IS g_minbal NUMBER; -- Package data
FUNCTION minbal RETURN VARCHAR2 IS BEGIN RETURN g_minbal; END; BEGIN -- Initialization section SELECT minimum_balance INTO g_minbal FROM user_configuration WHERE username = USER; EXCEPTION WHEN NO_DATA_FOUND THEN g_minbal := NULL; END usrinfo;
Previous: 1.13 Triggers
Oracle PL/SQL Language Pocket Reference
1.13 Triggers
The Oracle Library Navigation Copyright (c) 2000 O'Reilly & Associates. All rights reserved.
Next: 1.15 Calling PL/SQL Functions in SQL 1.15 Calling PL/SQL Functions in SQL
Previous: 1.14 Packages
Chapter 1 Oracle PL/SQL Language Pocket Reference
Next: 1.16 Oracle8 Objects
1.15 Calling PL/SQL Functions in SQL Stored functions can be called from SQL statements in a manner similar to built-in functions like DECODE, NVL, or RTRIM. This is a powerful technique for incorporating business rules into SQL in a simple and elegant way. Unfortunately, there are a number of caveats and restrictions. The most notable caveat is that stored functions executed from SQL are not guaranteed to follow the read consistency model of the database. Unless the SQL statement and any stored functions in that statement are in the same read-consistent transaction (even if they are read-only), each execution of the stored function will look at a different time-consistent set of data. To avoid this potential problem, you need to ensure read consistency programmatically by issuing the SET TRANSACTION READ ONLY or SET TRANSACTION SERIALIZABLE statement before executing your SQL statement containing the stored function. A COMMIT or ROLLBACK then needs to follow the SQL statement to end this read-consistent transaction.
1.15.1 Syntax for Calling Stored Functions in SQL The syntax for calling a stored function from SQL is the same as referencing it from PL/SQL: [schema_name.][pkg_name.]func_name[@db_link] [parm_list] schema_name is optional and refers to the user/owner of the function or package. pkg_name is optional and refers to the package containing the called function. func_name is mandatory and is the function name. db_link is optional and refers to the database link name to the remote database containing the function. parm_list is optional, as are the parameters passed to the function. The following are example calls to the GetTimestamp function in the time_pkg example seen earlier in the Section 1.14.1, "Overview of Package Structure " section: -- Capture system events. INSERT INTO v_sys_event (timestamp ,event
,qty_waits) SELECT time_pkg.GetTimestamp ,event ,total_waits FROM v$system_event -- Capture system statistics. INSERT INTO v_sys_stat (timestamp,stat#,value) SELECT time_pkg.GetTimestamp ,statistic# ,value FROM v$sysstat;
1.15.2 Requirements and Restrictions on Stored Functions in SQL There are a number of requirements for calling stored functions in SQL: ●
● ●
●
●
●
The function must be a single-row function -- not one that operates on a column or group function. All parameters must be IN; no IN OUT or OUT parameters are allowed. The datatypes of the function's parameters and RETURN must be compatible with RDBMS datatypes. You cannot have arguments or RETURN types like BOOLEAN, programmerdefined record, index-by table, etc. The parameters passed to the function must use positional notation; named notation is not supported. Functions defined in packages must have a RESTRICT_REFERENCES pragma in the specification (Oracle8.0 and earlier). The function must be stored in the database, not a local program, Developer/2000 PL/SQL library, or Form.
1.15.3 Calling Packaged Functions in SQL Prior to Oracle8i Release 8.1, it was necessary to assert the purity level of a packaged procedure or function when using it directly or indirectly in a SQL statement. Beginning with Oracle8i Release 8.1, the PL/SQL runtime engine determines a program's purity level automatically if no assertion exists. The RESTRICT_REFERENCES pragma asserts a purity level. The syntax for the RESTRICT_REFERENCES pragma is: PRAGMA RESTRICT_REFERENCES (program_name | DEFAULT, purity_level); The keyword DEFAULT applies to all methods of an object type or all programs in a package. There can be from one to five purity levels, in any order, in a comma-delimited list. The purity level describes to what extent the program or method is free of side effects. Side effects are listed in the following table with the purity levels they address.
Purity Level
Description
WNDS
Write No Database State Executes no INSERT, UPDATE, or DELETE statements.
RNDS
Read No Database State Executes no SELECT statements.
WNPS
Write No Package State
Does not modify any package variables.
RNPS
Read No Package State
Does not read any package variables.
TRUST (Oracle8i)
Restriction
Does not enforce the restrictions declared but allows the compiler to trust they are true.
The purity level requirements for packaged functions are different depending on where in the SQL statement the stored functions are used: ● ● ● ●
●
● ●
To be called from SQL, all stored functions must assert WNDS. All functions not used in a SELECT, VALUES, or SET clause must assert WNPS. To be executed remotely, the function must assert WNPS and RNPS. To be executed in parallel, the function must assert all four purity levels or, in Oracle8i, use PARALLEL_ENABLED in the declaration. These functions must not call any other program that does not also assert the minimum purity level. If a package has an initialization section, it too must assert purity in Oracle7. If a function is overloaded, each overloading must assert its own purity level, and the levels don't have to be the same. To do this, place the pragma immediately after each overloaded declaration.
Many of the built-in packages, including DBMS_OUTPUT, DBMS_PIPE, and DBMS_SQL, do not assert WNPS or RNPS, so their use in SQL stored functions is necessarily limited. 1.15.3.1 Column/function name precedence If your function has the same name as a table column in your SELECT statement and the function has no parameter, then the column takes precedence over the function. To force the RDBMS to resolve the name to your function, prepend the schema name to it: CREATE TABLE emp(new_sal NUMBER ...); CREATE FUNCTION new_sal RETURN NUMBER IS ...; SELECT new_sal FROM emp; -- Resolves to column. SELECT scott.new_sal FROM emp;-- Resolves to function.
Previous: 1.14 Packages
Oracle PL/SQL Language Pocket Reference
1.14 Packages The Oracle Library Navigation Copyright (c) 2000 O'Reilly & Associates. All rights reserved.
Next: 1.16 Oracle8 Objects 1.16 Oracle8 Objects
Previous: 1.15 Calling PL/ SQL Functions in SQL
Chapter 1 Oracle PL/SQL Language Pocket Reference
Next: 1.17 Collections
1.16 Oracle8 Objects In Oracle8, an object type combines attributes (data structures) and methods (functions and procedures) into a single programming construct. The object type construct allows programmers to defined their own reusable datatypes for use in PL/SQL programs and table and column definitions. An instance of an object type is an object in the same way that variables are instances of scalar types. Objects are either persistent (stored in the database) or transient (stored only in PL/SQL variables). Objects can be stored in a database as a row in a table (a row object) or as a column in a table. A table of row objects can be created with syntax such as this: CREATE TABLE table_name OF object_type; When stored in the database as a row object, the object (row) has an OID (Object IDentifier) that is unique throughout the database.
1.16.1 Object Types An object type has two parts: the specification and the body. The specification is required and contains the attributes and method specifications. The syntax for creating the object type specification is: CREATE [OR REPLACE] TYPE obj_type_name [AUTHID CURRENT_USER | DEFINER] -- Oracle8i AS OBJECT ( attribute_name datatype,..., [MEMBER | STATIC PROCEDURE | FUNCTION program_spec], [ORDER | MAP MEMBER FUNCTION comparison_function_spec], [PRAGMA RESTRICT_REFERENCES(program_name, purities)] );
All attribute specifications must appear before all method specifications. Object attributes, like variables, are declared with a name and a datatype. The name can be any legal identifier. Attribute datatypes can be any SQL datatype except LONG, LONG RAW, NCHAR, NVARCHAR2, NCLOB, ROWID, and UROWID. Attributes cannot have datatypes unique to PL/SQL such as BOOLEAN. Member function and procedure headers are listed in the object type specification in a commadelimited list. Unlike in a package specification, commas (not semicolons) terminate the object type program specifications. To support object comparisons and sorting, the type can optionally include one comparison method -- either ORDER or MAP. Member programs can assert purity with the RESTRICT_REFERENCES pragma. (See the earlier Section 1.15.1, "Syntax for Calling Stored Functions in SQL " section for more information on this pragma.) Member methods can be overloaded in object types following the same rules as function and procedure overloading in packages. The syntax for creating the object type body is: CREATE [OR REPLACE] TYPE BODY obj_type_name AS OBJECT ( [MEMBER | STATIC PROCEDURE | FUNCTION program_body;] [ORDER | MAP MEMBER FUNCTION comparison_function_body;] ); The keyword STATIC is new starting with Oracle8i. Static methods do not use the current SELF object.
1.16.2 Methods Every object has a default method, a constructor, which has the same name as the object type. The constructor constructs an instance of the object type from the elements passed to it, and returns the new object. This built-in method: ● ● ● ●
●
Has the same name as the object type Is a function that returns an object of that type Accepts attributes in named or positional notation Must be called with a value (or NULL) for every attribute -- there is no DEFAULT clause for object attributes Cannot be modified
If you wish to create your own pseudo-constructor, create a STATIC function that returns an object of the corresponding type.
All non-static methods have the built-in parameter SELF, which references the instance of the object. The default mode for the SELF parameter is IN for functions and IN OUT for procedures. SELF can be explicitly declared with a non-default mode. ORDER and MAP methods establish ordinal positions of objects for non-equality comparisons such as "<" or "between" and for sorting (ORDER BY, GROUP BY, DISTINCT). An ORDER function accepts two parameters: SELF, and another object of the same type. It must return an INTEGER with values of -1, 0, 1, or NULL. See the following table for a description of these return values. Return Value Object Comparison -1
SELF < second object
0
SELF = second object
1
SELF > second object
NULL
Undefined comparison, i.e., attributes needed for the comparison are NULL
For example, the Senate ranks majority party members higher than non-majority party members and within the majority (or non-majority), by years of service. Here is an example ORDER function incorporating these rules: CREATE TYPE senator_t AS OBJECT ( majority boolean_t, yrs_service NUMBER, ORDER MEMBER FUNCTION ranking (other IN senator_t) RETURN INTEGER ); CREATE OR REPLACE TYPE BODY senator_t AS ORDER MEMBER FUNCTION ranking (other IN senator_t) RETURN INTEGER IS BEGIN IF SELF.majority.istrue() AND other.majority.istrue() THEN RETURN SIGN(SELF.yrs_service other.yrs_service); ELSIF SELF.majority.istrue() AND other.majority.isfalse()
THEN RETURN 1; ELSIF SELF.majority.isfalse() AND other.majority.istrue() THEN RETURN -1; ELSIF SELF.majority.isfalse() AND other.majority.isfalse() THEN RETURN SIGN(SELF.yrs_service other.yrs_service); END IF; END ranking; END; A MAP function accepts no parameters and returns a scalar datatype such as DATE, NUMBER, or VARCHAR2 for which Oracle already knows a collating sequence. The MAP function translates, or maps, each object into a scalar datatype space that Oracle knows how to compare. When they exist, MAP methods are often more efficient than ORDER methods and are required for hash joins on the object in SQL. If no ORDER or MAP function exists for an object type, SQL, but not PL/SQL, supports only limited equality comparisons of objects. Objects are equal if they are of the same object type and if each attribute is equal.
1.16.3 Manipulating Objects in PL/SQL and SQL There are three ways to initialize an object: 1. Using the constructor method 2. Directly assignmening an existing object to a new object 3. Using SELECT INTO or FETCH INTO Here is an example using each initialization technique: DECLARE project_boiler_plate build_web_site
project_t; project_t;
-- Initialize via constructor. new_web_mgr proj_mgr_t := proj_mgr_t('Ruth', 'Home Office'); CURSOR template_cur IS SELECT VALUE(proj)
FROM projects WHERE project_type = 'TEMPLATE' AND sub_type = 'WEB SITE'; BEGIN OPEN template_cur; -- Initialize via FETCH INTO. FETCH template_cur INTO project_boiler_plate; -- Initialize via assignment. build_web_site := project_boiler_plate; ... After an object is initialized, it can be stored in the database, and you can then locate and use that object with the REF, VALUE, and DEREF operators. 1.16.3.1 The REF operator REF, short for REFerence, designates a datatype modifier or an operator to retrieve a logical pointer to an object. This pointer encapsulates the OID and can simplify navigation among related database objects. The syntax for a REF operator is: REF(table_alias_name) For example: SELECT REF(p) FROM pets p WHERE ... A PL/SQL variable can hold a reference to a particular object type: DECLARE petref REF Pet_t; BEGIN SELECT REF(p) INTO petref FROM pets p WHERE ... Through deletions, REFs can reference a nonexistent object -- called a dangling REF -- resulting in a state that can be detected with the IS DANGLING predicate. For example: UPDATE pets SET owner_ref = NULL WHERE owner_ref IS DANGLING. 1.16.3.2 The VALUE operator
Use the VALUE operator to retrieve a row object as a single object rather than multiple columns. The syntax for the VALUE operator is: VALUE(table_alias_name) For example: SELECT VALUE(p) FROM pets p WHERE ... 1.16.3.3 The DEREF operator Use the DEREF operator to retrieve the value of an object for which you have a REF. The syntax for the DEREF operator is: DEREF(table_alias_name) For example: DECLARE person_ref REF person_t; author person_t; BEGIN -- Get the ref. SELECT REF(p) INTO person_ref FROM persons WHERE p.last_name ='Pribyl'; -- Dereference the pointer back to the value. SELECT DEREF(person_ref) INTO author FROM dual; ... Additionally, Oracle uses an OID internally as a unique key to each object. Like a ROWID, you don't typically use an OID directly. The following table shows ways of referencing persistent objects. Scheme Description
Applications
OID
This is the persistent object's handle; it's what REFs point to. Your program never uses it directly.
An opaque, globally unique handle, produced when the object is stored in the database as a table (row) object.
VALUE An operator. In SQL, it acts on an object in an object table and returns the object's contents. Different from the VALUES keyword found in some INSERT statements.
Allows quasi-normalizing of objectrelational databases and joining of object tables using dot navigation. In PL/SQL, REFs serve as input/output variables.
REF
Used when fetching a table (row) object into a variable, or when you need to refer to an object table as an object instead of a list of columns.
A pointer to an object. May be used within a SQL statement as an operator or in a declaration as a type modifier.
DEREF Reverse pointer lookup for REFs.
Used for retrieving the contents of an object when all you know is its REF.
1.16.4 Changing Object Types You can add methods, but not attributes, to an object type stored in the database using the ALTER TYPE statement: ALTER TYPE type_name REPLACE AS OBJECT ( new_object_type_specification ); The only supported change you can make in the new object type specification is to include new methods. It is also possible to rebuild an object table with different physical storage characteristics by using the built-in procedure DBMS_DDL.ALTER_TABLE_REFERENCEABLE. The syntax for dropping an object type is: DROP TYPE type_name [FORCE]; You can drop only an object type that has not been implemented in a table (or you can drop the tables first). The FORCE option will drop object types even if they have dependencies, but FORCE will irreversibly invalidate any dependent objects such as tables. FORCE does not do a DROP CASCADE.
Previous: 1.15 Calling PL/ SQL Functions in SQL 1.15 Calling PL/SQL Functions in SQL
Oracle PL/SQL Language Pocket Reference
Next: 1.17 Collections 1.17 Collections
The Oracle Library Navigation Copyright (c) 2000 O'Reilly & Associates. All rights reserved.
Chapter 1 Oracle PL/SQL Language Pocket Reference
Previous: 1.16 Oracle8 Objects
Next: 1.18 External Procedures
1.17 Collections There are three types of collections: index-by tables (formerly known as PL/SQL tables), nested tables, and VARRAYs. Index-by table Single-dimension, unbounded collections of homogeneous elements available only in PL/ SQL, not in the database. Index-by tables are initially sparse; they have nonconsecutive subscripts. Nested table Single-dimension, unbounded collections of homogeneous elements available in both PL/SQL and the database as columns or tables. Nested tables are initially dense (they have consecutive subscripts), but can become sparse through deletions. VARRAYs Variable-size arrays are single-dimension, bounded collections of homogeneous elements available in both PL/SQL and the database. VARRAYs are never sparse. Unlike nested tables, their element order is preserved when you store and retrieve them from the database. The following table compares these similar collection types. Collection Type Characteristic
Index-by Table
Nested Table
VARRAY
Dimensionality
Single
Single
Single
Usable in SQL?
No
Yes
Yes
Usable as a column datatype in a table?
No
Yes; data stored "out of line" (in a separate table)
Yes; data typically stored "in line" (in the same table)
Uninitialized state
Empty (cannot be NULL); elements are undefined
Atomically null; illegal to reference elements
Atomically null; illegal to reference elements
Initialization
Automatic, when declared
Via constructor, fetch, assignment
Via constructor, fetch, assignment
In PL/SQL, elements referenced by
BINARY_INTEGER (2,147,483,647
Positive integer between 1 and 2,147483,647
Positive integer between 1 and 2,147483,647
.. 2,147,483,647) Sparse?
Yes
Initially no; after deletions, yes
No
Bounded?
No
Can be extended
Yes
Can assign a value to any element at any time?
Yes
No; may need to EXTEND first
No; may need to EXTEND first, and cannot EXTEND past the upper bound
Means of extending
Assign value to element with a new subscript
Use built-in EXTEND procedure or TRIM to condense, with no predefined maximum
EXTEND or TRIM, but only up to declared maximum size.
Can be compared for equality?
No
No
No
No
Yes
Elements retain N/A -- can't be stored in ordinal position and database subscript when stored and retrieved from the database
1.17.1 Syntax for Declaring Collection Datatypes Collections are implemented as TYPEs. Like any programmer-defined type, you must first define the type; then you can declare instances of that type. The TYPE definition can be stored in the database or declared in the PL/SQL program. Each instance of the TYPE is a collection.
The syntax for declaring an index-by table is: TYPE type_name IS TABLE OF element_type [NOT NULL] INDEX BY BINARY_INTEGER; The syntax for a nested table is: [CREATE [OR REPLACE]] TYPE type_name IS TABLE OF element_type [NOT NULL]; The syntax for a VARRAY is: [CREATE [OR REPLACE]] TYPE type_name IS VARRAY | VARYING ARRAY (max_elements) OF element_type [NOT NULL]; The CREATE keyword defines the statement to be DDL and indicates that this type will exist in the database. The optional OR REPLACE keywords are used to rebuild an existing type, preserving the privileges. type_name is any valid identifier that will be used later to declare the collection. max_elements is the maximum size of the VARRAY. element_type is the type of the collection's elements. All elements are of a single type, which can be most scalar datatypes, an object type, or a REF object type. If the elements are objects, the object type itself cannot have an attribute that is a collection. Explicitly disallowed collection datatypes are BOOLEAN, NCHAR, NCLOB, NVARCHAR2, REF CURSOR, TABLE, and VARRAY. NOT NULL indicates that a collection of this type cannot have any null elements. However, the collection can be atomically null (uninitialized).
1.17.2 Initializing Collections Initializing an index-by table is trivial -- simply declaring it also initializes it. Initializing a nested table or VARRAY can be done explicitly, with a constructor, or implicitly with a fetch from the database or a direct assignment of another collection variable. The constructor is a built-in function with the same name as the collection. It constructs the collection from the elements passed to it. We can create a nested table of colors and initialize it to three elements with a constructor: DECLARE TYPE colors_tab_t IS TABLE OF VARCHAR2(30); colors_tab_t('RED','GREEN','BLUE'); BEGIN
We can create our nested table of colors and initialize it with a fetch from the database: -- Create the nested table to exist in the database. CREATE TYPE colors_tab_t IS TABLE OF VARCHAR2(32); -- Create table with nested table type as column. CREATE TABLE color_models (model_type VARCHAR2(12) ,colors color_tab_t) NESTED TABLE colors STORE AS color_model_colors_tab; -- Add some data to the table. INSERT INTO color_models VALUES('RGB',color_tab_t('RED','GREEN','BLUE')); INSERT INTO color_models VALUES('CYMK',color_tab_t('CYAN','YELLOW', 'MAGENTA' 'BLACK')); -- Initialize a collection of colors from the table. DECLARE basic_colors colors_tab_t; BEGIN SELECT colors INTO basic_colors FROM color_models WHERE model_type = 'RGB'; ... END; The third initialization technique is by assignment from an existing collection: DECLARE basic_colors Color_tab_t := Color_tab_t ('RED','GREEN','BLUE'); my_colors Color_tab_t; BEGIN my_colors := basic_colors; my_colors(2) := 'MUSTARD';
1.17.3 Adding and Removing Elements Elements in an index-by table can be added simply by referencing new subscripts. To add elements to nested tables or VARRAYs, you must first enlarge the collection with the EXTEND function, and then you can assign a value to a new element using one of the methods described in the previous
section. Use the DELETE function to remove an element in a nested table regardless of its position. The TRIM function can also be used to remove elements, but only from the end of a collection. To avoid unexpected results, do not use both DELETE and TRIM on the same collection.
1.17.4 Collection Pseudo-Functions There are several psuedo-functions defined for collections. They include THE, CAST, MULTISET, and TABLE. THE Maps a single column's value in a single row into a virtual database table. Syntactically, this is similar to an inline view, where a subquery is used in the FROM clause. SELECT VALUE(c) FROM THE(SELECT colors FROM color_models WHERE model_type = 'RGB') c; The pseudo-function THE will work in Oracle8i but its use is discouraged. Use the 8i TABLE( ) function instead. CAST Maps a collection of one type to a collection of another type. SELECT column_value FROM THE(SELECT CAST(colors AS color_tab_t) FROM color_models_a WHERE model_type ='RGB'); MULTISET Maps a database table to a collection. With MULTISET and CAST, you can retrieve rows from a database table as a collection-typed column. SELECT b.genus ,b.species, CAST(MULTISET(SELECT bh.country FROM bird_habitats bh WHERE bh.genus = b.genus AND bh.species = b.species) AS country_tab_t)
FROM birds b; TABLE Maps a collection to a database table; the inverse of MULTISET. SELECT * FROM color_models c WHERE 'RED' IN (SELECT * FROM TABLE(c.colors)); In Oracle8i PL/SQL, you can use TABLE( ) to unnest a transient collection: DECLARE birthdays Birthdate_t := Birthdate_t('24-SEP-1984', '19-JUN-1993'); BEGIN FOR the_rec IN (SELECT COLUMN_VALUE FROM TABLE(CAST(birthdays AS Birthdate_t)))
1.17.5 Collection Methods There are a number of built-in functions (methods) defined for all collections. These methods are called with dot notation: collection_name.method_name[(parameters)] The methods are described in the following table. Collection Method
Description
COUNT function
Returns the current number of elements in the collection.
DELETE [( i [,j ] )] procedure
Removes element i or elements i through j from a nested table or index-by table. When called with no parameters, removes all elements in the collection. Reduces the COUNT if the element is not already DELETEd. Does not apply to VARRAYs.
EXISTS ( i ) function
Returns TRUE or FALSE to indicate whether element i exists. If the collection is an uninitialized nested table or VARRAY, returns FALSE.
EXTEND [( n [,i ] )] procedure Appends n elements to a collection, initializing them to the value of element i. n is optional and defaults to 1.
FIRST function
Returns the smallest index in use. Returns NULL when applied to empty initialized collections.
LAST function
Returns the largest index in use. Returns NULL when applied to empty initialized collections.
LIMIT function
Returns the maximum number of allowed elements in a VARRAY. Returns NULL for index-by tables and nested tables.
PRIOR ( i ) function
Return the index immediately before element i. Returns NULL if i is less than or equal to FIRST.
NEXT ( i ) function
Return the index immediately after element i. Returns NULL if i is greater than or equal to COUNT.
TRIM [( n )] procedure
Removes n elements at the end of the collection with the largest index. n is optional and defaults to 1. If n is NULL, TRIM does nothing. Index-by tables cannot be TRIMmed.
The EXISTS function returns a BOOLEAN and all other functions return BINARY_INTEGER. All parameters are of the BINARY_INTEGER type. Only EXISTS can be used on uninitialized nested tables or VARRAYs. Other methods applied to these atomically null collections will raise the COLLECTION_IS_NULL exception. DELETE and TRIM both remove elements from a nested table, but TRIM also removes the placeholder, while DELETE does not. This behavior may be confusing, since TRIM can remove previously DELETED elements. Here is an example of some collection methods in use: DECLARE TYPE colors_tab_t IS TABLE OF VARCHAR2(30); my_list colors_tab_t := colors_tab_t('RED','GREEN','BLUE'); element BINARY_INTEGER; BEGIN DBMS_OUTPUT.PUT_LINE('my_list has ' ||my_list.COUNT||' elements'); my_list.DELETE(2); -- delete element two DBMS_OUTPUT.PUT_LINE('my_list has ' ||my_list.COUNT||' elements'); FOR element IN my_list.FIRST..my_list.LAST LOOP IF my_list.EXISTS(element) THEN
DBMS_OUTPUT.PUT_LINE(my_list(element) || ' Prior= '||my_list.PRIOR(element) || ' Next= ' ||my_list.NEXT(element)); ELSE DBMS_OUTPUT.PUT_LINE('Element '|| element ||' deleted. Prior= '||my_ list.PRIOR(element) || ' Next= '||my_list.NEXT(element)); END IF; END LOOP; END; This example gives the output: my_list has 3 elements my_list has 2 elements RED Prior= Next= 3 Element 2 deleted. Prior= 1 Next= 3 BLUE Prior= 1 Next=
1.17.6 Privileges As with other TYPEs in the database, you need the EXECUTE privilege on that TYPE in order to use a collection type created by another schema (user account) in the database.
1.17.7 Bulk Binds (Oracle8i) Starting with Oracle8i, you can use collections to improve the performance of SQL operations executed iteratively by using bulk binds. Bulk binds reduce the number of round-trips that must be made between a client application and the database. Two PL/SQL language constructs implement bulk binds: FORALL and BULK COLLECT INTO. The syntax for the FORALL statement is: FORALL bulk_index IN lower_bound..upper_bound sql_statement; bulk_index can be used only in the sql_statement and only as a collection index (subscript). When PL/ SQL processes this statement, the whole collection, instead of each individual collection element, is sent to the database server for processing. To delete all the accounts in the collection inactives from the table ledger, do this: FORALL i IN inactives.FIRST..inactives.LAST DELETE FROM ledger WHERE acct_no = inactives(i);
The syntax for the BULK COLLECT INTO clause is: BULK COLLECT INTO collection_name_list; where collection_name_list is a comma-delimited list of collections, one for each column in the SELECT. As of Oracle8i, collections of records cannot be a target of a BULK COLLECT INTO clause. However, 8i does support retrieving a set of typed objects and "bulk collecting" them into a collection of objects. The BULK COLLECT INTO clause can be used in SELECT INTO, FETCH INTO, or RETURNING INTO statements. For example: DECLARE TYPE vendor_name_tab IS TABLE OF vendors.name%TYPE; TYPE vendor_term_tab IS TABLE OF vendors.terms%TYPE; v_names vendor_name_tab; v_terms vendor_term_tab; BEGIN SELECT name, terms BULK COLLECT INTO v_names, v_terms FROM vendors WHERE terms < 30; ... END; The next function deletes employees in an input list of departments, and the (Oracle8) SQL RETURNING clause returns a list of deleted employees: FUNCTION whack_emps_by_dept (deptlist dlist_t) RETURN enolist_t IS enolist enolist_t; BEGIN FORALL adept IN deptlist.FIRST..deptlist.LAST DELETE FROM emp WHERE deptno IN deptlist(adept) RETURNING empno BULK COLLECT INTO enolist; RETURN Enolist; END; You can use the SQL%BULK_ROWCOUNT cursor attribute for bulk bind operations. It is like an index-by table containing the number of rows affected by the executions of the bulk bound statements. The nth element of SQL%BULK_ROWCOUNT contains the number of rows affected by
nth execution of the SQL statement. For example: FORALL i IN inactives.FIRST..inactives.LAST DELETE FROM ledger WHERE acct_no = inactives(i); FOR counter IN inactives.FIRST..inactives.LAST LOOP IF SQL%BULK_ROWCOUNT(counter) = 0 THEN DBMS_OUTPUT.PUT_LINE('No rows deleted for '|| counter); END IF; END LOOP; You cannot pass SQL%BULK_ROWCOUNT as a parameter to another program, or use an aggregate assignment to another collection. %ROWCOUNT contains a summation of all % BULK_ROWCOUNT elements. %FOUND and %NOTFOUND reflect only the last execution of the SQL statement.
Previous: 1.16 Oracle8 Objects 1.16 Oracle8 Objects
Oracle PL/SQL Language Pocket Reference
The Oracle Library Navigation Copyright (c) 2000 O'Reilly & Associates. All rights reserved.
Next: 1.18 External Procedures 1.18 External Procedures
Previous: 1.17 Collections
Chapter 1 Oracle PL/SQL Language Pocket Reference
Next: 1.19 Java Language Integration
1.18 External Procedures External procedures provide a mechanism for calling out to a non-database program, such as a DLL under NT or a shared library under Unix. Every session calling an external procedure will have its own extproc process started by the listener. This extproc process is started with the first call to the external procedure and terminates when the session exits. The shared library needs to have a corresponding library created for it in the database.
1.18.1 Creating an External Procedure The following are the steps you need to follow in order to create an external procedure. 1.18.1.1 Set up the listener External procedures require a listener. If you are running a Net8 listener, it can be used as the extproc listener as well. See the Oracle8 Administrators' Guide or the Net8 Administrators' Guide for the details on configuring your listener. 1.18.1.2 Identify or create the shared library or DLL This step has nothing to do with PL/SQL or the database. You must write your own C routines and link them into a shared library/DLL or use an existing library's functions or procedures. In the simple example below, we will use the existing random number generating calls available from the operating system. 1.18.1.3 Create the library in the database Create a library in the database for the shared library or DLL using the CREATE LIBRARY statement: CREATE [OR REPLACE] LIBRARY library_name IS | AS 'absolute_path_and_file';
To remove libraries from the database, you use the DROP LIBRARY statement: DROP LIBRARY library_name; To call out to the C runtime library's rand function, you don't have to code any C routines at all, since the call is already linked into a shared library, and because its arguments are directly type-mappable to PL/SQL. If the rand function is in the standard /lib/libc.so shared library, as on Solaris, you would issue the following CREATE LIBRARY statement: CREATE OR REPLACE LIBRARY libc_l AS '/lib/libc.so'; -- References C runtime library. This is the typical corresponding statement for NT: CREATE OR REPLACE LIBRARY libc_l AS 'C:\WINNT\SYSTEM32\CRTDLL.DLL'; 1.18.1.4 Create the PL/SQL wrapper for the external procedure The syntax for the wrapper procedure is: CREATE [OR REPLACE] PROCEDURE proc_name [parm_list] AS|IS EXTERNAL LIBRARY library_name [NAME external_name] [LANGUAGE language_name] [CALLING STANDARD C | PASCAL] [WITH CONTEXT] [PARAMETERS (external_parameter_list)]; The following are the syntactic elements defined: proc_name The name of the wrapper procedure. library_name The name of the library created with the CREATE LIBRARY statement. external_name The name of the external routine as it appears in the library. It defaults to the wrapper package name. PL/SQL package names are usually saved in uppercase, so the external_name may need to be enclosed in double quotes to preserve case.
language_name The language that the external routine was written in. It defaults to C. CALLING STANDARD The calling standard, which defaults to C. The Pascal calling standard reverses the order of the parameters, and the called routine is responsible for popping the parameters off the stack. WITH CONTEXT Used to pass a context pointer to the external routine, so it can make OCI calls back to the database. PARAMETERS Identify the external_parameter_list, which is a comma-delimited list containing the position and datatype of parameters that get passed to the external routine. For more details on the external_parameter_list, see the next section, Section 1.12.3, "Parameters". The wrapper PL/SQL function or procedure is usually in a package. Using the preceding random number generator example, we could create the wrapper package as follows: CREATE OR REPLACE PACKAGE random_utl AS FUNCTION rand RETURN PLS_INTEGER; PRAGMA RESTRICT_REFERENCES(rand,WNDS,RNDS,WNPS,RNPS); PROCEDURE srand (seed IN PLS_INTEGER); PRAGMA RESTRICT_REFERENCES(srand,WNDS,RNDS,WNPS,RNPS); END random_utl; CREATE PACKAGE BODY random_utl AS FUNCTION rand RETURN PLS_INTEGER IS EXTERNAL -- Keyword to indicate external routine. LIBRARY libc_l -- The library created above. NAME "rand" -- Function name in the library. LANGUAGE C; -- Language of routine. PROCEDURE srand (seed IN PLS_INTEGER) IS EXTERNAL LIBRARY libc_l NAME "srand" -- Name is lowercase in this library.
LANGUAGE C PARAMETERS (seed ub4); --Map to unsigned 4byte. INT END random_utl; To use this external random number function, we simply call the package procedure srand to seed the generator, then the package function rand to get random numbers: DECLARE random_nbr PLS_INTEGER; seed PLS_INTEGER; BEGIN SELECT TO_CHAR(SYSDATE,'SSSSS') INTO seed FROM dual; random_utl.srand(seed);
-- Seed the generator.
random_nbr := random_utl.rand; -- Get the number. DBMS_OUTPUT.PUT_LINE('number='||random_nbr); random_nbr := random_utl.rand; -- Get the number. DBMS_OUTPUT.PUT_LINE('number='||random_nbr); END; You can generate random numbers without the complexity or overhead of an external call by using the built-in package DBMS_RANDOM. To learn more about DBMS_RANDOM and other built-ins, see O'Reilly's books Oracle Built-in Packages and Oracle PL/SQL Built-ins Pocket Reference.
1.18.2 Parameters When it comes to passing PL/SQL variables to C variables, we encounter many inconsistencies. For example, PL/SQL supports nullity, while C does not; PL/SQL can have variables in different character sets, while C cannot; and the datatypes in PL/SQL do not directly map to C datatypes. The PARAMETERS clause specifies the external parameter list, a comma-delimited list containing parameters. The syntax for each parameter in the list is: CONTEXT | RETURN | parameter_name [property] [BY REFERENCE] [external_datatype] The keyword CONTEXT indicates the position in the parameter list at which the context pointer will be passed. It is required if the WITH CONTEXT clause is being used to pass a context pointer to the called program. By convention, CONTEXT appears as the first parameter in the external parameter list. If CONTEXT is used, the property, BY REFERENCE, and external_datatype optional sections
are invalid. The keyword RETURN indicates that the descriptions are for the return value from the external routine. By default, RETURN is passed by value. You can use the keywords BY REFERENCE to pass by reference (use pointers). parameter_name is a PL/SQL formal parameter name. By default, IN formal parameters are passed by value. You can use the key words BY REFERENCE to pass by reference (as a pointer). IN OUT and OUT formal parameters are always passed by reference. property breaks out further to the general Oracle8 syntax: INDICATOR | LENGTH | MAXLEN | CHARSETID| CHARSETFORM The general Oracle8i syntax is: INDICATOR [STRUCT | TDO ] | LENGTH | MAXLEN | CHARSETID | CHARSETFORM | SELF INDICATOR indicates whether the corresponding parameter is NULL. In the C program, if the indicator equals the constant OCI_IND_NULL, the parameter is NULL. If the indicator equals the constant OCI_IND_NOTNULL, the indicator is not NULL. For IN parameters, INDICATOR is passed by value (by default). For IN OUT, OUT, and RETURN parameters, INDICATOR is passed by reference. In Oracle8i, you can pass a user-defined type to an external procedure. To do so, you will typically pass three parameters: the actual object value; a TDO (Type Descriptor Object) parameter as defined in C by the Oracle Type Translator; and an INDICATOR STRUCT parameter, to designate whether the object is NULL. LENGTH and MAXLEN can be used to pass the current and maximum length of strings or RAWs. For IN parameters, LENGTH is passed by value (by default). For IN OUT, OUT, and RETURN parameters, LENGTH is passed by reference. MAXLEN is not valid for IN parameters. For IN OUT, OUT, and RETURN parameters, MAXLEN is passed by reference and is read-only. CHARSETID and CHARSETFORM are used to support NLS character sets. They are the same as the OCI attributes OCI_ATTR_CHARSET_ID and OCI_ATTR_CHARSET_FORM. For IN parameters, CHARSETID and CHARSETFORM are passed by value (by default) and are read-only. For IN OUT, OUT, and RETURN parameters, CHARSETID and CHARSETFORM are passed by reference and are read-only. SELF is used if an object member function is implemented as a callout instead of a PL/SQL routine.
Previous: 1.17 Collections
Oracle PL/SQL Language Pocket Reference
1.17 Collections
The Oracle Library Navigation Copyright (c) 2000 O'Reilly & Associates. All rights reserved.
Next: 1.19 Java Language Integration 1.19 Java Language Integration
Previous: 1.18 External Procedures
Chapter 1 Oracle PL/SQL Language Pocket Reference
1.19 Java Language Integration In Oracle8i, Java(TM) programmers can write server-side classes that invoke SQL and PL/SQL using standard JDBC(TM) or SQLJ calls. PL/SQL programmers can call server-side Java methods by writing a PL/SQL cover or call spec for Java using Oracle DDL. Server-side Java in Oracle may be faster than PL/SQL for compute-intensive programs, but not as nimble for database access. PL/SQL is much more efficient for database-intensive routines because, unlike Java, it doesn't have to pay the overhead for converting SQL datatypes for use inside the stored program. Oracle programmers will want to continue to use PL/SQL for programs that perform a lot of database I/O, and use Java for the best raw computation performance. The first step in creating a Java stored procedure ( JSP) is writing or otherwise obtaining functional Java code. Having source code is not necessary, though, so you can use class libraries from third parties. The classes must, however, meet the following requirements: ●
●
Methods published to SQL and PL/SQL must be declared static. PL/SQL has no mechanisms for instantiating non-static Java classes. The classes must not issue any GUI calls (for example, to AWT) at runtime.
If you write your own JSP, and it needs to connect to the database for access to tables or stored procedures, use standard JDBC and/or SQLJ calls in your code. Many JDBC and SQLJ reference materials are available to provide assistance in calling SQL or PL/SQL from Java, but be sure to review the Oracle-specific documentation that ships with Oracle8i. Once you have the Java class in hand, either in source or .class file format, the next step is loading it into the database. Oracle's loadjava command-line utility is a convenient way to accomplish the load. Refer to Oracle's documentation for further assistance with loadjava. The third step is to create a call spec for the Java method, specifying the AS LANGUAGE JAVA clause of the CREATE command. You may create a function or procedure cover as appropriate. Finally, you may grant execute privileges on the new JSP using GRANT EXECUTE, and PL/SQL
routines can now call the JSP as if it were another PL/SQL module.
1.19.1 Example Let's write a simple "Hello, World" JSP that will accept an argument: package oreilly.plsquick.demos; public class Hello { public static String sayIt (String toWhom) { return "Hello, " + toWhom + "!"; } } Saved in a file called Hello.java, we can load the source code directly into Oracle. Doing so will automatically compile the code. A simple form of the loadjava command: loadjava -user scott/tiger -oci8 oreilly/plsquick/ demos/Hello.java The Hello.java file follows the Java file placement convention for packages and so exists in a subdirectory named oreilly/plsquick/demos. Now we can fire up our favorite SQL interpreter, connect as SCOTT/TIGER, and create the call spec for the Hello.sayIt( ) method: CREATE FUNCTION hello_there (to_whom IN VARCHAR2) RETURN VARCHAR2 AS LANGUAGE JAVA NAME 'oreilly.plsquick.demos.Hello.sayIt (java.lang.String) return java.lang.String'; / Now we can call our function very easily: BEGIN DBMS_OUTPUT.PUT_LINE(hello_there('world')); END; / And we get: Hello, world!
as the expected output.
1.19.2 Publishing Java to PL/SQL To write a call spec, use the AS LANGUAGE JAVA clause in a CREATE statement. The syntax for this clause is: { IS | AS } LANGUAGE JAVA NAME 'method_fullname [ (type_fullname,... ] [ return type_fullname ]' method_fullname is the package-qualified name of the Java class and method. It is case-sensitive and uses dots to separate parts of the package full name. type_fullname is the package-qualified name of the Java datatype. Notice that a simple string, not an SQL name, follows the NAME keyword. Type mapping follows most JDBC rules regarding the legal mapping of SQL types to Java types. Oracle extensions exist for Oracle-specific datatypes. Most datatype mappings are relatively straightforward, but passing Oracle8 objects of a user-defined type is harder than one would think. Oracle provides a JPublisher tool that generates the Java required to encapsulate an Oracle8 object and its corresponding REF. Refer to Oracle's JPublisher documentation for guidelines on usage. The AS LANGUAGE JAVA clause is the same whether you are using Java as a standalone JSP, the implementation of a packaged program, or the body of an object type method. For example, here is the complete syntax for creating JSPs as PL/SQL-callable functions or procedures: CREATE [OR REPLACE] { PROCEDURE procedure_name [(param[, param]...)] | FUNCTION function_name [(param[, param]...)] RETURN sql_type } [AUTHID {DEFINER | CURRENT_USER}] [PARALLEL_ENABLE] [DETERMINISTIC] { IS | AS } LANGUAGE JAVA NAME 'method_fullname [ (type_fullname,... ] [ return type_fullname ]' When using Java as the implementation of a packaged procedure or function, Oracle allows you to place the Java call spec in either the package specification (where the call spec substitutes for the subprogram specification) or in the package body (where the call spec substitutes for the subprogram body).
Similarly, when using JSPs in object type methods, the Java call spec can substitute for either the object type method specification or its body. Note that Java functions typically map to PL/SQL functions, but Java functions declared void map to PL/SQL procedures. Also, you will quickly learn that mistakes in mapping PL/SQL parameters to Java parameters become evident only at runtime.
1.19.3 Data Dictionary To learn what Java library units are available in your schema, look in the USER_OBJECTS data dictionary view where the object_type is like `JAVA%'. If you see a Java class with INVALID status, it has not yet been successfully resolved. Note that the names of the Java source library units need not match the names of the classes they produce. As of press time, there is no apparent way to discover which stored programs are implemented as Java stored procedures. You can look in the USER_SOURCE view for named programs that contain the source text `AS LANGUAGE JAVA', but that may not yield accurate results. The USER_DEPENDENCIES view does not track the relationship between PL/SQL cover programs and their underlying Java class. Even if you have loaded the Java source code into the database, there is no supported way of retrieving the source from the data dictionary.
Previous: 1.18 External Procedures 1.18 External Procedures
Oracle PL/SQL Language Pocket Reference
The Oracle Library Navigation Copyright (c) 2000 O'Reilly & Associates. All rights reserved.
By Steven Feuerstein & Bill Pribyl; ISBN 1-56592-335-9E Second Edition, published September 1997. (See the catalog page for this book.)
Search the text of Oracle PL/SQL Programming, 2nd Edition.
Index Symbols | A | B | C | D | E | F | G | H | I | J | K | L | M | N | O | P | Q | R | S | T | U | V | W | Y | Z
Table of Contents Dedication Foreword Preface
Part I: Programming in PL/SQL Chapter 1: Introduction to PL/SQL Chapter 2: PL/SQL Language Fundamentals Chapter 3: Effective Coding Style
Part II: PL/SQL Language Elements Chapter 4: Variables and Program Data Chapter 5: Conditional and Sequential Control Chapter 6: Database Interaction and Cursors Chapter 7: Loops Chapter 8: Exception Handlers Chapter 9: Records in PL/SQL Chapter 10: PL/SQL Tables
Part III: Built-In Functions
Chapter 11: Character Functions Chapter 12: Date Functions Chapter 13: Numeric, LOB, and Miscellaneous Functions Chapter 14: Conversion Functions
Part IV: Modular Code Chapter 15: Procedures and Functions Chapter 16: Packages Chapter 17: Calling PL/SQL Functions in SQL
Part V: New PL/SQL8 Features Chapter 18: Object Types Chapter 19: Nested Tables and VARRAYs Chapter 20: Object Views Chapter 21: External Procedures
Part VI: Making PL/SQL Programs Work Chapter 22: Code Design Tips Chapter 23: Managing Code in the Database Chapter 24: Debugging PL/SQL Chapter 25: Tuning PL/SQL Applications Chapter 26: Tracing PL/SQL Execution
Part VII: Appendixes Appendix A: What's on the Companion Disk? Appendix B: Calling Stored Procedures from PL/SQL Version 1.1 Appendix C: Built-In Packages
The Oracle PL/SQL CD Bookshelf Navigation Copyright © 2000 O'Reilly & Associates. All Rights Reserved.
Full Text Search
If you are having difficulty searching, or if you have not used this search utility before, please read this.
The Oracle PL/SQL CD Bookshelf Navigation
Symbols | A | B | C | D | E | F | G | H | I | J | K | L | M | N | O | P | Q | R | S | T | U | V | W | Y | Z
Index: Symbols and Numbers \:= (assignment) operator 2.1. The PL/SQL Character Set 4.4.3. Default Values 9.5. Assigning Values to and from Records -- (comment indicator) : 2.5.1. Single-Line Comment Syntax > (label delimeters) : 5.2.1. The GOTO Statement ' (quotation mark) 2.3.1. Embedding Single Quotes Inside a String 11.1.10. The REPLACE function ; (semicolon) : 2.4. The Semicolon Delimiter /* and */ (comment block delimiters) : 2.5.2. Multiline Comment Syntax || (concatenation) operator 4.3.3. Function Results with NULL Arguments 11.1.3. The CONCAT function
Symbols | A | B | C | D | E | F | G | H | I | J | K | L | M | N | O | P | Q | R | S | T | U | V | W | Y | Z
The Oracle Library Navigation Copyright (c) 2000 O'Reilly & Associates. All rights reserved.
Symbols | A | B | C | D | E | F | G | H | I | J | K | L | M | N | O | P | Q | R | S | T | U | V | W | Y | Z
Index: A ABS function : 13.1.1. The ABS function absolute value : 13.1.1. The ABS function abstract data types : (see ADTs) abstraction : 18.1.5.3. Abstraction access to compiled code, tuning : 25.2. Tuning Access to Compiled Code to data, tuning : 25.3. Tuning Access to Your Data data structure, encapsulating : 1.7.2. Synchronize Program and Data Structures to SQL, minimizing : 25.3.1. Use Package Data to Minimize SQL Access ACCESS table, tuning : 25.2.3. Tune ACCESS$ Table to Reduce First Execution Time of Code actual parameters : 15.6.3. Actual and Formal Parameters Ada programming language : Preface ADD_MONTHS function : 12.1.1. The ADD_MONTHS function customizing : 12.2.1. Customizing the Behavior of ADD_MONTHS adding collection elements : 19.4.3. Adding and Removing Elements administration of Oracle databases : About the Contents administration, Oracle/AQ : C.3.2. DBMS_AQADM (PL/SQL 8 Only) ADTs (abstract datatypes) (see also object types) 18.1.4.2. Classification building : 22.6. Construct Abstract Data Types (ADTs) advanced queuing : 1.4.7.2. Oracle/AQ, the Advanced Queueing Facility ADVISE_COMMIT procedure : C.15.1. The ADVISE_COMMIT procedure ADVISE_NOTHING procedure : C.15.2. The ADVISE_NOTHING procedure ADVISE_ROLLBACK procedure : C.15.3. The ADVISE_ROLLBACK procedure aggregate assignment into rows : 10.6.3. Aggregate Assignment operations 9.1.3.2. Aggregate operations 9.5.4. Aggregate Assignment 9.6.1.2. Records of the same type of nested records : 9.7.3. Aggregate Assignments of Nested Records
values, combining with scalars : 17.8.2. Combining Scalar and Aggregate Values aggregation : 18.1.4.3. Inheritance alerts : (see DBMS_ALERT package) algorithms, tuning : 25.4. Tuning Your Algorithms aliases column 6.7. Column Aliases in Cursors 9.3.2. Setting the Record's Column Names directory : 13.2.1. The BFILENAME function for cursor variables : 6.12.6.3. Cursor variable aliases alignment of code : (see coding, layout of) ALLOCATE_UNIQUE procedure : C.7.1. The ALLOCATE_UNIQUE procedure ALTER SESSION command : 26.1.1. Enabling Program Units for Tracing ALTER TABLE statement : 20.6. Schema Evolution ALTER_COMPILE procedure : C.4.1. The ALTER_COMPILE procedure ALTER_QUEUE procedure : C.3.2.4. The ALTER_QUEUE procedure ANALYZE statement : 25.1. Analyzing Program Performance ANALYZE_OBJECT procedure : C.4.2. The ANALYZE_OBJECT procedure ANALYZE_SCHEMA procedure : C.16.1. The ANALYZE_SCHEMA procedure anchored datatypes 1.6.1. Anchored declarations 4.5. Anchored Declarations anchoring to subtypes : 4.6.3. Emulating Constrained Subtypes angle brackets (>) as label delimiters : 5.2.1. The GOTO Statement anonymous blocks : 15.3. The Anonymous PL/SQL Block labels for : 15.3.6. Block Labels nested : 15.3.4. Nested Blocks in Oracle Tools : 15.3.3. Anonymous Blocks in the Oracle Tools APPEND procedure : C.6.1. The APPEND procedure applications, tuning : 25. Tuning PL/SQL Applications access to compiled code : 25.2. Tuning Access to Compiled Code access to data : 25.3. Tuning Access to Your Data analyzing performance : 25.1. Analyzing Program Performance optimizing algorithms : 25.4. Tuning Your Algorithms AQ : (see advanced queuing) arguments, trapping invalid : 22.2.4.1. Trap invalid argument values arrays (see also tables) 1.4.3.4. PL/SQL tables building with tables : 10.9.4. Building Traditional Arrays with PL/SQL Tables package for (see also PSG_array package)
10.9.4.3. Features of the array package variable arrays : 1.4.7.3. Variable arrays and nested tables objects for : 18.1.2. Some Simple Examples variable-size : (see VARRAYs) ASCII function : 11.1.1. The ASCII function assertion modules : 22.2.4. Use Assertion Modules to Validate Parameters and Assumptions assigning objects : 18.4.1.2. Direct assignment assignment (\:=) operator 2.1. The PL/SQL Character Set 4.4.3. Default Values 9.5. Assigning Values to and from Records association operator for positional notation (=>) : 2.1. The PL/SQL Character Set association, object : 18.1.4.3. Inheritance atomics of PL/SQL language : 2.1. The PL/SQL Character Set attributes, cursor 6.9. Cursor Attributes 6.12.2. Similarities to Static Cursors attributes, object : 18.1.1. Terminology collections as : 19.2.1.2. Collection as an attribute of an object type dot notation for 18.3.4.1. Dots in data structures 18.3.4.3. Attribute or method? object equality and : 18.3.6.2. Equality comparisons authority, execute/run : (see execute authority)
Symbols | A | B | C | D | E | F | G | H | I | J | K | L | M | N | O | P | Q | R | S | T | U | V | W | Y | Z
The Oracle Library Navigation Copyright (c) 2000 O'Reilly & Associates. All rights reserved.
Symbols | A | B | C | D | E | F | G | H | I | J | K | L | M | N | O | P | Q | R | S | T | U | V | W | Y | Z
Index: B backups : 24.2.6. Document and Back Up Your Efforts batch processing : 25.3.4. Take Advantage of DBMS_SQL Batch Processing encrypting code and : 23.7.2. Working with Encrypted Code BEGIN_DISCRETE_TRANSACTION procedure : C.15.14. The BEGIN_DISCRETE_TRANSACTION procedure BFILE datatype 1.4.7.6. Large object support 4.2.7.7. Working with BFILEs example of using : 20.8. Postscript: Using the BFILE Datatype BFILENAME function 4.2.7.7. Working with BFILEs 13.2.1. The BFILENAME function binary data : (see RAW datatype) BINARY_INTEGER datatype 4.2.1.1. Binary integer datatypes 25.4.5. Use PLS_INTEGER for All Integer Operations for table declaration : 10.4.1. Defining the Table TYPE BIND_ARRAY program : 25.3.4. Take Advantage of DBMS_SQL Batch Processing BIND_VARIABLE procedure : C.14.2. The BIND_VARIABLE procedure blended access : 10.9.5.6. Performance impact of blended access BLOB datatype 1.4.7.6. Large object support 4.2.7.2. The BLOB datatype EMPTY_BLOB function : 13.2.2. The EMPTY_BLOB function block comments : 2.5.2. Multiline Comment Syntax blocks (see also modules) 2.7. Block Structure 15. Procedures and Functions anonymous : 15.3. The Anonymous PL/SQL Block constructing : 15.2.1. Sequence of Section Construction cursors in : 15.3.5.4. Cursor scope
labels for : 15.3.6. Block Labels local : 15.7. Local Modules nested 15.3.4. Nested Blocks 15.3.5.2. Scope and nested blocks parameters of : 15.6. Parameters Booch diagram : 16.2.4. Public and Private Package Elements Boolean datatype : 4.2.4. The Boolean Datatype functions returning : 15.5.4.1. Functions without parameters literals : 2.3.3. Boolean Literals as parameters : 22.7.2. Use Self-Identifying Parameters (Avoid Boolean Values) variables in IF statements : (see IF statements) branching with exceptions : 1.7.5. Structured Code and Other Best Practices BROKEN procedure : C.5.1. The BROKEN procedure built-in collection methods : 19.6. Collection Built-Ins functionality, taking advantage of : 1.7.1. Write as Little Code as Possible package, reference on : C. Built-In Packages
Symbols | A | B | C | D | E | F | G | H | I | J | K | L | M | N | O | P | Q | R | S | T | U | V | W | Y | Z
The Oracle Library Navigation Copyright (c) 2000 O'Reilly & Associates. All rights reserved.
Symbols | A | B | C | D | E | F | G | H | I | J | K | L | M | N | O | P | Q | R | S | T | U | V | W | Y | Z
Index: C calendar : (see date) case consistency of : 22.7.4. Ensure Case Consistency of Parameters INITCAP function : 11.1.4. The INITCAP function LOWER function : 11.1.7. The LOWER function and readability : 3.1.2. Using Case to Aid Readability sensitivity 2.1. The PL/SQL Character Set 2.3. Literals UPPER function : 11.1.16. The UPPER function CAST procedure object views and : 20.1. Example: Using Object Views CAST pseudo-function : 19.5.2. The CAST Pseudo-function casting collections : 19.5.2.1. Casting a named collection CDE : (see Cooperative Development Environment) CEIL (ceiling) function : 13.1.6. The CEIL function century : (see date) CHANGE procedure : C.5.2. The CHANGE procedure CHAR datatype 2.3. Literals 4.2.3.1. The CHAR datatype converting to VARCHAR2 : 4.2.3.2. The VARCHAR2 and VARCHAR datatypes converting to/from ROWID 14.2.1. The CHARTOROWID function 14.2.5. The ROWIDTOCHAR function with LENGTH function : 11.1.6. The LENGTH function character datatypes, in overloaded modules : 15.8.4. Restrictions on Overloading character functions : 11. Character Functions character sets : 14.2.2. The CONVERT function characters adding to strings : 11.1.11. The RPAD function converting to numbers, package for : 17.8.7. Recursive Processing in a SQL Statement
datatypes for : 4.2.3. Character Datatypes extracting from strings : 11.1.14. The SUBSTR function NLS datatypes for : 4.2.6. NLS Character Datatypes replacing in strings 11.1.10. The REPLACE function 11.1.15. The TRANSLATE function stripping from strings 11.1.12. The RTRIM function 11.1.9. The LTRIM function word wrap : 11.2.2. Implementing Word Wrap for Long Text CHARSETFORM property : 21.4.3.4. CHARSETID and CHARSETFORM properties CHARSETID property : 21.4.3.4. CHARSETID and CHARSETFORM properties CHARTOROWID function : 14.2.1. The CHARTOROWID function checking for NULL values : 4.3.2. Checking for NULL Values child block : (see nested blocks) child records : (see records) CHR function : 11.1.2. The CHR function class instances : 18.1.4.2. Classification classes : (see object types) classification of objects : 18.1.4.2. Classification clearing tables : 10.7. Clearing the PL/SQL Table client-side SQL : 25.3.3. Avoid Client-Side SQL CLOB datatype 1.4.7.6. Large object support 4.2.7.3. The CLOB datatype EMPTY_CLOB function : 13.2.3. The EMPTY_CLOB function clock : (see time) CLOSE statement (see also cursors) 6.2.2. Cursor Operations 6.8. Closing Cursors CLOSE_CURSOR procedure : C.14.3. The CLOSE_CURSOR procedure CLOSE_DATABASE_LINK procedure : C.12.1. The CLOSE_DATABASE_LINK procedure closing cursors : 6.8. Closing Cursors code compiled, tuning access to : 25.2. Tuning Access to Compiled Code critical, pinning into SGA : 25.2.2. Pin Critical Code into the SGA encrypting : 23.7. Encrypting Stored Code memory-based architecture : 23.1.3. Memory-Based Architecture of PL/SQL Code procedural, avoiding : 25.3.5. Avoid Procedural Code When Possible repetetive : (see redundancy) reusing : 1.7.1. Write as Little Code as Possible
shared, executing : 23.1. Executing Stored Code structuring of : 1.7.5. Structured Code and Other Best Practices style of : 1.7.4. Standardize Your PL/SQL Development Environment testing : 24.2.5. Change and Test One Area of Code at a Time coding : 1.2. The Concept of Programming in Oracle Applications analyzing size of : 23.6.3. Analyzing the Size of PL/SQL Code anticipating errors : (see exceptions) avoiding repetitive : 22.3. Take Full Advantage of Local Modularization comments in : (see comments) considering parameter case : 22.7.4. Ensure Case Consistency of Parameters creating independent modules : 22.5. Create Independent Modules cross-referencing source code : 23.6.5. Cross-Referencing Source Code in databases : 23. Managing Code in the Database documenting : 24.2.6. Document and Back Up Your Efforts errors : (see errors; exceptions) finding strings in : 23.6.4. Displaying and Searching Source Code hints for effective 1.5. Advice for Oracle Programmers 3. Effective Coding Style 4.2.8.3. Drawbacks of implicit conversions 22. Code Design Tips commenting : 3.6. Using Comments Effectively exception handling : 8.10. RAISE Nothing but Exceptions IF statements : 5.1.4. Nested IF Statements loops : 7.7. Tips for PL/SQL Loops nested records : 9.7.1. Example of Nested Records parameters : 22.7. Tips for Parameter Design records : 9.1.3.3. Leaner, cleaner code increasing readability of code : 5.2.2.1. Improving the readability of your program layout of : 3.1. Fundamentals of Effective Layout recursive processing : 17.8.7. Recursive Processing in a SQL Statement removing unused variables : 4.7.6. Remove Unused Variables from Programs sequential processing : 17.8.6. Sequential Processing Against a Column's Value simplifying logic with variables : 4.7.9. Use Variables to Hide Complex Logic testing programs : 2.5.2. Multiline Comment Syntax collections adding/removing elements from : 19.4.3. Adding and Removing Elements built-in methods for : 19.6. Collection Built-Ins casting : 19.5.2.1. Casting a named collection choosing which kind to use : 19.9. Which Collection Type Should I Use? collection variables
19.2.2.1. Collection variables 19.4.1. Initializing Collection Variables comparing : 19.4.4. Comparing Collections creating : 19.2. Creating the New Collections data dictionary entries for : 19.8.2. Data Dictionary declaring as datatype : 19.2.2. Collections in PL/SQL index-by tables : (see index-by tables) nested tables : (see nested tables) passing arguments of : 19.8.3. Call by Reference or Call by Value PL/SQL-to-server integration example : 19.7. Example: PL/SQL-to-Server Integration privileges : 19.8.1. Privileges pseudo-functions : 19.5. Collection Pseudo-Functions types of : 19.1. Types of Collections VARRAYs : (see VARRAYs) COLUMN_VALUE procedure : C.14.4. The COLUMN_VALUE procedure columns (see also records) 9.1.1. Different Types of Records abbreviations for : 3.2. Formatting SQL Statements aliases for 3.2. Formatting SQL Statements 6.7. Column Aliases in Cursors 9.3.2. Setting the Record's Column Names BFILE, initializing : 13.2.1. The BFILENAME function choosing for cursor-based record : 9.3.1. Choosing Columns for a Cursor Record collections as : 19.2.1.1. Collection as a "column" in a conventional table collections as datatypes for : 19.1. Types of Collections names for : 1.7.5. Structured Code and Other Best Practices naming procedure : 17.6. Column/Function Name Precedence objects for : 18.1.2. Some Simple Examples VALUE operator with : 18.4.2.3. VALUE partial values of : 17.8.5. GROUP BY Partial Column Values represented by variables : 4.7.7. Use %TYPE When a Variable Represents a Column sequential processing against value : 17.8.6. Sequential Processing Against a Column's Value synchronization with : 4.5.1.1. Synchronization with database columns where OIDS are stored : 18.4.2.1. Object identifiers (OIDs) COMMA_TO_TABLE procedure : C.16.2. The COMMA_TO_TABLE procedure COMMENT keyword : 6.1.1. The COMMIT Statement comments : 2.5. Comments associated with transactions : 6.1.1. The COMMIT Statement describing parameters : 22.7.1. Document All Parameters and Their Functions
encrypted code and : 23.7.3. Impact of Encrypting Code symbols for : 2.1. The PL/SQL Character Set using effectively : 3.6. Using Comments Effectively COMMIT procedure (see also DBMS_PIPE) C.10. DBMS_PIPE C.15.4. The COMMIT procedure COMMIT statement 6.1.1. The COMMIT Statement 6.11.1. Releasing Locks with COMMIT COMMIT_COMMENT procedure : C.15.5. The COMMIT_COMMENT procedure COMMIT_FORCE procedure : C.15.6. The COMMIT_FORCE procedure Companion Utilities Guide : A. What's on the Companion Disk? COMPARE function : C.6.2. The COMPARE function comparing collections : 19.4.4. Comparing Collections with NULL : 4.3. NULLs in PL/SQL objects : 18.3.6. Comparing Objects records : 9.1.6. Comparing Two Records strings 4.2.3.2. The VARCHAR2 and VARCHAR datatypes 11.1.13. The SOUNDEX function comparison methods : 18.3.1. About Object Types compilation automatic : 23.3.1. Interdependencies of Stored Objects errors, viewing : 23.5.4. Viewing Compilation Errors in SQL*Plus manual : 23.3.1. Interdependencies of Stored Objects of modules : 4.5.2. Anchoring at Compile Time COMPILE_SCHEMA procedure : C.16.3. The COMPILE_SCHEMA procedure compiler constructs : (see pragmas) compiling forced : 20.7.3. Forcing Compilation package specifications : 1.7.3. Center All Development Around Packages compound symbols : (see symbols) CONCAT function 4.3.3. Function Results with NULL Arguments 11.1.3. The CONCAT function concatenation (||) operator 4.3.3. Function Results with NULL Arguments 11.1.3. The CONCAT function concatenation, string 4.3.3. Function Results with NULL Arguments
11.1.3. The CONCAT function conditional control structures : 5. Conditional and Sequential Control formatting : 3.3. Formatting Control Structures conditional loops : (see loops) constants : (see literals; named constants; variables) constrained datatypes 4.4.1. Constrained Declarations 4.6. Programmer-Defined Subtypes 4.6.3. Emulating Constrained Subtypes constructor methods 18.2.2.1. PL/SQL usage 18.3.1. About Object Types 18.4.1.1. Constructors constructors, initializing collections : 19.4.1.1. Initializing with a constructor control structures, iterative : (see loops) conventions, naming : 4.7.1. Establish Clear Variable Naming Conventions conversion and format models : 14.1. Conversion Formats functions for : 14. Conversion Functions implicit : 14. Conversion Functions CONVERT function C.7.2. The CONVERT function 14.2.2. The CONVERT function converting between datatypes : 4.2.8. Conversion Between Datatypes datatypes external procedures and : 21.4.1. Datatype Conversion performance and : 25.4.7. Avoid Type Conversions When Possible explicitly versus implicitly : 4.2.8.1. Explicit data conversions to/from hexadecimal : 14.2.3. The HEXTORAW function to row numbers : 10.5.1. Automatic Conversion of Row Number Expressions triggers to procedures : 25.3.7. Keep Database Triggers Small variables to named constants : 4.7.5. Convert Variables into Named Constants Cooperative Development Environment (CDE) : 1.2. The Concept of Programming in Oracle Applications COPY procedure : C.6.3. The COPY procedure correlated subqueries : 17.8.3. Replacing Correlated Subqueries correlation variables : 18.4.2.2. REFs COS function : 13.1.7. The COS function COSH function : 13.1.8. The COSH function COUNT function 10.8.2.1. The COUNT function
19.6.1. COUNT counted loops : (see numeric FOR loops) counting substring occurrences : 11.2.4. Counting Substring Occurrences in Strings CREATE command : 23.5.1. Creating Stored Objects CREATE DIRECTORY command : 4.2.7.7. Working with BFILEs CREATE LIBRARY command 21.2.3. Step 3: Issue CREATE LIBRARY Statement 21.3.1. CREATE LIBRARY: Creating the External Procedure Library CREATE OR REPLACE command : 23.5.3. Changing Stored Objects CREATE TYPE BODY statement : 18.3.3. CREATE TYPE BODY: Creating a Body CREATE TYPE command : 19.2. Creating the New Collections CREATE TYPE ... AS OBJECT statement : 19.2.1.2. Collection as an attribute of an object type CREATE TYPE statement : 18.3.2. CREATE TYPE and DROP TYPE: Creating and Dropping Types CREATE VIEW statement : 20.3.1. CREATE VIEW: Creating an Object View CREATE_QUEUE procedure : C.3.2.3. The CREATE_QUEUE procedure CREATE_QUEUE_TABLE procedure : C.3.2.1. The CREATE_QUEUE_TABLE procedure cursor FOR loops : 7.4. The Cursor FOR Loop formatting : 3.3.2. Formatting Loops premature termination of : 7.7.2.1. Premature FOR loop termination records in : 7.4.2. The Cursor FOR Loop Record scope of : 7.6.2.1. Scope in FOR loops CURSOR statement : 6.4. Declaring Cursors cursor variables aliases for : 6.12.6.3. Cursor variable aliases as arguments : 6.12.7. Passing Cursor Variables as Arguments attributes of : 6.12.2. Similarities to Static Cursors scope of : 6.12.6.4. Scope of cursor object CURSOR_ALREADY_OPEN exception : 8.3.1. Named System Exceptions cursors : 6.2. Cursors in PL/SQL attributes of : 6.9. Cursor Attributes for cursor variables : 6.12.2. Similarities to Static Cursors %FOUND : 6.9.1. The %FOUND Attribute %ISOPEN 6.5. Opening Cursors 6.9.4. The %ISOPEN Attribute %NOTFOUND 6.6.2. Fetching Past the Last Row 6.9.2. The %NOTFOUND Attribute %ROWCOUNT : 6.9.3. The %ROWCOUNT Attribute closing : 6.8. Closing Cursors
column aliases in : 6.7. Column Aliases in Cursors corresponding to records : 9.1.4. Guidelines for Using Records cursor variables 1.4.5.2. Cursor variables 6.2.1. Types of Cursors 6.12. Cursor Variables restrictions on : 6.12.8. Cursor Variable Restrictions database access based on : 1.4.3.8. Cursor-based access to the database declaring : 6.4. Declaring Cursors in packages : 16.3.2. Declaring Package Cursors examples of using : 6.13. Working with Cursors explicit 1.7.4. Standardize Your PL/SQL Development Environment 6.2.1. Types of Cursors 6.3.3. Explicit Cursors FETCH INTO from : 9.5.3. FETCH INTO from an Explicit Cursor explicit, fetching from : 1.7.2. Synchronize Program and Data Structures fetching from : 6.6. Fetching from Cursors FOR loops for 1.6.4. The cursor FOR loop 1.7.1. Write as Little Code as Possible group functions in : 6.13.1.1. Inefficiency of group functions in cursors identifier precedence : 6.4.3. Identifier Precedence in a Cursor implicit 1.7.4. Standardize Your PL/SQL Development Environment 6.2.1. Types of Cursors 6.3.1. Implicit Cursors 6.9. Cursor Attributes 6.9.5. Implicit SQL Cursor Attributes SELECT INTO from : 9.5.2. SELECT INTO from an Implicit Cursor naming : 6.4.1. The Cursor Name opening 6.2.2. Cursor Operations 6.5. Opening Cursors 6.10.2. Opening Cursors with Parameters parameters of : 6.10. Cursor Parameters records based on : 9.3. Cursor-Based Records RETURN statement : 6.4.4. The Cursor RETURN Clause scope of : 15.3.5.4. Cursor scope SELECT FOR UPDATE statement : 6.11. SELECT FOR UPDATE in Cursors specifying in packages : 16.3. The Package Specification static : 6.2.1. Types of Cursors
variables in : 6.4.2. PL/SQL Variables in a Cursor
Symbols | A | B | C | D | E | F | G | H | I | J | K | L | M | N | O | P | Q | R | S | T | U | V | W | Y | Z
The Oracle Library Navigation Copyright (c) 2000 O'Reilly & Associates. All rights reserved.
Symbols | A | B | C | D | E | F | G | H | I | J | K | L | M | N | O | P | Q | R | S | T | U | V | W | Y | Z
Index: D dangling REFs : 18.2.3. Adding Complex Data Structures data abstract datatypes : (see ADTs) abstraction : 9.1.3.1. Data abstraction combining scalars and aggregates : 17.8.2. Combining Scalar and Aggregate Values denormalizing with nested records : 9.7.4. Denormalizing Program Data with Nested Records errors by implicit cursors : 6.3.2.2. Vulnerability to data errors from packages, performance and : 25.4.4. Use Package Data to Avoid Passing "Bulky" Parameter Values global (see also global variables) 16.1.4. Object Persistence 16.5.2. Global Within a Single Oracle Session 22.5.4. Avoid Global Variables and Data Structures private : 16.5.4. Global Private Data public : 16.5.3. Global Public Data object model and : 18.1.5.4. Combining data with behavior package : 16.5. Package Data program : (see variables) records : (see records) tuning access to : 25.3. Tuning Access to Your Data verifying : 24.2.7. Test All Assumptions data abstraction : 18.1.5.3. Abstraction data dictionary external procedure entries : 21.6.1. Data Dictionary for managing collections : 19.8.2. Data Dictionary object types entries : 18.6.1. Data Dictionary object views entries : 20.7.1. Data Dictionary data structures, synchronizing : 1.7.2. Synchronize Program and Data Structures databases administration of : About the Contents communication between sessions : C.10. DBMS_PIPE
cursor-based access to : 1.4.3.8. Cursor-based access to the database events, receiving notification of : C.2. DBMS_ALERT locking records : 6.11. SELECT FOR UPDATE in Cursors managing code in : 23. Managing Code in the Database structure for objects : 18.2.2.2. DDL usage synchroniztion with columns : 4.5.1.1. Synchronization with database columns triggers : (see triggers) tuning of : About the Contents datatypes : 4.2. Scalar Datatypes abstract (see abstract datatypes) (see ADTs) anchored 1.6.1. Anchored declarations 4.5. Anchored Declarations collections as : 19.2.2. Collections in PL/SQL comverting external procedures and : 21.4.1. Datatype Conversion constrained/unconstrained : 4.4.1. Constrained Declarations converting performance and : 25.4.7. Avoid Type Conversions When Possible converting between 4.2.8. Conversion Between Datatypes 14. Conversion Functions declaring in tables 10.4.1. Defining the Table TYPE 10.8.1. PL/SQL Tables of Records external : 21.4.1. Datatype Conversion for LOB variables : 1.4.7.6. Large object support for LOBs : 4.2.7. LOB Datatypes object : (see object types) for overloaded modules : 15.8.4. Restrictions on Overloading PL/SQL Version 2.0 : B.2.1. No Server-Side PL/SQL Datatypes programmer-defined : (see subtypes) standardizing with %TYPE : 4.7.8. Use %TYPE to Standardize Nondatabase Declarations of stored functions parameters : 17.3. Requirements for Stored Functions in SQL date 12. Date Functions 14.3.5. Building a Date Manager changing millenia : 14.3.3. RR: Changing Millenia converting strings to/from 14.1. Conversion Formats
14.2.6. The TO_CHAR function (date conversion) 14.2.8. The TO_DATE function DATE datatype : 4.2.5. The Date-Time Datatype range : 14.3.4. Using TO_CHAR to Create a Date Range system : 12.1.7. The SYSDATE function DATE datatype : 12. Date Functions days : (see date) DB2 data source : 4.2.3.1. The CHAR datatype dbgextp.sql script : 21.6.2. Rules and Warnings About External Procedures DBMS_AQ package : C.3. Oracle AQ, the Advanced Queueing Facility DBMS_AQADM package : C.3.2. DBMS_AQADM (PL/SQL 8 Only) DBMS_DDL package : C.4. DBMS_DDL DBMS_DESCRIBE package pinning in SGA shared pool : 25.2.2.1. Candidates for pinning in the shared pool DBMS_JOB package C.5. DBMS_ JOB 1.4.5.3. Job scheduling with DBMS_ JOB DBMS_LOB package : C.6. DBMS_LOB (PL/SQL8 Only) DBMS_LOCK package : C.7. DBMS_LOCK DBMS_MAIL package : C.8. DBMS_MAIL DBMS_OUTPUT package C.9. DBMS_OUTPUT 10.9.3. Displaying a PL/SQL Table 26.5. Quick-and-Dirty Tracing pinning in SGA shared pool : 25.2.2.1. Candidates for pinning in the shared pool DBMS_PIPE package : C.10. DBMS_PIPE DBMS_ROWID package : C.11. DBMS_ROWID (PL/SQL8 Only) DBMS_SESSION package : C.12. DBMS_SESSION DBMS_SHARED_POOL package : 25.2.2. Pin Critical Code into the SGA DBMS_SNAPSHOT package : C.13. DBMS_SNAPSHOT DBMS_SQL package : C.14. DBMS_SQL batch processing : 25.3.4. Take Advantage of DBMS_SQL Batch Processing DBMS_STANDARD package pinning in SGA shared pool : 25.2.2.1. Candidates for pinning in the shared pool DBMS_TRANSACTION package : C.15. DBMS_TRANSACTION DBMS_UTILITY package : C.16. DBMS_UTILITY GET_TIME Function : 25.1.1. Use the DBMS_UTILITY.GET_TIME Function pinning in SGA shared pool : 25.2.2.1. Candidates for pinning in the shared pool DDL (Data Definition Language) DBMS_DDL package for : C.4. DBMS_DDL object privileges and : 18.3.7.1. DDL statements : 1.4.4.2. Support for DDL and dynamic SQL
debugging 2.5.2. Multiline Comment Syntax 24. Debugging PL/SQL external procedures : 21.6.2. Rules and Warnings About External Procedures finding code by line number : 23.6.6. Finding the Code for a Line Number messages about, in packages : 24.2.9. Build Debugging Messages into Your Packages strategies for : 24.2. Debugging Tips and Strategies tracing PL/SQL execution : 26. Tracing PL/SQL Execution DEC subtype : 4.2.2. Numeric Subtypes decimal datatypes 4.2.1.2. Decimal numeric datatypes 4.2.2. Numeric Subtypes DECIMAL subtype : 4.2.2. Numeric Subtypes declarations anchored 1.6.1. Anchored declarations 4.5. Anchored Declarations commenting : 3.6.5. Comment Declaration Statements FOR loop indexes : 1.7.5. Structured Code and Other Best Practices formatting : 3.1.5. Formatting Your Declarations forward : 15.9. Forward Declarations in packages 16.3. The Package Specification 16.4.1. Declare in Specification or Body of record TYPEs : 9.4.1. Declaring Programmer-Defined Record TYPEs of records 9.2.1. Declaring Records with the %ROWTYPE Attribute 9.4.2. Declaring the Record subtype : 4.6.1. Declaring Subtypes of tables : 10.4. Declaring a PL/SQL Table unconstrained : 15.6.1. Defining the Parameters variable : 4.4. Variable Declarations declaring collection datatypes : 19.3. Syntax for Declaring Collection Datatypes cursor variables : 6.12.3. Declaring REF CURSOR Types and Cursor Variables cursors : 6.4. Declaring Cursors exceptions raised in declarations : 8.5.3. Exceptions Raised in a Declaration parameters : 21.4.4. Correct Declaration of Properties DECODE function in MAKE_REF funfction : 20.4.2.3. Working around the ORA-22972 problem DECODE function, replacing with IF : 17.8.4. Replacing DECODEs with IF Statements default
constructor method : 18.3.1. About Object Types parameter values B.2.4. No Default Parameter Values 15.6.5. Default Values 22.7.5. Default Values and Remote Procedure Calls records : 9.6.2. Record Initialization values for variables : 4.4.3. Default Values DEFAULT keyword : 4.4.3. Default Values DEFINE_ARRAY program : 25.3.4. Take Advantage of DBMS_SQL Batch Processing DEFINE_COLUMN procedure : C.14.5. The DEFINE_COLUMN procedure definer rights model : 18.3.7.3. Rights model DELETE procedure : 10.8.2.2. The DELETE procedure removing collection elements : 19.4.3.2. Removing elements using DELETE THE function with : 19.5.1. The THE Pseudo-function DELETE statement (see also DML statements) 10.3. PL/SQL Tables and DML Statements WHERE CURRENT OF clause : 6.11.2. The WHERE CURRENT OF Clause deleting collection elements : 19.4.3. Adding and Removing Elements table rows : 10.8.2.2. The DELETE procedure deleting tables : 10.7. Clearing the PL/SQL Table denormalizing program data : 9.7.4. Denormalizing Program Data with Nested Records dependency management : 23.3. Module Validation and Dependency Management DEQUEUE procedure : C.3.1.2. The DEQUEUE procedure DEREF function, virtual REFs and : 20.4.2.4. DEREF: Interpreting a virtual REF DEREF operator : 18.4.2.4. DEREF desc command (SQL*Plus), objects and : 18.6.2. SQL*Plus "Describe" Command Developer/2000 : 18.5.5. Implications for Developer/2000 development best practices for : 1.7. Best Practices for PL/SQL Excellence packages for : 1.7.3. Center All Development Around Packages standarizing environment for : 1.7.4. Standardize Your PL/SQL Development Environment digits, number of : (see precision) direct field assignment 9.5. Assigning Values to and from Records 10.6.1. Direct Assignment directories, creating : 4.2.7.7. Working with BFILEs directory aliases, BFILENAME functions and : 13.2.1. The BFILENAME function DISABLE procedure : C.9.1. The DISABLE procedure disk accompanying this book : A. What's on the Companion Disk? disk space : (see memory)
DMBS_ALERT package : C.2. DBMS_ALERT DML encapsulating in object views : 20.2. INSTEAD OF Triggers encapsulating in packages : 18.5.4. Approach 4: Use an Object and a PL/SQL Container Package object privileges and : 18.3.7.2. DML DML statements : 1.4.4.2. Support for DDL and dynamic SQL and tables : 10.3. PL/SQL Tables and DML Statements "do nothing" statement : (see NULL statements) documentation with encrypted code : 23.7.3. Impact of Encrypting Code of parameters : 22.7.1. Document All Parameters and Their Functions of programming process : 24.2.6. Document and Back Up Your Efforts documentation, inline : (see comments) dot notation B.2.2. No Direct Stored Package Variable References 9.1.2. Accessing Record-Based Data 18.3.4. Dot Notation with nested records : 9.7.2. Dot Notation with Nested Records DOUBLE PRECISION subtype : 4.2.2. Numeric Subtypes DROP command 20.3.2. DROP: Dropping Views and Triggers 21.3.3. DROP: Dropping Libraries 23.5.3. Changing Stored Objects DROP TYPE statement : 18.3.2. CREATE TYPE and DROP TYPE: Creating and Dropping Types DROP_QUEUE procdure : C.3.2.5. The DROP_QUEUE procedure DROP_QUEUE_TABLE procedure : C.3.2.2. The DROP_QUEUE_TABLE procedure DROP_SNAPSHOT procedure : C.13.1. The DROP_SNAPSHOT procedure dropping libraries : 21.3.3. DROP: Dropping Libraries triggers : 20.3.2. DROP: Dropping Views and Triggers views : 20.3.2. DROP: Dropping Views and Triggers dummy programs : 5.2.2.3. Supporting top-down design of modules DUMP function : 13.3.1. The DUMP function DUP_VAL_ON_INDEX exception : 8.3.1. Named System Exceptions dynamic linking : 21.1.2. Architecture dynamic SQL C.14. DBMS_SQL 1.4.4.2. Support for DDL and dynamic SQL 6.2.1. Types of Cursors
Symbols | A | B | C | D | E | F | G | H | I | J | K | L | M | N | O | P | Q | R | S | T | U | V | W | Y | Z
The Oracle Library Navigation Copyright (c) 2000 O'Reilly & Associates. All rights reserved.
Symbols | A | B | C | D | E | F | G | H | I | J | K | L | M | N | O | P | Q | R | S | T | U | V | W | Y | Z
Index: E editing table rows : 10.5. Referencing and Modifying PL/SQL Table Rows ELSE keyword : (see IF statements) ELSIF keyword : (see IF statements) email, sending with external procedures : 21.7.2. Example: Sending Email embedded PL/SQL : (see stored functions, PL/SQL) embedding trace calls in programs : 26.5. Quick-and-Dirty Tracing embedding quotation marks : 2.3.1. Embedding Single Quotes Inside a String EMPTY_BLOB function : 13.2.2. The EMPTY_BLOB function EMPTY_CLOB function : 13.2.3. The EMPTY_CLOB function ENABLE procedure : C.9.2. The ENABLE procedure encapsulating calculations : 17.8.1. Encapsulating Calculations encapsulation : 18.1.5.2. Encapsulation of data structure access : 1.7.2. Synchronize Program and Data Structures on object views : 20.2.1.1. The "don't use" argument of persistent objects : 18.2.2.2. DDL usage enclosed block : (see nested blocks) encrypting code : 23.7. Encrypting Stored Code END IF : (see IF statements) END label 15.4.4. The END Label 15.5.3. The END Label END LOOP keywords : (see loops) ENQUEUE procedure : C.3.1.1. The ENQUEUE procedure Enterprise Manager/Performance Pack product : 25.1. Analyzing Program Performance entity-relationship (ER) model : 18.1.4.3. Inheritance environment, user : 13.3.9. The USERENV function equality, testing objects for : 18.3.6.2. Equality comparisons ER (entity-relationship) model : 18.1.4.3. Inheritance ERASE procedure : C.6.4. The ERASE procedure erasing : (see deleting) error messages "attribute expression within SQL expression" : 6.9. Cursor Attributes
"cursor already open" 6.5. Opening Cursors 6.9.4. The %ISOPEN Attribute "expression is inappropriate" : 6.4.1. The Cursor Name "fetch out of sequence" : 6.11.1. Releasing Locks with COMMIT "function returned without value" : 15.5.8.3. No RETURN is executed "maximum open cursors exceeded" : 6.8.1. Maximum Number of Cursors "wrong number of values in the INTO list" : 6.6.1. Matching Column List with INTO Clause SQLERRM function : 13.3.6. The SQLERRM function "illegal GOTO statement" : 5.2.1.2. Target labels and scope of GOTO errors (see also exceptions) 8. Exception Handlers caused by implicit cursors : 6.3.2.2. Vulnerability to data errors codes for : (see SQLCODE) communication from server to client : 8.7. Client-Server Error Communication handling : 1.4.3.9. Error handling viewing in SQL*Plus : 23.5.4. Viewing Compilation Errors in SQL*Plus violation of RESTRICT_REFERENCES pragma : 17.5.1.1. Pragma violation errors event level, tracing : 26.1.2. Turning On the Trace EXCEPTION keyword 8.3.2. Named Programmer-Defined Exceptions 8.6. Handling Exceptions EXCEPTION_INIT pragma : 8.3.3.1. The EXCEPTION_INIT pragma exceptions 1.4.3.9. Error handling 8. Exception Handlers for branching logic : 1.7.5. Structured Code and Other Best Practices continuing once handled : 8.6.4. Continuing Past Exceptions CURSOR_ALREADY_OPEN : 8.3.1. Named System Exceptions declaring in packages : 16.3. The Package Specification DUP_VAL_ON_INDEX : 8.3.1. Named System Exceptions exception section of code : 8.2. The Exception Section formatting handlers of : 3.3.3. Formatting Exception Handlers handler development : 1.7.4. Standardize Your PL/SQL Development Environment handles for : 8.6. Handling Exceptions handling : 22.2.3. Avoid Exception Handlers for Normal Program Exits like IF statement : 8.9. Exception Handler as IF Statement multiple : 8.6.1. Combining Multiple Exceptions in a Single Handler structure for : 8.4. Determining Exception-Handling Behavior tips for : 8.10. RAISE Nothing but Exceptions INVALID_CURSOR : 8.3.1. Named System Exceptions
INVALID_NUMBER : 8.3.1. Named System Exceptions LOGIN_DENIED : 8.3.1. Named System Exceptions NO_DATA_FOUND 8.3.1. Named System Exceptions 8.8. NO_DATA_FOUND: Multipurpose Exception NOT_LOGGED_ON : 8.3.1. Named System Exceptions nullifying effect of raised : 5.2.2.2. Nullifying the effect of a raised exception overlapping names of : 8.4.1.3. Overlapping exception names as package : 16.3.1.1. A package of exceptions PROGRAM_ERROR : 8.3.1. Named System Exceptions programmer-defined 8.3.2. Named Programmer-Defined Exceptions 8.3.4. Unnamed Programmer-Defined Exceptions propagation of : 8.4.2. Propagation of an Exception raised within handler : 8.5.4. Exceptions Raised in an Exception Handler raising 8.5. Raising an Exception 8.10. RAISE Nothing but Exceptions ROWTYPE_MISMATCH : 6.12.5.2. Handling the ROWTYPE_MISMATCH exception scope of : 8.4.1. Scope of an Exception SQLCODE function : 13.3.5. The SQLCODE function STORAGE_ERROR : 8.3.1. Named System Exceptions system : 8.3.1. Named System Exceptions TIMEOUT_ON_RESOURCE : 8.3.1. Named System Exceptions TOO_MANY_ROWS : 8.3.1. Named System Exceptions TRANSACTION_BACKED_OUT : 8.3.1. Named System Exceptions trapping invalid arguments : 22.2.4.1. Trap invalid argument values types of : 8.3. Types of Exceptions VALUE_ERROR : 8.3.1. Named System Exceptions ZERO_DIVIDE : 8.3.1. Named System Exceptions execute authority 1.3.2. Improved Execution Authority and Transaction Integrity with PL/SQL 23.2. Transaction Integrity and Execute Authority collections and : 19.8.1. Privileges packages and : 23.2.1. Execute Authority on Stored Objects sharing code and : 23.1.4. Key Concepts for Program Execution on stored objects : 23.2.1. Execute Authority on Stored Objects EXECUTE command C.14.6. The EXECUTE function 23.1.1. Executing Procedures 23.5.3. Changing Stored Objects EXECUTE_AND_FETCH command : C.14.7. The EXECUTE_AND_FETCH function
execution, shared code : 23.1. Executing Stored Code EXISTS function 10.8.2.3. The EXISTS function 19.6.3. EXISTS(i) EXIT statement (see also loops) 7.2.1. Terminating a Simple Loop: EXIT and EXIT WHEN 7.7.2.2. EXIT and EXIT WHEN statements EXIT WHEN statement 7.2.1. Terminating a Simple Loop: EXIT and EXIT WHEN 7.2.2. Emulating a REPEAT UNTIL Loop 7.7.2.2. EXIT and EXIT WHEN statements with loop labels : 7.6.1.2. Loop termination using labels EXIT WHEN statement (see also loops) 7.2.1. Terminating a Simple Loop: EXIT and EXIT WHEN exiting loops : 1.7.5. Structured Code and Other Best Practices EXP function : 13.1.9. The EXP function EXPLAIN PLAN statement : 25.1. Analyzing Program Performance explicit conversion functions : 14. Conversion Functions cursors (see also cursors) 1.7.4. Standardize Your PL/SQL Development Environment 6.2.1. Types of Cursors 6.3.3. Explicit Cursors fetching from 9.5.3. FETCH INTO from an Explicit Cursor 1.7.2. Synchronize Program and Data Structures explicit datatype conversion : 4.2.8.1. Explicit data conversions exponents : 13.1.14. The POWER function EXTEND procedure : 19.6.4. EXTEND [ (n [,i] ) ] adding collection elements : 19.4.3.1. Adding elements using EXTEND extensions, filename : (see filenames) external LOBs : 1.4.7.6. Large object support procedures : 1.4.7.5. External procedures EXTERNAL clause : 21.3.2. EXTERNAL: Creating the PL/SQL Body external datatypes : 21.4.1. Datatype Conversion external procedures : 21. External Procedures architecture of : 21.1.2. Architecture creating : 21.2. Steps in Creating an External Procedure
data dictionary entries : 21.6.1. Data Dictionary debugging : 21.6.2. Rules and Warnings About External Procedures examples : 21.7. Examples listeners for : 21.2.1. Step 1: Set Up the Listener mapping parameters : 21.4. Mapping Parameters OCI routines for : 21.5. OCI Service Routines syntax : 21.3. Syntax for External Procedures warnings about : 21.6.2. Rules and Warnings About External Procedures EXTERNAL_PROCEDURE_LISTENER listener : 21.2.1. Step 1: Set Up the Listener
Symbols | A | B | C | D | E | F | G | H | I | J | K | L | M | N | O | P | Q | R | S | T | U | V | W | Y | Z
The Oracle Library Navigation Copyright (c) 2000 O'Reilly & Associates. All rights reserved.
Symbols | A | B | C | D | E | F | G | H | I | J | K | L | M | N | O | P | Q | R | S | T | U | V | W | Y | Z
Index: F FALSE : (see Boolean literals) FCLOSE procedure : C.17.1.1. The FCLOSE procedure FCLOSE_ALL procedure : C.17.1.2. The FCLOSE_ALL procedure FETCH clause, assigning objects : 18.4.1.3. Assignment via FETCH (with SELECT) FETCH INTO statement : 9.5.3. FETCH INTO from an Explicit Cursor FETCH statement (see also cursors) 4.2.3.2. The VARCHAR2 and VARCHAR datatypes 6.2.2. Cursor Operations 6.6. Fetching from Cursors with cursor variables : 6.12.5. Fetching from Cursor Variables initializing collections : 19.4.1.3. Initializing implicitly via fetch FETCH_ROW function : C.14.8. The FETCH_ROWS function fetching from cursor variables : 6.12.5. Fetching from Cursor Variables from cursors : 6.6. Fetching from Cursors checking status of FETCH : 6.9.1. The %FOUND Attribute to cursors, multiple times : 6.13.1.2. Using multiple fetches more efficiently FFLUSH procedure : C.17.1.3. The FFLUSH procedure fields, record : (see records) FILECLOSE procedure : C.6.5. The FILECLOSE procedure FILECLOSEALL procedure : C.6.6. The FILECLOSEALL procedure FILEEXISTS function : C.6.7. The FILEEXISTS function FILEGETNAME procedure : C.6.8. The FILEGETNAME procedure FILEISOPEN function : C.6.9. The FILEISOPEN function filenames, encrypted file extensions : 23.7.2. Working with Encrypted Code FILEOPEN procedure : C.6.10. The FILEOPEN procedure files encrypted code, size of : 23.7.3. Impact of Encrypting Code operating system : C.17. UTL_FILE for package specifications : 1.7.3. Center All Development Around Packages filtering trace information : 26.2.3. Filtering Trace Information
FIRST function 10.8.2.4. The FIRST function 19.6.5. FIRST, LAST fixed-point numbers : 4.2.2. Numeric Subtypes FLOAT subtype : 4.2.2. Numeric Subtypes floating-point numbers : 4.2.2. Numeric Subtypes FLOOR function : 13.1.10. The FLOOR function FM (fill mode) modifier : 14.3.1. FM: Suppressing Blanks and Zeros FOPEN function : C.17.1.4. The FOPEN function FOR loops 1.7.1. Write as Little Code as Possible 1.7.5. Structured Code and Other Best Practices cursor 1.6.4. The cursor FOR loop 7.4. The Cursor FOR Loop formatting : 3.3.2. Formatting Loops numeric : 7.3. The Numeric FOR Loop premature termination of : 7.7.2.1. Premature FOR loop termination scope of : 7.6.2.1. Scope in FOR loops FORCE parameter : 18.3.2. CREATE TYPE and DROP TYPE: Creating and Dropping Types forced compilation : 20.7.3. Forcing Compilation foreign key lookups, optimizing in tables : 10.9.5. Optimizing Foreign Key Lookups with PL/SQL Tables object reference versus : 18.2.3. Adding Complex Data Structures validating entry of (example) : 6.13.1. Validating Foreign Key Entry with Cursors formal parameters 15.6.3. Actual and Formal Parameters naming : 22.1.2. Develop Consistent Naming Conventions for Your Formal Parameters format FM and FX modifiers : 14.3.1. FM: Suppressing Blanks and Zeros models : 14.1. Conversion Formats RR model : 14.3.3. RR: Changing Millenia verifying string : 11.2.5. Verifying String Formats with TRANSLATE FORMAT_CALL_STACK function : C.16.4. The FORMAT_CALL_STACK function FORMAT_ERROR_STACK function : C.16.5. The FORMAT_ERROR_STACK function formatting code : 3.1. Fundamentals of Effective Layout forward declarations : 15.9. Forward Declarations forward type definitions : 18.3.5.1. Forward type definitions %FOUND cursor attribute : 6.9.1. The %FOUND Attribute free format trace filtering : 26.3. Free Format Filtering functional abstraction : 18.1.5.3. Abstraction functions
(see also modules) 1.4.3.10. Modular construction 15. Procedures and Functions 15.5. Functions 22.1.1. Make Sure the Module Name Explains the Module 22.2. Build the Most Functional Functions built-in 1.4.3.5. Built-in functions 1.6.2. Built-in functions for characters, strings : 11. Character Functions for collections built-in : 19.6. Collection Built-Ins pseudo-functions : 19.5. Collection Pseudo-Functions collections as return values : 19.2.2.4. Collections as the datatype of a function's return value conversion : 14. Conversion Functions date and time : 12. Date Functions formatting : 3.4. Formatting PL/SQL Blocks group : 6.13.1.1. Inefficiency of group functions in cursors headers of : 15.5.5. Function Header IN OUT and OUT parameters in : 22.2.1.1. Do not use OUT and IN OUT parameters for LOBs : 13.2. LOB Function Descriptions local 15.7. Local Modules 22.3. Take Full Advantage of Local Modularization miscellaneous : 13.3. Miscellaneous Function Descriptions names for : 1.7.5. Structured Code and Other Best Practices naming precedence : 17.6. Column/Function Name Precedence with NULL arguments : 4.3.3. Function Results with NULL Arguments numeric : 13. Numeric, LOB, and Miscellaneous Functions overloaded : 15.8.4. Restrictions on Overloading packaged : 17.5. Calling Packaged Functions in SQL parameters of : 15.6. Parameters without : 15.5.4.1. Functions without parameters PL/SQL, calling in SQL : 25.3.2. Call PL/SQL Functions in SQL to Reduce I/O records as parameters : 9.1.4. Guidelines for Using Records RETURN statement : 15.5.8. The RETURN Statement returned value of : 15.5.2. The RETURN Datatype returning objects : 18.1.2. Some Simple Examples returning tables from : 10.8.1.1. Referencing fields of record elements in PL/SQL tables shared : 23.1.2. Executing Functions tables as parameters for : 10.5.4. Passing PL/SQL Tables as Parameters
template for : 22.2.2.1. Build a function template user information : 13.3.7. The UID function using single RETURN statement : 22.2.2. Use a Single RETURN Statement for Successful Termination FX (format exact) modifier : 14.3.2. FX: Matching Formats Exactly
Symbols | A | B | C | D | E | F | G | H | I | J | K | L | M | N | O | P | Q | R | S | T | U | V | W | Y | Z
The Oracle Library Navigation Copyright (c) 2000 O'Reilly & Associates. All rights reserved.
Symbols | A | B | C | D | E | F | G | H | I | J | K | L | M | N | O | P | Q | R | S | T | U | V | W | Y | Z
Index: G GET_LINE procedure C.9.3. The GET_LINE procedure C.17.1.5. The GET_LINE procedure GET_LINES procedure : C.9.4. The GET_LINES procedure GET_LOG_AGE procedure : C.13.2. The GET_LOG_AGE procedure GET_TIME function : C.16.6. The GET_TIME function GET_TIME Function : 25.1.1. Use the DBMS_UTILITY.GET_TIME Function GETLENGTH function : C.6.11. The GETLENGTH function global data 16.1.4. Object Persistence 16.5.2. Global Within a Single Oracle Session variables : 22.5.4. Avoid Global Variables and Data Structures GOTO statements : 5.2.1. The GOTO Statement inside loop : 7.7.2.4. GOTO statements inside a loop with NULL statements : 5.2.2.4. Using NULL with GOTO to avoid additional statement execution greater than (>=) operator : 2.1. The PL/SQL Character Set GREATEST function : 13.3.2. The GREATEST function GROUP BY clause for partial column values : 17.8.5. GROUP BY Partial Column Values functions in : 17.1. Looking at the Problem group functions in cursors : 6.13.1.1. Inefficiency of group functions in cursors
Symbols | A | B | C | D | E | F | G | H | I | J | K | L | M | N | O | P | Q | R | S | T | U | V | W | Y | Z
The Oracle Library Navigation Copyright (c) 2000 O'Reilly & Associates. All rights reserved.
Symbols | A | B | C | D | E | F | G | H | I | J | K | L | M | N | O | P | Q | R | S | T | U | V | W | Y | Z
Index: H handles, object : (see identifiers) handling exceptions (see exceptions) headers function : 15.5.5. Function Header procedure : 15.4.2. Procedure Header recognizing encrypted code from : 23.7.3. Impact of Encrypting Code help, asking for : 24.2.4. Take Breaks and Ask for Help hexadecimal strings, converting : 14.2.3. The HEXTORAW function HEXTORAW function : 14.2.3. The HEXTORAW function hiding information : (see private elements, package) homogeneity of tables : 10.2. Characteristics of PL/SQL Tables host variables, references to : 25.4.3.2. Minimize references to host variables hour : (see date; time) hyperbolic cosine function : 13.1.8. The COSH function hyperbolic sine function : 13.1.18. The SINH function hyperbolic tangent function : 13.1.21. The TANH function
Symbols | A | B | C | D | E | F | G | H | I | J | K | L | M | N | O | P | Q | R | S | T | U | V | W | Y | Z
The Oracle Library Navigation Copyright (c) 2000 O'Reilly & Associates. All rights reserved.
Symbols | A | B | C | D | E | F | G | H | I | J | K | L | M | N | O | P | Q | R | S | T | U | V | W | Y | Z
Index: I I/O I/O-intensive SQL : 25.3.6. Use PL/SQL to Improve Performance of IO-Intensive SQL reducing by calling PL/SQL in SQL : 25.3.2. Call PL/SQL Functions in SQL to Reduce I/O identifiers (see naming) 2.2. Identifiers 15.3.5. Scope and Visibility precedence in cursors : 6.4.3. Identifier Precedence in a Cursor qualified : 15.3.5.1. Qualified identifiers savepoints : (see savepoints) identity, object : 18.1.4.1. Identity IF statements : 5.1. Conditional Control Statements ELSE keyword : 5.1.2. The IF-THEN-ELSE Combination ELSIF keyword : 5.1.3. The IF-ELSIF Combination ELSIF statement : 1.7.5. Structured Code and Other Best Practices exception handlers as : 8.9. Exception Handler as IF Statement formatting : 3.3.1. Formatting IF Statements nested : 5.1.4. Nested IF Statements replacing DECODE function : 17.8.4. Replacing DECODEs with IF Statements using whitespace in : 3.1.1. Revealing Logical Structure with Indentation implicit conversion : 14. Conversion Functions implicit cursors (see also cursors) 1.7.4. Standardize Your PL/SQL Development Environment 6.2.1. Types of Cursors 6.3.1. Implicit Cursors 6.3.3. Explicit Cursors attributes to 6.9. Cursor Attributes 6.9.5. Implicit SQL Cursor Attributes SELECT INTO from : 9.5.2. SELECT INTO from an Implicit Cursor vulnerability to data errors : 6.3.2.2. Vulnerability to data errors
implicit datatype conversion : 4.2.8.2. Implicit data conversions IN mode : 15.6.2.1. IN mode stored functions and : 17.3. Requirements for Stored Functions in SQL IN OUT parameter : 25.4.3.1. Work with local copies IN OUT parameters 15.6.2.3. The IN OUT mode 22.7.3. Assign Values to All OUT and IN OUT Parameters external procedure mappings : 21.4.1. Datatype Conversion in functions : 22.2.1.1. Do not use OUT and IN OUT parameters INDICATOR property for : 21.4.3.1. INDICATOR property IN OUT parameters, function : 1.7.5. Structured Code and Other Best Practices IN parameters : 25.4.3.1. Work with local copies index, FOR loop : 1.7.5. Structured Code and Other Best Practices index, table (see also tables) 10.2. Characteristics of PL/SQL Tables 10.4.1. Defining the Table TYPE 10.8.1.1. Referencing fields of record elements in PL/SQL tables index-by tables (see also collections) 19.1. Types of Collections 25.4.8. Use Index-By Tables of Records and Objects adding/removing elements of : 19.4.3. Adding and Removing Elements assigning values to elements : 19.4.2. Assigning Values to Elements: Index (Subscript) Considerations initializing : 19.4.1. Initializing Collection Variables indexes, ROWID datatype for : 4.2.3.6. The ROWID datatype INDICATOR property 21.4.1. Datatype Conversion 21.4.3.1. INDICATOR property infinite loops : 7.2. The Simple Loop formatting : 3.3.2. Formatting Loops WHILE loops : 7.5.1. The Infinite WHILE Loop information hiding : 18.1.5.1. Information hiding inheritance 18.1.4.3. Inheritance modifying persistent objects and : 18.5. Modifying Persistent Objects INITCAP function : 11.1.4. The INITCAP function initialization section, package, asserting purity level : 17.5.2. Asserting Purity Level with Package Initialization Section initializing BFILE columns : 13.2.1. The BFILENAME function
collection variables : 19.4.1. Initializing Collection Variables objects : 18.4.1. The Need to Initialize packages : 16.6. Package Initialization records : 9.6.2. Record Initialization inner tables : 19.1. Types of Collections input, considering case of : 22.7.4. Ensure Case Consistency of Parameters INSERT statement (see also DML statements) 4.2.3.2. The VARCHAR2 and VARCHAR datatypes 10.3. PL/SQL Tables and DML Statements THE function with : 19.5.1. The THE Pseudo-function instances of classes : 18.1.4.2. Classification instantiation of objects : 18.2.2.1. PL/SQL usage of program data, storage of : 23.1.4. Key Concepts for Program Execution INSTEAD OF triggers 20.2. INSTEAD OF Triggers compiling : 20.7.3. Forcing Compilation INSTR function C.6.12. The INSTR function 11.1.5. The INSTR function 11.2.4. Counting Substring Occurrences in Strings INSTRB function : 11.1.5. The INSTR function instsrv utility (Windows NT) : 21.2.1. Step 1: Set Up the Listener INTEGER datatype : 25.4.5. Use PLS_INTEGER for All Integer Operations integers 4.2.1.1. Binary integer datatypes INT subtype : 4.2.2. Numeric Subtypes INTEGER subtype : 4.2.2. Numeric Subtypes operations on, performance of : 25.4.5. Use PLS_INTEGER for All Integer Operations PLS_INTEGER datatype : 4.2.1.3. The PLS_INTEGER datatype SMALLINT subtype : 4.2.2. Numeric Subtypes interdependencies, package : 25.2.4. Creating Packages with Minimal Interdependencies internal documentation : (see comments) internal LOBs 1.4.7.6. Large object support BFILE datatype versus : 4.2.7.7. Working with BFILEs internationalization, NLS character datatypes : 4.2.6. NLS Character Datatypes INTERVAL procedure : C.5.3. The INTERVAL procedure INTO clause (see also FETCH statement) 6.6.1. Matching Column List with INTO Clause
9.5.2. SELECT INTO from an Implicit Cursor 9.5.3. FETCH INTO from an Explicit Cursor INVALID_CURSOR exception : 8.3.1. Named System Exceptions INVALID_NUMBER exception : 8.3.1. Named System Exceptions invisible characters : (see whitespace) IS DANGLING predicate : 18.2.3. Adding Complex Data Structures is-a relationship : (see inheritance) IS_OPEN function C.14.9. The IS_OPEN function C.17.1.6. The IS_OPEN function IS_PARALLEL_SERVER function : C.16.7. The IS_PARALLEL_SERVER function IS_ROLE_ENABLED function : C.12.2. The IS_ROLE_ENABLED function isolation levels : 6.1.4. The SET TRANSACTION Statement %ISOPEN cursor attribute : 6.9.4. The %ISOPEN Attribute %ISOPEN cursor attribute : 6.5. Opening Cursors ISUBMIT procedure : C.5.4. The ISUBMIT procedure iterative assignment into rows : 10.6.2. Iterative Assignment control structure : (see loops)
Symbols | A | B | C | D | E | F | G | H | I | J | K | L | M | N | O | P | Q | R | S | T | U | V | W | Y | Z
The Oracle Library Navigation Copyright (c) 2000 O'Reilly & Associates. All rights reserved.
Symbols | A | B | C | D | E | F | G | H | I | J | K | L | M | N | O | P | Q | R | S | T | U | V | W | Y | Z
Index: J job scheduling, with DBMS_JOB C.5. DBMS_ JOB 1.4.5.3. Job scheduling with DBMS_ JOB Julian dates : (see date) justifying text : 11.2.3. Filling Text to Fit a Line
Symbols | A | B | C | D | E | F | G | H | I | J | K | L | M | N | O | P | Q | R | S | T | U | V | W | Y | Z
The Oracle Library Navigation Copyright (c) 2000 O'Reilly & Associates. All rights reserved.
Symbols | A | B | C | D | E | F | G | H | I | J | K | L | M | N | O | P | Q | R | S | T | U | V | W | Y | Z
Index: K KEEP procedure : 25.2.2. Pin Critical Code into the SGA keys, object references versus : 18.2.3. Adding Complex Data Structures
Symbols | A | B | C | D | E | F | G | H | I | J | K | L | M | N | O | P | Q | R | S | T | U | V | W | Y | Z
The Oracle Library Navigation Copyright (c) 2000 O'Reilly & Associates. All rights reserved.
Symbols | A | B | C | D | E | F | G | H | I | J | K | L | M | N | O | P | Q | R | S | T | U | V | W | Y | Z
Index: L label delimeters (>) : 5.2.1. The GOTO Statement labels : 5.2.1. The GOTO Statement delimiters for (>) : 2.1. The PL/SQL Character Set for loops : 7.6.1. Loop Labels and loop scope : 7.6.2.2. Scope with labels labels for blocks : 15.3.6. Block Labels large objects : (see LOBs) LAST function 10.8.2. PL/SQL Table Built-ins 10.8.2.5. The LAST function 19.6.5. FIRST, LAST LAST_DAY function : 12.1.2. The LAST_DAY function LAST_ERROR_POSITION function : C.14.10. The LAST_ERROR_POSITION function LAST_ROW_COUNT function : C.14.11. The LAST_ROW_COUNT function LAST_ROW_ID function : C.14.12. The LAST_ROW_ID function LAST_SQL_FUNCTION_CODE function : C.14.13. The LAST_SQL_FUNCTION_CODE function LEAST function : 13.3.3. The LEAST function LENGTH function : 11.1.6. The LENGTH function LENGTH property 21.4.1. Datatype Conversion 21.4.3.2. LENGTH property less than (<=) operator : 2.1. The PL/SQL Character Set lexical units, PL/SQL : 2.1. The PL/SQL Character Set libraries dropping : 21.3.3. DROP: Dropping Libraries LIMIT function : 19.6.6. LIMIT line breaks : (see whitespace) line number, finding code for : 23.6.6. Finding the Code for a Line Number listener for external procedures : 21.2.1. Step 1: Set Up the Listener literals 2.3. Literals 4.7.4. Use Named Constants to Avoid Hardcoding Values 16.3.1.2. A package of magic values
strings : (see strings) LN function : 13.1.11. The LN function LOBs (large object datatypes) : 1.4.7.6. Large object support functions for : 13.2. LOB Function Descriptions LOBs (large objects) : 4.2.7. LOB Datatypes datatypes for : 4.2.7. LOB Datatypes DMBS_LOB package for : C.6. DBMS_LOB (PL/SQL8 Only) LONG datatypes and : 4.2.7.5. LOBs and LONGs local modules 1.7.1. Write as Little Code as Possible 15.7. Local Modules 22.3. Take Full Advantage of Local Modularization forward declarations of : 15.9. Forward Declarations scope of : 15.7.5. Scope of Local Modules local variables objects for : 18.1.2. Some Simple Examples performance and : 25.4.3. Rely on Local Variables to Improve Performance local variables, normalizing : 4.5.1.2. Normalization of local variables LOCAL_TRANSACTION_ID function : C.15.17. The LOCAL_TRANSACTION_ID function LOCK TABLE statement : 6.1.5. The LOCK TABLE Statement locking records 6.11. SELECT FOR UPDATE in Cursors with DBMS_LOCK : (see DBMS_LOCK package) locking tables : (see table locks) LOG function : 13.1.12. The LOG function logical datatype : (see Boolean datatype) logical structure : 3.1.1. Revealing Logical Structure with Indentation LOGIN_DENIED exception : 8.3.1. Named System Exceptions LONG columns : 4.2.3.3. The LONG datatype and VARCHAR2 handling : 4.2.3.2. The VARCHAR2 and VARCHAR datatypes LONG datatype : 4.2.3.3. The LONG datatype LOB datatypes and : 4.2.7.5. LOBs and LONGs LONG RAW datatype : 4.2.3.5. The LONG RAW datatype LOB datatypes and : 4.2.7.5. LOBs and LONGs loop index : 7.3. The Numeric FOR Loop with loop scope : 7.6.2.1. Scope in FOR loops naming : 7.7.1. Naming Loop Indexes nontrivial increments : 7.3.3. Handling Nontrivial Increments using REVERSE : 7.3.1. Rules for Numeric FOR Loops LOOP keywords : (see loops) loop scope : 7.6.2.2. Scope with labels
loops : 7. Loops cursor FOR 1.6.4. The cursor FOR loop 7.4. The Cursor FOR Loop exiting : 1.7.5. Structured Code and Other Best Practices filling table rows with : 10.6.2. Iterative Assignment FOR loop 1.7.1. Write as Little Code as Possible 1.7.5. Structured Code and Other Best Practices formatting : 3.3.2. Formatting Loops GOTO statements within : 7.7.2.4. GOTO statements inside a loop labels for : 7.6.1. Loop Labels numeric FOR : 7.3. The Numeric FOR Loop REPEAT UNTIL : 7.2.2. Emulating a REPEAT UNTIL Loop RETURN statement within : 7.7.2.3. RETURN statement scope of : 7.6.2. Loop Scope simple : 7.2. The Simple Loop terminating with labels : 7.6.1.2. Loop termination using labels WHILE : 7.5. The WHILE Loop LOWER function : 11.1.7. The LOWER function lowercase : (see case) LPAD function : 11.1.8. The LPAD function LTRIM function 11.1.9. The LTRIM function 25.4.2. Zen and the Art of PL/SQL Tuning
Symbols | A | B | C | D | E | F | G | H | I | J | K | L | M | N | O | P | Q | R | S | T | U | V | W | Y | Z
The Oracle Library Navigation Copyright (c) 2000 O'Reilly & Associates. All rights reserved.
Symbols | A | B | C | D | E | F | G | H | I | J | K | L | M | N | O | P | Q | R | S | T | U | V | W | Y | Z
Index: M magic values : 16.3.1.2. A package of magic values hard-coding : 1.7.5. Structured Code and Other Best Practices mail : C.8. DBMS_MAIL mail, sending with external procedures : 21.7.2. Example: Sending Email MAKE_REF function : 20.3.3. MAKE_REF: Returning a Virtual REF DECODE function in : 20.4.2.3. Working around the ORA-22972 problem managing work queue (example) : 6.13.2. Managing a Work Queue with SELECT FOR UPDATE manual records : 9.6.1.1. Manual records MAP methods : 18.3.6.1. The MAP and ORDER methods MAXLEN property 21.4.1. Datatype Conversion 21.4.3.3. MAXLEN property member methods : 18.3.1. About Object Types memory analyzing size of code : 23.6.3. Analyzing the Size of PL/SQL Code and conditional control statements : 5.1.4. Nested IF Statements determining free disk space (example) : 21.1.1. Example: Determining Free Disk Space on Windows NT memory-based architecture of code : 23.1.3. Memory-Based Architecture of PL/SQL Code reducing package variables usage : 25.2.5. Reducing Memory Usage of Package Variables SGA (System Global Area) pinning critical code in : 25.2.2. Pin Critical Code into the SGA tuning shared pool size : 25.2.1. Tune the Size of the Shared Pool of the SGA used by open cursors : 6.8. Closing Cursors VSIZE function : 13.3.10. The VSIZE function messages about debugging : 24.2.9. Build Debugging Messages into Your Packages methods : 18.1.1. Terminology dot notation for : 18.3.4.2. Dots in method invocations for collections, built-in : 19.6. Collection Built-Ins modifying persistent objects : 18.5.2. Approach 2: Define Methods and Permit Limited Use of Conventional SQL types of : 18.3.1. About Object Types
minute : (see date; time) MOD function : 13.1.13. The MOD function modes, cursor parameters : 6.10.4. Cursor Parameter Modes modifying table rows : 10.5. Referencing and Modifying PL/SQL Table Rows modularization : 15.1. Modular Code modules (see also blocks; functions; packages; procedures) 1.4.3.10. Modular construction 2.7. Block Structure 15. Procedures and Functions 22.1.1. Make Sure the Module Name Explains the Module anchoring to variables in : 4.5.4. Anchoring to Variables in Other PL/SQL Blocks assertion : 22.2.4. Use Assertion Modules to Validate Parameters and Assumptions collections as parameters of : 19.2.2.3. Collections as module parameters constructing : 15.2.1. Sequence of Section Construction designing with NULL statements : 5.2.2.3. Supporting top-down design of modules exception handlers in (see also exceptions) 22.2.3. Avoid Exception Handlers for Normal Program Exits formatting : 3.4. Formatting PL/SQL Blocks forward declarations of : 15.9. Forward Declarations independent : 22.5. Create Independent Modules local 1.7.1. Write as Little Code as Possible 15.7. Local Modules 22.3. Take Full Advantage of Local Modularization naming 15.3.4.3. Named modules offer scoping effect of nested block 15.3.5.3. Qualifying identifier names with module names 22.1.1. Make Sure the Module Name Explains the Module nested 1.6.5. Scoping with nested blocks 2.7.3. Nested Blocks raising exceptions in : 8.4.1.2. Raising exceptions in nested blocks overloaded 1.6.6. Module overloading 15.8. Module Overloading overloading : 18.1.4.4. Polymorphism parameters of : 15.6. Parameters without : 22.4. Be Wary of Modules Without Any Parameters specifying in packages : 16.3. The Package Specification status of : 23.3. Module Validation and Dependency Management
stored : 23. Managing Code in the Database and target labels : 5.2.1.3. Target labels and PL/SQL blocks utility : C.16. DBMS_UTILITY validating : 23.3. Module Validation and Dependency Management MONITOR tool : 25.1. Analyzing Program Performance months : (see date) MONTHS_BETWEEN function : 12.1.3. The MONTHS_BETWEEN function multiline comments : (see block comments) multiline statements, formatting : 3.1.6. Formatting Multiline Statements MULTISET pseudo-function : 19.5.3. The MULTISET Pseudo-function mutual recursion : (see forward declarations)
Symbols | A | B | C | D | E | F | G | H | I | J | K | L | M | N | O | P | Q | R | S | T | U | V | W | Y | Z
The Oracle Library Navigation Copyright (c) 2000 O'Reilly & Associates. All rights reserved.
Symbols | A | B | C | D | E | F | G | H | I | J | K | L | M | N | O | P | Q | R | S | T | U | V | W | Y | Z
Index: N NAME_RESOLVE procedure : C.16.8. The NAME_RESOLVE procedure NAME_TOKENIZE procedure : C.16.9. The NAME_TOKENIZE procedure named collections : 19.5.2.1. Casting a named collection named constants 4.1. Identifiers 4.7.4. Use Named Constants to Avoid Hardcoding Values converting variables to : 4.7.5. Convert Variables into Named Constants named labels : 5.2.1. The GOTO Statement named notation : 15.6.4.2. Named notation naming columns 1.7.5. Structured Code and Other Best Practices 9.3.2. Setting the Record's Column Names cursor identifiers : 6.4.3. Identifier Precedence in a Cursor cursors : 6.4.1. The Cursor Name encrypted code files : 23.7.2. Working with Encrypted Code exceptions 8.3.1. Named System Exceptions 8.4.1.3. Overlapping exception names functions : 1.7.5. Structured Code and Other Best Practices identifiers : 2.2. Identifiers loop indexes : 7.7.1. Naming Loop Indexes loops : 7.6.1. Loop Labels modules 15.3.4.3. Named modules offer scoping effect of nested block 22.1.1. Make Sure the Module Name Explains the Module qualified identifiers and : 15.3.5.3. Qualifying identifier names with module names object types : 18.6.3. Schema Evolution packages : 22.1.3. Name Packages and Their Elements to Reflect the Packaged Structure parameters : 22.1.2. Develop Consistent Naming Conventions for Your Formal Parameters precedence, column/function : 17.6. Column/Function Name Precedence savepoints : 6.1.3. The SAVEPOINT Statement
subtypes : 4.7.2. Name Subtypes to Self-Document Code tables : 1.7.5. Structured Code and Other Best Practices variables 1.7.5. Structured Code and Other Best Practices 4.1. Identifiers 4.7.1. Establish Clear Variable Naming Conventions National Language Support : (see NLS character datatypes) NATURAL datatype : 4.2.1.1. Binary integer datatypes natural logarithm function : 13.1.11. The LN function NCHAR datatype : 4.2.6.1. The NCHAR datatype NCLOB datatype 1.4.7.6. Large object support 4.2.7.4. The NCLOB datatype negative numbers : 4.2.1.1. Binary integer datatypes negative row index : 10.2. Characteristics of PL/SQL Tables nested blocks (see also anonymous blocks) 15.3. The Anonymous PL/SQL Block 15.3.4. Nested Blocks cursors and : 15.3.5.4. Cursor scope scope and : 15.3.5.2. Scope and nested blocks IF statements : 5.1.4. Nested IF Statements modules : 2.7.3. Nested Blocks raising exceptions in : 8.4.1.2. Raising exceptions in nested blocks scoping with : 1.6.5. Scoping with nested blocks objects dot notation for : 18.3.4.1. Dots in data structures records : 9.7. Nested Records tables : 1.4.7.3. Variable arrays and nested tables (see also collections) 19.1. Types of Collections 19.3. Syntax for Declaring Collection Datatypes adding/removing elements of : 19.4.3. Adding and Removing Elements assigning values to elements : 19.4.2. Assigning Values to Elements: Index (Subscript) Considerations defining : 19.2.1. Collections "In the Database" initializing : 19.4.1. Initializing Collection Variables objects for : 18.1.2. Some Simple Examples THE pseudo-function for : 19.5.1. The THE Pseudo-function %TYPE attributes : 4.5.3. Nesting Usages of the %TYPE Attribute NESTED TABLE ... STORE AS clause : 19.2.1.1. Collection as a "column" in a conventional table
Net8 listener : 21.2.1. Step 1: Set Up the Listener new_add_months function : 12.2.1. Customizing the Behavior of ADD_MONTHS NEW_LINE procedure C.9.5. The NEW_LINE procedure C.17.1.7. The NEW_LINE procedure NEW_TIME function 12.1.4. The NEW_TIME function 12.2.2. Using NEW_TIME in Client-Server Environments NEXT function 10.8.2.6. The NEXT function 10.8.2.7. The PRIOR function 19.6.7. PRIOR(i), NEXT(i) NEXT_DATE procedure : C.5.5. The NEXT_DATE procedure NEXT_DAY function : 12.1.5. The NEXT_DAY function NEXT_ITEM_TYPE function : C.10.2. The NEXT_ITEM_TYPE function NLS character datatypes : 4.2.6. NLS Character Datatypes NO_DATA_FOUND exception 8.3.1. Named System Exceptions 8.8. NO_DATA_FOUND: Multipurpose Exception normalization of local variables : 4.5.1.2. Normalization of local variables not equals (<> and !=) : 2.1. The PL/SQL Character Set NOT NULL datatype : 4.4.4. NOT NULL Clause anchoring to : 4.5.5. Anchoring to NOT NULL Datatypes constraints : 25.4.6. Avoid NOT NULL Constraints NOT_LOGGED_ON exception : 8.3.1. Named System Exceptions %NOTFOUND cursor attribute 6.6.2. Fetching Past the Last Row 6.9.2. The %NOTFOUND Attribute NOWAIT keyword : 6.1.5. The LOCK TABLE Statement NULL : 4.3. NULLs in PL/SQL assigning to objects : 18.5.3. Approach 3: Do Everything via Methods and default values : 4.4.4. NOT NULL Clause in IF statements : 5.1.1. The IF-THEN Combination NOT NULL constraints : 25.4.6. Avoid NOT NULL Constraints NULL statements : 5.2.2. The NULL Statement with GOTO statements : 5.2.2.4. Using NULL with GOTO to avoid additional statement execution NVL function : 13.3.4. The NVL function setting records to : 9.6.1.3. Setting records to NULL string : 2.3. Literals NUMBER datatype 4.2.1.2. Decimal numeric datatypes
25.4.5. Use PLS_INTEGER for All Integer Operations numbers converting strings to/from 14.1.2. Number Format Models 14.2.7. The TO_CHAR function (number conversion) 14.2.9. The TO_NUMBER function converting to words : 17.8.7. Recursive Processing in a SQL Statement date : (see date) functions for : 13. Numeric, LOB, and Miscellaneous Functions line, finding code for : 23.6.6. Finding the Code for a Line Number suppressing zeros : 14.3.1. FM: Suppressing Blanks and Zeros numeric datatypes : 4.2.1. Numeric Datatypes FOR loops : 7.3. The Numeric FOR Loop formatting : 3.3.2. Formatting Loops loop index : 7.3. The Numeric FOR Loop nontrivial increments : 7.3.3. Handling Nontrivial Increments premature termination of : 7.7.2.1. Premature FOR loop termination range scheme : 7.3. The Numeric FOR Loop scope of : 7.6.2.1. Scope in FOR loops unnecessary : 7.7.3. Avoiding the Phony Loop literals : 2.3.2. Numeric Literals NUMERIC subtype : 4.2.2. Numeric Subtypes NVARCHAR2 datatype : 4.2.6.2. The NVARCHAR2 datatype NVL function 4.3.3. Function Results with NULL Arguments 13.3.4. The NVL function
Symbols | A | B | C | D | E | F | G | H | I | J | K | L | M | N | O | P | Q | R | S | T | U | V | W | Y | Z
The Oracle Library Navigation Copyright (c) 2000 O'Reilly & Associates. All rights reserved.
Symbols | A | B | C | D | E | F | G | H | I | J | K | L | M | N | O | P | Q | R | S | T | U | V | W | Y | Z
Index: O object tables, object views versus : 20.4. Differences Between Object Views and Object Tables object types 18.1.1. Terminology 18.1.4.2. Classification constructor methods 18.3.1. About Object Types 18.4.1.1. Constructors data dictionary entries : 18.6.1. Data Dictionary defining : 18.2.2. Defining the Object Type Body forward type definitions : 18.3.5.1. Forward type definitions instantiating objects from : 18.2.2.1. PL/SQL usage modifying : 18.6.3. Schema Evolution renaming : 18.6.3. Schema Evolution syntax for : 18.3. Syntax for Creating Object Types type modifiers : 18.2.3. Adding Complex Data Structures object views : 20. Object Views data dictionary entries : 20.7.1. Data Dictionary duplicate OIDs in : 20.4.1.1. Duplicate OIDs in a single view example of : 20.1. Example: Using Object Views INSTEAD OF triggers and : 20.2. INSTEAD OF Triggers object tables versus : 20.4. Differences Between Object Views and Object Tables privileges : 20.7.2. Privileges REFs and : 20.4.2. Using REFs with Object Views schema evolution and 20. Object Views 20.6. Schema Evolution syntax for : 20.3.1. CREATE VIEW: Creating an Object View object-oriented programming 18. Object Types 18.1.5. Object Programming Themes 18.7. Making the Objects Option Work object views and : 20. Object Views
objects : 18.1. Introduction to Oracle8 Objects assigning : 18.4.1.2. Direct assignment collections as object types : 19.2.1.2. Collection as an attribute of an object type comparing : 18.3.6. Comparing Objects database structure for : 18.2.2.2. DDL usage dependency of : 23.6.1. Displaying Object Dependencies desc command (SQL*Plus) : 18.6.2. SQL*Plus "Describe" Command destroying : 18.5.3. Approach 3: Do Everything via Methods dot notation : 18.3.4. Dot Notation equality of, testing : 18.3.6.2. Equality comparisons examples of 18.1.2. Some Simple Examples 18.2. Oracle Objects Example handles for : (see identifiers) identifiers : (see OIDs) in packages : 16.1.4. Object Persistence index-by tables of : 25.4.8. Use Index-By Tables of Records and Objects inheritance : 18.1.4.3. Inheritance initializing : 18.4.1. The Need to Initialize instantiating : 18.2.2.1. PL/SQL usage LOBs (large objects) : 1.4.7.6. Large object support functions for : 13.2. LOB Function Descriptions object views : 1.4.7.4. Object views object-oriented model support : 1.4.7.1. Support for an object-oriented model OIDs (object identifiers) : 18.4.2.1. Object identifiers (OIDs) persistent, modifying : 18.5. Modifying Persistent Objects privileges : 18.3.7. Privileges referring to : 18.4.2. OID, VALUE, REF, and DEREF REFs : (see REFs) returnin value of : 18.4.2.4. DEREF self-reference : (see SELF object) stored (see also stored objects) 23. Managing Code in the Database managing with SQL*Plus : 23.5. Managing Stored Objects with SQL*Plus viewing with SQL : 23.6. Using SQL to Examine Stored Objects synonyms for : 23.2.2. Creating Synonyms for Stored Objects OCI routines, for external procedures : 21.5. OCI Service Routines OIDs (object identifiers) : 18.4.2.1. Object identifiers (OIDs) uniqueness of 20.4.1. OID Uniqueness
20.4.4. REFs to Nonunique OIDs where stored : 18.4.2.1. Object identifiers (OIDs) one-dimensionality of tables : 10.2. Characteristics of PL/SQL Tables OODBs (object-oriented databases) : 18.1. Introduction to Oracle8 Objects OPEN statement (see also cursors) 6.2.2. Cursor Operations 6.5. Opening Cursors 6.10.2. Opening Cursors with Parameters with cursor variables : 6.12.4. Opening Cursor Variables OPEN FOR statement : 6.12.4. Opening Cursor Variables OPEN_CURSOR function : C.14.14. The OPEN_CURSOR function OPEN_CURSORS parameter : 6.8.1. Maximum Number of Cursors opening cursors 6.2.2. Cursor Operations 6.5. Opening Cursors 6.10.2. Opening Cursors with Parameters 6.12.4. Opening Cursor Variables operating sytem files : C.17. UTL_FILE operators, REFs as : 18.4.2.2. REFs optimizing foreign key lookups : 10.9.5. Optimizing Foreign Key Lookups with PL/SQL Tables OR REPLACE predicate : 18.3.2. CREATE TYPE and DROP TYPE: Creating and Dropping Types Oracle how PL/SQL fits in : 1.1. What Is PL/SQL? programming in : (see coding) Oracle/AQ : (see advanced queuing) Oracle Forms : 1.2. The Concept of Programming in Oracle Applications code of : 1.2. The Concept of Programming in Oracle Applications Oracle Lock Management (OLM) services : C.7. DBMS_LOCK Oracle Reports : 1.2. The Concept of Programming in Oracle Applications Oracle Server Version 7.1 : (see Release 2.1, PL/SQL) Version 7.2 : (see Release 2.2, PL/SQL) Oracle Tools, anonymous blocks in : 15.3.3. Anonymous Blocks in the Oracle Tools Oracle*Mail : C.8. DBMS_MAIL Oracle, Trusted : About the Contents Oracle/AQ, administration on : C.3.2. DBMS_AQADM (PL/SQL 8 Only) Oracle/AQ facility : C.3. Oracle AQ, the Advanced Queueing Facility ORADBX tool : 25.1. Analyzing Program Performance order, VARRAY elements : 19.4.1.4. VARRAY integration ORDER methods : 18.3.6.1. The MAP and ORDER methods OUT parameters
15.6.2.2. OUT mode 22.7.3. Assign Values to All OUT and IN OUT Parameters external procedure mappings : 21.4.1. Datatype Conversion in functions : 22.2.1.1. Do not use OUT and IN OUT parameters : 1.7.5. Structured Code and Other Best Practices outer tables : 19.1. Types of Collections overloaded modules 1.6.6. Module overloading 15.8. Module Overloading restrictions on : 15.8.4. Restrictions on Overloading overloading modules : 18.1.4.4. Polymorphism
Symbols | A | B | C | D | E | F | G | H | I | J | K | L | M | N | O | P | Q | R | S | T | U | V | W | Y | Z
The Oracle Library Navigation Copyright (c) 2000 O'Reilly & Associates. All rights reserved.
Symbols | A | B | C | D | E | F | G | H | I | J | K | L | M | N | O | P | Q | R | S | T | U | V | W | Y | Z
Index: P PACK_MESSAGE procedure : C.10.3. The PACK_MESSAGE procedure package variables, stored functions and : 17.4. Restrictions on PL/SQL Functions in SQL packages 1.4.3.10. Modular construction 1.6.8. Packages 16. Packages Booch diagram : 16.2.4. Public and Private Package Elements built-in 1.4.3.6. Built-in packages 1.6.3. Built-in packages built-in, reference on : C. Built-In Packages cursors in : 6.4.4. The Cursor RETURN Clause data structures in : 16.5. Package Data debugging messages in : 24.2.9. Build Debugging Messages into Your Packages declaring cursors in : 16.3.2. Declaring Package Cursors developing around : 1.7.3. Center All Development Around Packages documenting : 3.7. Documenting the Entire Package encapsulating data structure access : 1.7.2. Synchronize Program and Data Structures of exceptions only : 16.3.1.1. A package of exceptions formatting : 3.5. Formatting Packages functions in, calling : 17.5. Calling Packaged Functions in SQL granting execute authority to : 23.2.1. Execute Authority on Stored Objects initialization section purity level assertions in : 17.5.2. Asserting Purity Level with Package Initialization Section initializing : 16.6. Package Initialization of magic values only : 16.3.1.2. A package of magic values minimizing interdependencies : 25.2.4. Creating Packages with Minimal Interdependencies modifying persistent objects : 18.5.4. Approach 4: Use an Object and a PL/SQL Container Package naming : 22.1.3. Name Packages and Their Elements to Reflect the Packaged Structure numbers-to-words : 17.8.7. Recursive Processing in a SQL Statement
pinning into SGA shared pool : 25.2.2. Pin Critical Code into the SGA public versus private elements : 16.2.4. Public and Private Package Elements purity level of : 17.5.1. The RESTRICT_REFERENCES Pragma referencing elements of : 23.1.4. Key Concepts for Program Execution rights models : 18.3.7.3. Rights model specification 16.2.1. The Specification 16.3. The Package Specification STANDARD : 8.3.1. Named System Exceptions storing spefifications for : 1.7.3. Center All Development Around Packages synchronizing body and specification : 16.4.2. Synchronize Body with Package toggles in : 1.7.3. Center All Development Around Packages variables in : B.2.2. No Direct Stored Package Variable References reducing memory usage of : 25.2.5. Reducing Memory Usage of Package Variables padding strings 11.1.11. The RPAD function 11.1.8. The LPAD function parameters : 15.6. Parameters accepted in PARAMETERS clause : 21.4.3. Properties actual versus formal : 15.6.3. Actual and Formal Parameters Boolean : 22.7.2. Use Self-Identifying Parameters (Avoid Boolean Values) case consistency of : 22.7.4. Ensure Case Consistency of Parameters declaring : 21.4.4. Correct Declaration of Properties default values of B.2.4. No Default Parameter Values 15.6.5. Default Values 22.7.5. Default Values and Remote Procedure Calls design tips for : 22.7. Tips for Parameter Design documenting : 22.7.1. Document All Parameters and Their Functions IN mode : 15.6.2.1. IN mode IN OUT mode 15.6.2.3. The IN OUT mode 22.7.3. Assign Values to All OUT and IN OUT Parameters increasing number of : 22.5.3. Use Parameters Liberally mapping for external procedures : 21.4. Mapping Parameters module, collections as : 19.2.2.3. Collections as module parameters modules without : 22.4. Be Wary of Modules Without Any Parameters naming : 22.1.2. Develop Consistent Naming Conventions for Your Formal Parameters OUT mode 15.6.2.2. OUT mode 22.7.3. Assign Values to All OUT and IN OUT Parameters for overloaded modules : 15.8.4. Restrictions on Overloading
package data and : 25.4.4. Use Package Data to Avoid Passing "Bulky" Parameter Values passing by reference : 21.4.2. More Syntax: The PARAMETERS Clause tables as : 10.5.4. Passing PL/SQL Tables as Parameters validating with assertion modules : 22.2.4. Use Assertion Modules to Validate Parameters and Assumptions PARAMETERS clause : 21.4.1. Datatype Conversion declaring parameters : 21.4.4. Correct Declaration of Properties parameters possible in : 21.4.3. Properties parameters, cursor : 6.10. Cursor Parameters parent block : (see nested blocks) PARSE procedure : C.14.15. The PARSE procedure parsing SQL statements : 6.2.2. Cursor Operations parsing strings : 11.2.1. Parsing a Name part-of relationship : 18.1.4.3. Inheritance partitioned tables, ROWID datatype for : 4.2.3.6. The ROWID datatype partitioning table to store array : 10.9.4.2. Partitioning a PL/SQL table to store an array passing collection arguments : 19.8.3. Call by Reference or Call by Value parameters by reference : 21.4.2. More Syntax: The PARAMETERS Clause performance analyzing : 25.1. Analyzing Program Performance implicit cursors and : 6.3.2.1. Inefficiencies of implicit cursors implicit data conversions and : 4.2.8.3. Drawbacks of implicit conversions local variables and : 25.4.3. Rely on Local Variables to Improve Performance package data and : 25.4.4. Use Package Data to Avoid Passing "Bulky" Parameter Values stored functions and : 17.1. Looking at the Problem time, using progress box : 22.6.3. Progress Box as ADT persistence encapsulation and : 18.2.2.2. DDL usage REFs and : 18.2.3. Adding Complex Data Structures persistent objects modifying : 18.5. Modifying Persistent Objects referring to : 18.4.2. OID, VALUE, REF, and DEREF PGA (Program Global Area) : 25.3.1. Use Package Data to Minimize SQL Access phonetic string comparisons : 11.1.13. The SOUNDEX function pinning packages into SGA shared pool : 25.2.2. Pin Critical Code into the SGA pipes : (see DBMS_PIPE package) PL/SQL applications, tuning : 25. Tuning PL/SQL Applications access to compiled code : 25.2. Tuning Access to Compiled Code access to data : 25.3. Tuning Access to Your Data analyzing performance : 25.1. Analyzing Program Performance
optimizing algorithms : 25.4. Tuning Your Algorithms best practices : 1.7. Best Practices for PL/SQL Excellence blocks : (see modules) C interface, datatypes and : 21.4.1. Datatype Conversion and client-server architecture : 1.1. What Is PL/SQL? collections in : 19.2.2.1. Collection variables datatype subtypes in : 4.6.1. Declaring Subtypes debugging : (see debugging) definition of : 1.1. What Is PL/SQL? exceptions : (see exceptions) for I/O-intensive SQL : 25.3.6. Use PL/SQL to Improve Performance of IO-Intensive SQL functions in SQL : (see stored functions, PL/SQL) identifiers : (see identifiers) integration with server (example) : 19.7. Example: PL/SQL-to-Server Integration language coding : (see coding) structure of : 2.7. Block Structure language of : 2.1. The PL/SQL Character Set lexical units of : 2.1. The PL/SQL Character Set literals : (see literals) loops : (see loops) memory-based code architecture : 23.1.3. Memory-Based Architecture of PL/SQL Code modules : 2.7. Block Structure objects : (see objects) origins of : 1.3. The Origins of PL/SQL packages : (see packages) Programming Companion Utilities Guide : A. What's on the Companion Disk? Release 1.1 : 10.9.4.3. Features of the array package Release 2.2 : 6.12. Cursor Variables Release 2.3 6.12. Cursor Variables 10.1.1. PL/SQL Tables 10.8. PL/SQL Table Enhancements in PL/SQL Release 2.3 tracing execution : 26. Tracing PL/SQL Execution variables : (see variables) version 8 enhancements : 25.5. Overview of PL/SQL8 Enhancements versions of : 1.4. PL/SQL Versions Release 2.1 : 15.8.4. Restrictions on Overloading Version 1.1 : B. Calling Stored Procedures from PL/SQL Version 1.1 Version 2 : 15.6.1.1. %TYPE and %ROWTYPE Version 2.0
B.1. Using Stubs to Talk to Server-Side PL/SQL 1.4.3. PL/SQL Version 2.0 23.4. Remote Procedure Calls working with multiple : 1.4.1. Working with Multiple Versions of PL/SQL wrapper : 1.4.5.1. The PL/SQL wrapper PL/SQL tables : (see index-by tables) PLS-00452 error : 17.5.1.1. Pragma violation errors PLS_INTEGER data type : 25.4.5. Use PLS_INTEGER for All Integer Operations PLS_INTEGER datatype : 4.2.1.3. The PLS_INTEGER datatype pointers to objects : (see references to objects) polymorphism : 18.1.4.4. Polymorphism PORT_STRING function : C.16.10. The PORT_STRING function portability : 1.3.1. Improved Application Portability with PL/SQL POSITIVE datatype : 4.2.1.1. Binary integer datatypes Post-Query trigger : 6.3.2.1. Inefficiencies of implicit cursors POWER function : 13.1.14. The POWER function PRAGMA keyword : 2.6. The PRAGMA Keyword pragmas EXCEPTION_INIT : 8.3.3.1. The EXCEPTION_INIT pragma RESTRICT_REFEFRENCES : 17.3. Requirements for Stored Functions in SQL RESTRICT_REFERENCES 17.5.1. The RESTRICT_REFERENCES Pragma 17.7.1. Manual Application of Pragmas precedence, identifiers in cursors : 6.4.3. Identifier Precedence in a Cursor precision : 4.2.1.2. Decimal numeric datatypes predefined system exceptions : 8.3.1. Named System Exceptions PRIOR function 10.8.2.7. The PRIOR function 19.6.7. PRIOR(i), NEXT(i) private elements, package 16.2.2. The Body 16.2.4. Public and Private Package Elements global data : 16.5.4. Global Private Data privileges collections : 19.8.1. Privileges of objects : 18.3.7. Privileges procedural code, avoiding : 25.3.5. Avoid Procedural Code When Possible procedures (see also functions; modules) 1.4.3.10. Modular construction 15. Procedures and Functions
15.4. Procedures 22.1.1. Make Sure the Module Name Explains the Module changing trigger code to : 25.3.7. Keep Database Triggers Small for collections : 19.6. Collection Built-Ins external (see external procedures) 1.4.7.5. External procedures headers of : 15.4.2. Procedure Header IN OUT parameters in : 22.2.1.2. Switch to a procedure with IN OUT parameters local : 15.7. Local Modules parameters of : 15.6. Parameters records as parameters : 9.1.4. Guidelines for Using Records remote 22.7.5. Default Values and Remote Procedure Calls 23.4. Remote Procedure Calls RETURN statements in : 15.5.8.5. RETURN statement in a procedure shared : 23.1.1. Executing Procedures stored, from PL/SQL Version 1.1 : B. Calling Stored Procedures from PL/SQL Version 1.1 synonyms for : 23.2.2. Creating Synonyms for Stored Objects tables as parameters for : 10.5.4. Passing PL/SQL Tables as Parameters production support : 26.2. Tracing for Production Support Program Global Area (PGA) : 25.3.1. Use Package Data to Minimize SQL Access PROGRAM_ERROR exception : 8.3.1. Named System Exceptions programmer-defined exceptions 8.3.2. Named Programmer-Defined Exceptions 8.3.4. Unnamed Programmer-Defined Exceptions scope of : 8.4.1.1. Scope of programmer-defined exception records 1.4.3.3. Programmer-defined records 9.4. Programmer-Defined Records subtypes : 1.4.4.4. Programmer-defined subtypes programmer-defined datatypes : (see subtypes) programmer-defined PL/SQL functions : (see stored functions, PL/SQL) programming : (see coding) Programming Companion Utilities Guide : A. What's on the Companion Disk? programs analyzing performance of : 25.1. Analyzing Program Performance enabling tracing of : 26.1.1. Enabling Program Units for Tracing pinning into SGA shared pool : 25.2.2. Pin Critical Code into the SGA shared, executing : 23.1. Executing Stored Code testing : 24.2.5. Change and Test One Area of Code at a Time
progress boxes : 22.6.3. Progress Box as ADT progress package : 22.6.4.1. The progress package specification propagation of exceptions : 8.4.2. Propagation of an Exception properties, object : (see attributes, object) privileges, object views : 20.7.2. Privileges pseudoinstructions : 2.6. The PRAGMA Keyword public elements, package 16.2.1. The Specification 16.2.4. Public and Private Package Elements global data : 16.5.3. Global Public Data PURGE procedure : C.10.4. The PURGE procedure PURGE_LOG procedure : C.13.3. The PURGE_LOG procedure PURGE_LOST_DB procedure : C.15.16. The PURGE_LOST_DB procedure PURGE_MIXED procedure : C.15.15. The PURGE_MIXED procedure purity levels, packages : 17.5.1. The RESTRICT_REFERENCES Pragma PUT procedure : C.17.1.8. The PUT procedure PUT_LINE function : 23.1.2. Executing Functions PUT_LINE procedure C.9.7. The PUT_LINE procedure C.17.1.10. The PUT_LINE procedure PUTF procedure : C.17.1.9. The PUTF procedure
Symbols | A | B | C | D | E | F | G | H | I | J | K | L | M | N | O | P | Q | R | S | T | U | V | W | Y | Z
The Oracle Library Navigation Copyright (c) 2000 O'Reilly & Associates. All rights reserved.
Symbols | A | B | C | D | E | F | G | H | I | J | K | L | M | N | O | P | Q | R | S | T | U | V | W | Y | Z
Index: Q qualified identifiers : 15.3.5.1. Qualified identifiers queries and correlated subqueries : 17.8.3. Replacing Correlated Subqueries queue managing, with DBMS_JOB : (see DBMS_JOB) queue, managing (example) : 6.13.2. Managing a Work Queue with SELECT FOR UPDATE queuing, advanced : 1.4.7.2. Oracle/AQ, the Advanced Queueing Facility queuing facility C.3. Oracle AQ, the Advanced Queueing Facility administration of : C.3.2. DBMS_AQADM (PL/SQL 8 Only) quick-and-dirty tracing : 26.5. Quick-and-Dirty Tracing quotation marks 2.3.1. Embedding Single Quotes Inside a String 11.1.10. The REPLACE function embedding : 2.3.1. Embedding Single Quotes Inside a String 2.3.1. Embedding Single Quotes Inside a String
Symbols | A | B | C | D | E | F | G | H | I | J | K | L | M | N | O | P | Q | R | S | T | U | V | W | Y | Z
The Oracle Library Navigation Copyright (c) 2000 O'Reilly & Associates. All rights reserved.
Symbols | A | B | C | D | E | F | G | H | I | J | K | L | M | N | O | P | Q | R | S | T | U | V | W | Y | Z
Index: R RAISE statement 8.5.1.2. Programmer raises ZERO_DIVIDE exception 8.10. RAISE Nothing but Exceptions RAISE_APPLICATION_ERROR procedure 8.3.4. Unnamed Programmer-Defined Exceptions 8.7. Client-Server Error Communication raising exceptions (see also exceptions) 8.4.1.2. Raising exceptions in nested blocks 8.5. Raising an Exception 8.10. RAISE Nothing but Exceptions range scheme, FOR loops : 7.3. The Numeric FOR Loop RAW datatype 4.2.3.4. The RAW datatype 14.2.3. The HEXTORAW function RAWTOHEX function : 14.2.4. The RAWTOHEX function RDBMS language : 1.3.1. Improved Application Portability with PL/SQL read consistency, stored functions and : 17.7.2. Read Consistency Model Complications READ procedure : C.6.13. The READ procedure read-committed isolation level : 6.1.4. The SET TRANSACTION Statement read-only parameters : (see IN mode) read-only transactions : 6.1.4. The SET TRANSACTION Statement READ_ONLY procedure : C.15.7. The READ_ONLY procedure READ_WRITE procedure : C.15.8. The READ_WRITE procedure readability of code : 15.7.3. Improving Readability readability, local modules for : 1.7.1. Write as Little Code as Possible REAL subtype : 4.2.2. Numeric Subtypes real-time production support : 26.2.1. Features of a Real-Time Support Mechanism RECEIVE_MESSAGE function : C.10.5. The RECEIVE_MESSAGE function records (see also variables) 1.4.3.3. Programmer-defined records
1.7.1. Write as Little Code as Possible 4. Variables and Program Data 9. Records in PL/SQL accessing data from : 9.1.2. Accessing Record-Based Data child : 8.3.3.1. The EXCEPTION_INIT pragma collections as components of : 19.2.2.2. Collections as components of a record comparing : 9.1.6. Comparing Two Records compatibility of : 9.6. Record Types and Record Compatibility corresponding to cursors : 9.1.4. Guidelines for Using Records cursor FOR loops : 7.4.2. The Cursor FOR Loop Record cursor-based (see also cursors) 9.3. Cursor-Based Records declaring 9.2.1. Declaring Records with the %ROWTYPE Attribute 9.4.2. Declaring the Record deleting 10.7. Clearing the PL/SQL Table 10.8.2.2. The DELETE procedure fetching into : (see FETCH statement) filling : 10.6. Filling the Rows of a PL/SQL Table index-by tables of : 25.4.8. Use Index-By Tables of Records and Objects initializing : 9.6.2. Record Initialization locking : 6.11. SELECT FOR UPDATE in Cursors manual : 9.6.1.1. Manual records naming columns of : 9.3.2. Setting the Record's Column Names nested : 9.7. Nested Records as parameters : 9.1.4. Guidelines for Using Records programmer-defined : 9.4. Programmer-Defined Records referencing : 9.1.5. Referencing a Record and its Fields setting to NULL : 9.6.1.3. Setting records to NULL table-based : 9.2. Table-Based Records in tables : 10.8. PL/SQL Table Enhancements in PL/SQL Release 2.3 referencing fields of : 10.8.1.1. Referencing fields of record elements in PL/SQL tables recursion, mutual : (see forward declarations) recursive object types : 18.3.5.1. Forward type definitions recursive processing : 17.8.7. Recursive Processing in a SQL Statement redundancy avoiding in package bodies : 1.7.3. Center All Development Around Packages local modules for : 1.7.1. Write as Little Code as Possible REF CURSOR type (see also cursor variables)
6.12.3. Declaring REF CURSOR Types and Cursor Variables 6.12.6.3. Cursor variable aliases identifying : 6.12.7.1. Identifying the REF CURSOR type REF keyword : 18.2.3. Adding Complex Data Structures reference pointers : (see REFs) references to host variables : 25.4.3.2. Minimize references to host variables references to objects : (see REFs) referencing record fields in tables : 10.8.1.1. Referencing fields of record elements in PL/SQL tables table rows : 10.5. Referencing and Modifying PL/SQL Table Rows REFRESH procedure : C.13.4. The REFRESH procedure REFRESH_ALL procedure : C.13.5. The REFRESH_ALL procedure REFs (object references) 18.1.4.3. Inheritance 18.2.3. Adding Complex Data Structures 18.4.2.2. REFs as collection elements : 19.2.1. Collections "In the Database" DEREF operator and : 18.4.2.4. DEREF object views and 20. Object Views 20.3.3. MAKE_REF: Returning a Virtual REF 20.4.2. Using REFs with Object Views as operators : 18.4.2.2. REFs as type modifiers : 18.4.2.2. REFs REGISTER procedure : C.2.1. The REGISTER procedure relational (=) operators : 2.1. The PL/SQL Character Set Release 1.1, PL/SQL 1.4.8. PL/SQL Release 1.1 10.9.4.3. Features of the array package Release 2.1, PL/SQL : 1.4.4. PL/SQL Release 2.1 new_add_months function : 12.2.1. Customizing the Behavior of ADD_MONTHS overloaded modules : 15.8.4. Restrictions on Overloading Release 2.2, PL/SQL : 1.4.5. PL/SQL Release 2.2 cursor variables : 6.12. Cursor Variables Release 2.3, PL/SQL 1.4.6. PL/SQL Release 2.3 10.1.1. PL/SQL Tables tables : 10.8. PL/SQL Table Enhancements in PL/SQL Release 2.3 RELEASE function : C.7.3. The RELEASE function releasing record locks : 6.11.1. Releasing Locks with COMMIT remainder function : 13.1.13. The MOD function remote dependency
1.4.6.4. Improved remote dependency model 1.4.7.5. External procedures remote procedure calls (RPCs) : B.2.3. No Direct Remote Procedure Calls remote procedures 22.7.5. Default Values and Remote Procedure Calls 23.4. Remote Procedure Calls REMOVE procedure C.2.2. The REMOVE procedure C.5.6. The REMOVE procedure REMOVE_PIPE function : C.10.6. The REMOVE_PIPE function REMOVEALL procedure : C.2.3. The REMOVEALL procedure removing : (see deleting) REPEAT UNTIL loop : 7.2.2. Emulating a REPEAT UNTIL Loop repetitive code (see redundancy) 15.7.1. Benefits of Local Modularization REPLACE function (see also TRANSLATE function) 4.3.3. Function Results with NULL Arguments 11.1.10. The REPLACE function 11.1.15. The TRANSLATE function replacing characters in strings : 11.1.15. The TRANSLATE function REQUEST function : C.7.4. The REQUEST function reserved words 2.2.1. Reserved Words 3.1.2. Using Case to Aid Readability RESET_BUFFER procedure : C.10.7. The RESET_BUFFER procedure RESET_PACKAGE procedure : C.12.3. The RESET_PACKAGE procedure RESTRICT_REFEFRENCES pragma : 17.3. Requirements for Stored Functions in SQL RESTRICT_REFERENCES pragma : 17.5.1. The RESTRICT_REFERENCES Pragma manual application of : 17.7.1. Manual Application of Pragmas RETURN datatype : 15.5.2. The RETURN Datatype RETURN statement 6.4.4. The Cursor RETURN Clause 7.7.2.3. RETURN statement 15.5.8. The RETURN Statement cursor : 6.4. Declaring Cursors in procedures : 15.5.8.5. RETURN statement in a procedure overloaded functions : 15.8.4. Restrictions on Overloading of package cursors : 16.3.2. Declaring Package Cursors using single : 22.2.2. Use a Single RETURN Statement for Successful Termination reusing code : 1.7.1. Write as Little Code as Possible
REVERSE keyword : 7.3.1. Rules for Numeric FOR Loops rights models : 18.3.7.3. Rights model RNDS purity code : 17.5.1. The RESTRICT_REFERENCES Pragma RNPS purity code : 17.5.1. The RESTRICT_REFERENCES Pragma ROLLBACK procedure : C.15.9. The ROLLBACK procedure ROLLBACK statement 6.1.2. The ROLLBACK Statement 6.11.1. Releasing Locks with COMMIT ROLLBACK TO statement : 6.1.2. The ROLLBACK Statement ROLLBACK_FORCE procedure : C.15.10. The ROLLBACK_FORCE procedure ROLLBACK_SAVEPOINT procedure : C.15.11. The ROLLBACK_SAVEPOINT procedure ROUND function 12.1.6. The ROUND function 13.1.15. The ROUND function rounding dates : 12.1.6. The ROUND function row numbers, converting expressions to : 10.5.1. Automatic Conversion of Row Number Expressions %ROWCOUNT cursor attribute : 6.9.3. The %ROWCOUNT Attribute ROWID datatype : 4.2.3.6. The ROWID datatype converting to/from : 14.2.1. The CHARTOROWID function ROWID_BLOCK_NUMBER function : C.11.6. The ROWID_BLOCK_NUMBER function ROWID_CREATE function : C.11.1. The ROWID_CREATE function ROWID_INFO procedure : C.11.2. The ROWID_INFO procedure ROWID_OBJECT function : C.11.4. The ROWID_OBJECT function ROWID_RELATIVE_FNO function : C.11.5. The ROWID_RELATIVE_FNO function ROWID_ROW_NUMBER function : C.11.7. The ROWID_ROW_NUMBER function ROWID_TO_ABSOLUTE_FNO function : C.11.8. The ROWID_TO_ABSOLUTE_FNO function ROWID_TO_EXTENDED function : C.11.9. The ROWID_TO_EXTENDED function ROWID_TO_RESTRICTED function : C.11.10. The ROWID_TO_RESTRICTED function ROWID_TYPE function : C.11.3. The ROWID_TYPE function ROWID_VERIFY function : C.11.11. The ROWID_VERIFY function ROWIDs, DBMS_ROWID package for : C.11. DBMS_ROWID (PL/SQL8 Only) ROWIDTOCHAR function : 14.2.5. The ROWIDTOCHAR function rows, table (see also records) 9.1.1. Different Types of Records data-smart numbers for : 10.9.2. Data-Smart Row Numbers in PL/SQL Tables negative index : 10.2. Characteristics of PL/SQL Tables objects for : 18.1.2. Some Simple Examples referencing and modifying : 10.5. Referencing and Modifying PL/SQL Table Rows %ROWTYPE attribute 1.7.2. Synchronize Program and Data Structures 9.2.1. Declaring Records with the %ROWTYPE Attribute
15.6.1.1. %TYPE and %ROWTYPE in cursor declarations : (see cursors) ROWTYPE_MISMATCH exception : 6.12.5.2. Handling the ROWTYPE_MISMATCH exception RPAD function : 11.1.11. The RPAD function RPCs (remote procedure calls) : 23.4. Remote Procedure Calls RR format model : 14.3.3. RR: Changing Millenia RTRIM function : 11.1.12. The RTRIM function run authority (see execute authority) 1.3.2. Improved Execution Authority and Transaction Integrity with PL/SQL RUN procedure : C.5.7. The RUN procedure
Symbols | A | B | C | D | E | F | G | H | I | J | K | L | M | N | O | P | Q | R | S | T | U | V | W | Y | Z
The Oracle Library Navigation Copyright (c) 2000 O'Reilly & Associates. All rights reserved.
Symbols | A | B | C | D | E | F | G | H | I | J | K | L | M | N | O | P | Q | R | S | T | U | V | W | Y | Z
Index: S SAVEPOINT procedure : C.15.12. The SAVEPOINT procedure SAVEPOINT statement : 6.1.3. The SAVEPOINT Statement savepoints (see also ROLLBACK statement) 6.1.2. The ROLLBACK Statement COMMIT statements and : 6.1.1. The COMMIT Statement creating : 6.1.3. The SAVEPOINT Statement saving virtual REFs : 20.4.3. Storage of Virtual REFs scalar datatypes : (see datatypes) scalar values and aggregates : 17.8.2. Combining Scalar and Aggregate Values scale : 4.2.1.2. Decimal numeric datatypes scheduling jobs DBMS_JOB for C.5. DBMS_ JOB 1.4.5.3. Job scheduling with DBMS_ JOB schema evolution object types and : 18.6.3. Schema Evolution object views and 20. Object Views 20.6. Schema Evolution scope 1.6.5. Scoping with nested blocks 2.7.2. Scope of a Block 15.3.4.2. Nested blocks provide scope cursor : 15.3.5.4. Cursor scope of cursor parameters : 6.10.3. Scope of Cursor Parameters of cursor variables : 6.12.6.4. Scope of cursor object of exceptions : 8.4.1. Scope of an Exception of local modules : 15.7.5. Scope of Local Modules of loops : 7.6.2. Loop Scope nested blocks and : 15.3.5.2. Scope and nested blocks second : (see date; time)
security backups : (see backups) encrypting code : 23.7. Encrypting Stored Code SELECT COUNT(*) : 1.7.5. Structured Code and Other Best Practices SELECT INTO statement : 9.5.2. SELECT INTO from an Implicit Cursor select lists : 6.4.2. PL/SQL Variables in a Cursor SELECT statement assigning objects : 18.4.1.3. Assignment via FETCH (with SELECT) in cursor declarations : 6.4. Declaring Cursors cursors and : 6.2. Cursors in PL/SQL SELECT FOR UPDATE statement 6.11. SELECT FOR UPDATE in Cursors 6.13.2. Managing a Work Queue with SELECT FOR UPDATE SELECT INTO statement initializing collections : 19.4.1.3. Initializing implicitly via fetch THE function with : 19.5.1. The THE Pseudo-function SELECT statements (see also DML statements) 4.2.3.2. The VARCHAR2 and VARCHAR datatypes 9.1.5. Referencing a Record and its Fields 10.3. PL/SQL Tables and DML Statements SELF object 18.1.2. Some Simple Examples 18.3.5. SELF: The Implied Parameter IN mode for : 18.3.4.2. Dots in method invocations semicolon (;) : 2.4. The Semicolon Delimiter SEND_MESSAGE function : C.10.8. The SEND_MESSAGE function sequential control structures : 5.2. Sequential Control Statements formatting : 3.3. Formatting Control Structures sequential processing : 17.8.6. Sequential Processing Against a Column's Value serializable isolation level : 6.1.4. The SET TRANSACTION Statement servers, PL/SQL integration with (example) : 19.7. Example: PL/SQL-to-Server Integration session, user : 13.3.9. The USERENV function SET clause, functions in : 17.1. Looking at the Problem SET TRANSACTION statements : 6.1.4. The SET TRANSACTION Statement SET_BLOCK_PROPERTY : 14.3.4. Using TO_CHAR to Create a Date Range SET_DEFAULTS procedure : C.2.4. The SET_DEFAULTS procedure SET_LABEL procedure : C.12.4. The SET_LABEL procedure SET_MLS_LABEL procedure : C.12.5. The SET_NLS_LABEL procedure SET_NLS procedure : C.12.6. The SET_NLS procedure SET_ROLE procedure : C.12.7. The SET_ROLE procedure SET_SQL_TRACE procedure : C.12.8. The SET_SQL_TRACE procedure
SET_UP procedure : C.13.6. The SET_UP procedure SGA (System Global Area) pinning critical code in : 25.2.2. Pin Critical Code into the SGA tuning shared pool size : 25.2.1. Tune the Size of the Shared Pool of the SGA shared functions : 23.1.2. Executing Functions procedures : 23.1.1. Executing Procedures shared libraries 1.4.7.5. External procedures for external procedures : 21.2.2. Step 2: Identify or Create the Shared Library shared pool, SGA : 25.2.1. Tune the Size of the Shared Pool of the SGA SIGN function : 13.1.16. The SIGN function SIGNAL procedure : C.2.5. The SIGNAL procedure signed numbers 4.2.1.1. Binary integer datatypes 4.2.1.3. The PLS_INTEGER datatype simple loops 7.2. The Simple Loop formatting : 3.3.2. Formatting Loops SIN function : 13.1.17. The SIN function SINH function : 13.1.18. The SINH function size database triggers : 25.3.7. Keep Database Triggers Small encrypted code file size : 23.7.3. Impact of Encrypting Code of PL/SQL code, analyzing : 23.6.3. Analyzing the Size of PL/SQL Code SGA shared pool, tuning : 25.2.1. Tune the Size of the Shared Pool of the SGA SLEEP procedure : C.7.5. The SLEEP procedure SMALLINT subtype : 4.2.2. Numeric Subtypes snapshots : C.13. DBMS_SNAPSHOT SOUNDEX function : 11.1.13. The SOUNDEX function source code : (see coding) spaces : (see whitespace) sparsity of tables 10.2. Characteristics of PL/SQL Tables 10.9.2. Data-Smart Row Numbers in PL/SQL Tables specifcations, package : 1.7.3. Center All Development Around Packages specification, package : (see packages, specification) SQL ALTER SESSION commands : C.12. DBMS_SESSION calliong PL/SQL functions in : 25.3.2. Call PL/SQL Functions in SQL to Reduce I/O client-side : 25.3.3. Avoid Client-Side SQL DDL statements : (see DDL)
DML statements : (see DML statements) dynamic C.14. DBMS_SQL 1.4.4.2. Support for DDL and dynamic SQL formatting statements : 3.2. Formatting SQL Statements I/O-intensive : 25.3.6. Use PL/SQL to Improve Performance of IO-Intensive SQL minimizing access to : 25.3.1. Use Package Data to Minimize SQL Access PL/SQL in : (see stored functions, PL/SQL) PL/SQL loops versus : 7.7.4. PL/SQL Loops Versus SQL Processing statements, recursive processing in : 17.8.7. Recursive Processing in a SQL Statement static vs. dynamic : 6.2.1. Types of Cursors storing functions in : 1.4.4.1. Stored functions in SQL viewing stored objects : 23.6. Using SQL to Examine Stored Objects SQL %FOUND attribute : 6.9.5. Implicit SQL Cursor Attributes SQL %ISOPEN attribute : 6.9.5. Implicit SQL Cursor Attributes SQL %NOTFOUND attribute : 6.9.5. Implicit SQL Cursor Attributes SQL %ROWCOUNT attribute : 6.9.5. Implicit SQL Cursor Attributes SQL*Plus managing stored objects : 23.5. Managing Stored Objects with SQL*Plus viewing compilation errors : 23.5.4. Viewing Compilation Errors in SQL*Plus SQL_TRACE utility : 25.1. Analyzing Program Performance SQLCODE function 8.3.1. Named System Exceptions 8.6.3. Using SQLCODE and SQLERRM in WHEN OTHERS Clause 13.3.5. The SQLCODE function SQLERRM function 8.6.3. Using SQLCODE and SQLERRM in WHEN OTHERS Clause 13.3.6. The SQLERRM function SQRT function : 13.1.19. The SQRT function standalone procedures synonyms for : 23.2.2. Creating Synonyms for Stored Objects STANDARD package : 8.3.1. Named System Exceptions pinning in SGA shared pool : 25.2.2.1. Candidates for pinning in the shared pool START_QUEUE procedure : C.3.2.6. The START_QUEUE procedure static cursors : 6.2.1. Types of Cursors static SQL : 6.2.1. Types of Cursors status, module : 23.3. Module Validation and Dependency Management STEP syntax : (see numeric FOR loops) STEP_ID function : C.15.18. The STEP_ID function STOP_QUEUE procedure : C.3.2.7. The STOP_QUEUE procedure STORAGE_ERROR exception : 8.3.1. Named System Exceptions store tables : 19.1. Types of Collections
stored code, encrypting : 23.7. Encrypting Stored Code functions, executing PL/SQL : 23.1.2. Executing Functions modules/packages : 1.4.3.11. Stored procedures, functions, and packages objects : 23. Managing Code in the Database execute authority on : 23.2.1. Execute Authority on Stored Objects interdependency of : 23.3.1. Interdependencies of Stored Objects managing with SQL*Plus : 23.5. Managing Stored Objects with SQL*Plus synonyms for : 23.2.2. Creating Synonyms for Stored Objects viewing with SQL : 23.6. Using SQL to Examine Stored Objects procedures, PL/SQL Version 1.1 : B. Calling Stored Procedures from PL/SQL Version 1.1 virtual REFs : 20.4.3. Storage of Virtual REFs stored functions, PL/SQL 17.1. Looking at the Problem 17.7. Realities: Calling PL/SQL Functions in SQL calling packaged functions : 17.5. Calling Packaged Functions in SQL examples of : 17.8. Examples of Embedded PL/SQL name precedence and : 17.6. Column/Function Name Precedence package variable modification : 17.4. Restrictions on PL/SQL Functions in SQL read consistency and : 17.7.2. Read Consistency Model Complications requirements/restrictions : 17.3. Requirements for Stored Functions in SQL strings (see also literals) 2.3. Literals adding characters to 11.1.11. The RPAD function 11.1.8. The LPAD function case of 11.1.16. The UPPER function 11.1.4. The INITCAP function 11.1.7. The LOWER function comparing 4.2.3.2. The VARCHAR2 and VARCHAR datatypes 11.1.13. The SOUNDEX function concatenating : 11.1.3. The CONCAT function converting between character sets : 14.2.2. The CONVERT function to/from dates 14.1. Conversion Formats 14.2.6. The TO_CHAR function (date conversion) 14.2.8. The TO_DATE function hexadecimal : 14.2.3. The HEXTORAW function
to/from numbers 14.1.2. Number Format Models 14.2.7. The TO_CHAR function (number conversion) 14.2.9. The TO_NUMBER function 17.8.7. Recursive Processing in a SQL Statement to row numbers : 10.5.1. Automatic Conversion of Row Number Expressions datatypes for : 4.2.3. Character Datatypes extracting characters from : 11.1.14. The SUBSTR function finding substrings of : 11.1.5. The INSTR function functions for : 11. Character Functions justifying : 11.2.3. Filling Text to Fit a Line length of : 11.1.6. The LENGTH function parsing : 11.2.1. Parsing a Name replacing characters in 11.1.10. The REPLACE function 11.1.15. The TRANSLATE function searching for, in code : 23.6.4. Displaying and Searching Source Code stripping characters from 11.1.12. The RTRIM function 11.1.9. The LTRIM function variable-length : 4.2.3.2. The VARCHAR2 and VARCHAR datatypes verifying format of : 11.2.5. Verifying String Formats with TRANSLATE word wrap : 11.2.2. Implementing Word Wrap for Long Text strong REF CURSOR type : (see cursor variables) structure, code : 1.7.5. Structured Code and Other Best Practices structure, data : (see data structures) structured interface trace filtering : 26.4. Structured Interface Filtering stub generation : B.1. Using Stubs to Talk to Server-Side PL/SQL stubs : 5.2.2.3. Supporting top-down design of modules style, coding : 1.7.4. Standardize Your PL/SQL Development Environment subblocks : (see nested blocks; nested modules) SUBMIT procedure : C.5.8. The SUBMIT procedure subqueries, correlated : 17.8.3. Replacing Correlated Subqueries SUBSTR function C.6.14. The SUBSTR function 11.1.14. The SUBSTR function for declaring long strings : 4.2.3.1. The CHAR datatype substrings counting occurrences of : 11.2.4. Counting Substring Occurrences in Strings extracting from strings : 11.1.14. The SUBSTR function finding : 11.1.5. The INSTR function replacing
11.1.10. The REPLACE function 11.1.15. The TRANSLATE function subtypes 1.4.4.4. Programmer-defined subtypes 4.6. Programmer-Defined Subtypes suppressing zeros/spaces : 14.3.1. FM: Suppressing Blanks and Zeros symbols != (not equals) : 2.1. The PL/SQL Character Set % (percent sign) : 2.1. The PL/SQL Character Set > (label delimeters) : 2.1. The PL/SQL Character Set >= (greater than) : 2.1. The PL/SQL Character Set <> (not equals) : 2.1. The PL/SQL Character Set <= (less than) : 2.1. The PL/SQL Character Set ** (double asterisk) : 2.1. The PL/SQL Character Set -- (comment indicator) : 2.1. The PL/SQL Character Set /* and */ (comment block delimiters) : 2.1. The PL/SQL Character Set ; (semicolon) : 2.1. The PL/SQL Character Set => (associational operator for positional notation) : 2.1. The PL/SQL Character Set \: (colon) : 2.1. The PL/SQL Character Set _ (underscore) : 2.1. The PL/SQL Character Set || (concatenation) operator : 2.1. The PL/SQL Character Set synchronization : 1.7.2. Synchronize Program and Data Structures synchronization with columns : 4.5.1.1. Synchronization with database columns synonyms for stored objects : 23.2.2. Creating Synonyms for Stored Objects SYS_NC_OID$ column : 18.4.2.1. Object identifiers (OIDs) SYS_NC_ROWINFO$ column : 18.4.2.1. Object identifiers (OIDs) SYSDATE function : 12.1.7. The SYSDATE function and NEW_TIME function : 12.2.2. Using NEW_TIME in Client-Server Environments system date : 12.1.7. The SYSDATE function exceptions : 8.3.1. Named System Exceptions System Global Area (SGA) pinning critical code into : 25.2.2. Pin Critical Code into the SGA tuning shared pool size : 25.2.1. Tune the Size of the Shared Pool of the SGA
Symbols | A | B | C | D | E | F | G | H | I | J | K | L | M | N | O | P | Q | R | S | T | U | V | W | Y | Z
The Oracle Library Navigation Copyright (c) 2000 O'Reilly & Associates. All rights reserved.
Symbols | A | B | C | D | E | F | G | H | I | J | K | L | M | N | O | P | Q | R | S | T | U | V | W | Y | Z
Index: T table locks 6.1.5. The LOCK TABLE Statement COMMIT statements and : 6.1.1. The COMMIT Statement TABLE pseudo-function : 19.5.4. The TABLE Pseudo-function TABLE type : 15.6.1.1. %TYPE and %ROWTYPE table-based records : 9.2. Table-Based Records TABLE_TO_COMMA procedure : C.16.11. The TABLE_TO_COMMA procedure tables (see also arrays; variables) (see also collections) 1.4.3.4. PL/SQL tables 4. Variables and Program Data 10. PL/SQL Tables 19.1. Types of Collections abbreviations for : 3.2. Formatting SQL Statements aliases for : 3.2. Formatting SQL Statements building arrays with : 10.9.4. Building Traditional Arrays with PL/SQL Tables clearing (deleting) : 10.7. Clearing the PL/SQL Table combining scalars and aggregates : 17.8.2. Combining Scalar and Aggregate Values declaring : 10.4. Declaring a PL/SQL Table displaying : 10.9.3. Displaying a PL/SQL Table and DML statements : 10.3. PL/SQL Tables and DML Statements filling rows of : 10.6. Filling the Rows of a PL/SQL Table index-by : (see index-by tables) inner tables : 19.1. Types of Collections names for : 1.7.5. Structured Code and Other Best Practices nested (see nested tables) 1.4.7.3. Variable arrays and nested tables objects for : 18.1.2. Some Simple Examples optimizing foreign key lookups : 10.9.5. Optimizing Foreign Key Lookups with PL/SQL Tables
outer tables : 19.1. Types of Collections as parameters : 10.5.4. Passing PL/SQL Tables as Parameters partitioned, ROWID datatype for : 4.2.3.6. The ROWID datatype PL/SQL : (see index-by tables) records in : 10.8. PL/SQL Table Enhancements in PL/SQL Release 2.3 referencing rows : 10.5. Referencing and Modifying PL/SQL Table Rows Release 2.3 enhancements to : 10.8. PL/SQL Table Enhancements in PL/SQL Release 2.3 returned from functions : 10.8.1.1. Referencing fields of record elements in PL/SQL tables row index data-smart : 10.9.2. Data-Smart Row Numbers in PL/SQL Tables negative : 10.2. Characteristics of PL/SQL Tables store tables : 19.1. Types of Collections table objects retrieving : 18.4.2.3. VALUE VARRAYs : (see VARRAYs) virtual : 6.2. Cursors in PL/SQL tabs : (see whitespace) TAN function : 13.1.20. The TAN function TANH function : 13.1.21. The TANH function target labels : 5.2.1.2. Target labels and scope of GOTO terminating loops prematurely : 7.7.2. The Proper Way to Say Goodbye testing code : 24.2.5. Change and Test One Area of Code at a Time object equality : 18.3.6.2. Equality comparisons testing programs : 2.5.2. Multiline Comment Syntax text datatypes : 4.2.3. Character Datatypes debugging messages in packages : 24.2.9. Build Debugging Messages into Your Packages justifying : 11.2.3. Filling Text to Fit a Line word wrap : 11.2.2. Implementing Word Wrap for Long Text THE pseudo-function 19.5.1. The THE Pseudo-function 19.5.4. The TABLE Pseudo-function THEN keyword : (see IF statements; WHEN clause) time (see also date) C.16.6. The GET_TIME function 12.1.1. The ADD_MONTHS function 12.1.4. The NEW_TIME function system : 12.1.7. The SYSDATE function zones 12.1.4. The NEW_TIME function
12.2.2. Using NEW_TIME in Client-Server Environments time zone, retrieving (example) : 21.7.1. Example: Retrieving the Time Zone TIMEOUT_ON_RESOURCE exception : 8.3.1. Named System Exceptions TO_CHAR function : 14.2.6. The TO_CHAR function (date conversion) and date ranges : 14.3.4. Using TO_CHAR to Create a Date Range TO_DATE function : 14.2.8. The TO_DATE function and FX modifier : 14.3.2. FX: Matching Formats Exactly TO_NUMBER function 14.2.9. The TO_NUMBER function 25.4.2. Zen and the Art of PL/SQL Tuning toggles, in packages : 1.7.3. Center All Development Around Packages TOO_MANY_ROWS exception : 8.3.1. Named System Exceptions tracing PL/SQL execution : 26. Tracing PL/SQL Execution transaction integrity 1.3.2. Improved Execution Authority and Transaction Integrity with PL/SQL 23.2. Transaction Integrity and Execute Authority TRANSACTION_BACKED_OUT exception : 8.3.1. Named System Exceptions transactions : 6.1. Transaction Management comments with : 6.1.1. The COMMIT Statement DBMS_TRANSACTION package for : C.15. DBMS_TRANSACTION read-only : 6.1.4. The SET TRANSACTION Statement TRANSLATE function 11.1.15. The TRANSLATE function 11.2.5. Verifying String Formats with TRANSLATE 25.4.2. Zen and the Art of PL/SQL Tuning trapping errors : (see exceptions) triggers dropping : 20.3.2. DROP: Dropping Views and Triggers size of : 25.3.7. Keep Database Triggers Small trigonometric functions : (see functions, numeric) TRIM procedure C.6.15. The TRIM procedure 19.6.8. TRIM [ (n ) ] removing collection elements with : 19.4.3.3. ...And what about TRIM? TRUE : (see Boolean literals) TRUNC function 12.1.6. The ROUND function 12.1.8. The TRUNC function 13.1.22. The TRUNC function truncating dates : 12.1.8. The TRUNC function truncating numbers : 13.1.22. The TRUNC function Trusted Oracle : About the Contents
tuning PL/SQL applications : 25. Tuning PL/SQL Applications access to compiled code : 25.2. Tuning Access to Compiled Code access to data : 25.3. Tuning Access to Your Data analyzing performance : 25.1. Analyzing Program Performance optimizing algorithms : 25.4. Tuning Your Algorithms TYPE ... RECORD statement : 9.4.1. Declaring Programmer-Defined Record TYPEs %TYPE attribute 1.7.2. Synchronize Program and Data Structures 4.5. Anchored Declarations 4.7.7. Use %TYPE When a Variable Represents a Column 15.6.1.1. %TYPE and %ROWTYPE TYPE declarations, in packages : 16.3. The Package Specification type modifiers 18.2.3. Adding Complex Data Structures REFs as : 18.4.2.2. REFs TYPE statement 9.4.1. Declaring Programmer-Defined Record TYPEs for tables : 10.4.1. Defining the Table TYPE types, data : (see datatypes)
Symbols | A | B | C | D | E | F | G | H | I | J | K | L | M | N | O | P | Q | R | S | T | U | V | W | Y | Z
The Oracle Library Navigation Copyright (c) 2000 O'Reilly & Associates. All rights reserved.
Symbols | A | B | C | D | E | F | G | H | I | J | K | L | M | N | O | P | Q | R | S | T | U | V | W | Y | Z
Index: U UID function : 13.3.7. The UID function UML (Unified Modeling Lanuage) : 18.1.4.3. Inheritance unconstrained datatypes : 4.6. Programmer-Defined Subtypes unconstrained declaration : (see parameters) undefined table rows : 10.5.2. Referencing an Undefined Row unhandled exceptions : (see exceptions) Unified Modeling Lanuage : 18.1.4.3. Inheritance UNIQUE_SESSION_ID function : C.12.9. The UNIQUE_SESSION_ID function UNIQUE_SESSION_NAME function : C.10.9. The UNIQUE_SESSION_NAME function unlocking records : 6.11.1. Releasing Locks with COMMIT unnamed constants : (see literals) UNPACK_MESSAGE procedure : C.10.10. The UNPACK_MESSAGE procedure UPDATE statement (see also DML statements) 4.2.3.2. The VARCHAR2 and VARCHAR datatypes 10.3. PL/SQL Tables and DML Statements THE function with : 19.5.1. The THE Pseudo-function WHERE CURRENT OF clause : 6.11.2. The WHERE CURRENT OF Clause UPPER function : 11.1.16. The UPPER function uppercase : (see case) USE_ROLLBACK_SEGMENT procedure : C.15.13. The USE_ROLLBACK_SEGMENT procedure user ID number of : 13.3.7. The UID function name of : 13.3.8. The USER function session : 13.3.9. The USERENV function USER function : 13.3.8. The USER function USER_DEPENDENCIES view, SQL : 23.6.1. Displaying Object Dependencies USER_EXPORT procedure : C.5.9. The USER_EXPORT procedure USER_OBJECT_SIZE view, SQL : 23.6.3. Analyzing the Size of PL/SQL Code USER_OBJECTS view, SQL : 23.6.2. Displaying Information About Stored Objects USER_SOURCE view, SQL : 23.6.4. Displaying and Searching Source Code USERENV function : 13.3.9. The USERENV function
utility modules C.16. DBMS_UTILITY 24.2.8. Leverage Existing Utilities -- Or Build Your Own for analyzing performance : 25.1. Analyzing Program Performance UTL_FILE package : C.17. UTL_FILE UTLBSTAT, UTLESTAT scripts : 25.1. Analyzing Program Performance
Symbols | A | B | C | D | E | F | G | H | I | J | K | L | M | N | O | P | Q | R | S | T | U | V | W | Y | Z
The Oracle Library Navigation Copyright (c) 2000 O'Reilly & Associates. All rights reserved.
Symbols | A | B | C | D | E | F | G | H | I | J | K | L | M | N | O | P | Q | R | S | T | U | V | W | Y | Z
Index: V validating foreign key entry (example) : 6.13.1. Validating Foreign Key Entry with Cursors modules : 23.3. Module Validation and Dependency Management parameters and assumptions : 22.2.4. Use Assertion Modules to Validate Parameters and Assumptions VALUE operator : 18.4.2.3. VALUE VALUE_ERROR exception : 8.3.1. Named System Exceptions VALUES list, functions in : 17.1. Looking at the Problem VARCHAR datatype : 4.2.3.2. The VARCHAR2 and VARCHAR datatypes VARCHAR2 datatype : 4.2.3.2. The VARCHAR2 and VARCHAR datatypes converting to CHAR : 4.2.3.2. The VARCHAR2 and VARCHAR datatypes converting to/from ROWID : 14.2.1. The CHARTOROWID function variable arrays, objects for : 18.1.2. Some Simple Examples variable-size arrays : (see VARRAYs) VARIABLE_VALUE procedure : C.14.16. The VARIABLE_VALUE procedure variables (see also datatypes) 1.4.3.2. Expanded set of datatypes for variables and constants 4. Variables and Program Data 4.2. Scalar Datatypes Boolean : (see Boolean variables) collection variables 19.2.2.1. Collection variables 19.4.1. Initializing Collection Variables combining scalars and aggregates : 17.8.2. Combining Scalar and Aggregate Values constants : (see literals) converting to named constants : 4.7.5. Convert Variables into Named Constants correlation variables : 18.4.2.2. REFs cursor : 1.4.5.2. Cursor variables cursor variables 6.2.1. Types of Cursors 6.12. Cursor Variables
restrictions on : 6.12.8. Cursor Variable Restrictions in cursors : 6.4.2. PL/SQL Variables in a Cursor declaring : 4.4. Variable Declarations in packages : 16.3. The Package Specification default values for : 4.4.3. Default Values fetching into : (see FETCH statement) global : 22.5.4. Avoid Global Variables and Data Structures package data as : 16.5.2. Global Within a Single Oracle Session IN OUT mode : 15.6.2.3. The IN OUT mode local objects for : 18.1.2. Some Simple Examples performance and : 25.4.3. Rely on Local Variables to Improve Performance names for (see also identifiers) 1.7.5. Structured Code and Other Best Practices naming 4.1. Identifiers 4.7.1. Establish Clear Variable Naming Conventions normalization of local : 4.5.1.2. Normalization of local variables NULL : 4.3. NULLs in PL/SQL package, stored functions and : 17.4. Restrictions on PL/SQL Functions in SQL in packages B.2.2. No Direct Stored Package Variable References reducing memory usage of : 25.2.5. Reducing Memory Usage of Package Variables recycling : 4.7.3. Avoid Recycling Variables removing unused : 4.7.6. Remove Unused Variables from Programs representing columns : 4.7.7. Use %TYPE When a Variable Represents a Column simplifying logic with : 4.7.9. Use Variables to Hide Complex Logic text : (see strings) variable arrays : 1.4.7.3. Variable arrays and nested tables VARRAYs (variable-size arrays) : 19.1. Types of Collections adding/removing elements of : 19.4.3. Adding and Removing Elements assigning values to elements : 19.4.2. Assigning Values to Elements: Index (Subscript) Considerations CAST pseudo-function for : 19.5.2. The CAST Pseudo-function defining : 19.2.1. Collections "In the Database" initializing : 19.4.1. Initializing Collection Variables integration of : 19.4.1.4. VARRAY integration verifying string format : 11.2.5. Verifying String Formats with TRANSLATE Version 1.1, PL/SQL : B. Calling Stored Procedures from PL/SQL Version 1.1 Version 2.0, PL/SQL : 1.4.3. PL/SQL Version 2.0 datatypes : B.2.1. No Server-Side PL/SQL Datatypes
RPCs : 23.4. Remote Procedure Calls stubs : B.1. Using Stubs to Talk to Server-Side PL/SQL Version 8.0, PL/SQL 1.4.7. PL/SQL Version 8.0 version 8 enhancements : 25.5. Overview of PL/SQL8 Enhancements versions of Oracle, objects and : 18.1.3. Comparison: Oracle8 Objects and Earlier Features versions, PL/SQL, working with multiple : 1.4.1. Working with Multiple Versions of PL/SQL views, dropping : 20.3.2. DROP: Dropping Views and Triggers views, object (see objects, object views) virtual REFs : 20.3.3. MAKE_REF: Returning a Virtual REF defining : 20.4.2.1. Defining virtual REFs DEREF function and : 20.4.2.4. DEREF: Interpreting a virtual REF storing : 20.4.3. Storage of Virtual REFs virtual tables : 6.2. Cursors in PL/SQL visibility of identifiers : 15.3.5. Scope and Visibility VSIZE function : 13.3.10. The VSIZE function
Symbols | A | B | C | D | E | F | G | H | I | J | K | L | M | N | O | P | Q | R | S | T | U | V | W | Y | Z
The Oracle Library Navigation Copyright (c) 2000 O'Reilly & Associates. All rights reserved.
Symbols | A | B | C | D | E | F | G | H | I | J | K | L | M | N | O | P | Q | R | S | T | U | V | W | Y | Z
Index: W WAITANY procedure : C.2.6. The WAITANY procedure WAITONE procedure : C.2.7. The WAITONE procedure weak REF CURSOR type : (see cursor variables) what parameter : (see DBMS_JOB) WHAT procedure : C.5.10. The WHAT procedure WHEN clause (see also exceptions) 8.2. The Exception Section WHEN OTHERS clause 8.2. The Exception Section 8.6. Handling Exceptions SQLCODE, SQLERRM functions in : 8.6.3. Using SQLCODE and SQLERRM in WHEN OTHERS Clause WHERE clause : 6.4.2. PL/SQL Variables in a Cursor stored functions and : 17.4. Restrictions on PL/SQL Functions in SQL WHERE CURRENT OF clause : 6.11.2. The WHERE CURRENT OF Clause WHILE loops 7.5. The WHILE Loop 7.7.2.2. EXIT and EXIT WHEN statements formatting : 3.3.2. Formatting Loops to fill table rows : 10.6.2. Iterative Assignment whitespace (see also formatting code) 2.2.2. Whitespace and Keywords 3.1.1. Revealing Logical Structure with Indentation 3.6.4. Maintain Indentation adding to strings : 11.1.8. The LPAD function and CHR function : 11.1.2. The CHR function in comments : 3.6.4. Maintain Indentation in CHAR variables : (see CHAR datatype) and justifying text : 11.2.3. Filling Text to Fit a Line stripping from strings
11.1.12. The RTRIM function 11.1.9. The LTRIM function suppressing : 14.3.1. FM: Suppressing Blanks and Zeros whole numbers : 4.2.1.1. Binary integer datatypes Windows NT, determining free disk space (example) : 21.1.1. Example: Determining Free Disk Space on Windows NT WNDS purity code : 17.5.1. The RESTRICT_REFERENCES Pragma WNPS purity code : 17.5.1. The RESTRICT_REFERENCES Pragma word wrap : 11.2.2. Implementing Word Wrap for Long Text WORK keyword : 6.1.1. The COMMIT Statement work queue, managing (example) : 6.13.2. Managing a Work Queue with SELECT FOR UPDATE wrap executable : 23.7.1. How to Encrypt Code WRAP_UP procedure : C.13.7. The WRAP_UP procedure wrapping code : (see encrypting code) WRITE procedure : C.6.16. The WRITE procedure write-only parameters : (see OUT mode)
Symbols | A | B | C | D | E | F | G | H | I | J | K | L | M | N | O | P | Q | R | S | T | U | V | W | Y | Z
The Oracle Library Navigation Copyright (c) 2000 O'Reilly & Associates. All rights reserved.
Symbols | A | B | C | D | E | F | G | H | I | J | K | L | M | N | O | P | Q | R | S | T | U | V | W | Y | Z
Index: Y year : (see date)
Symbols | A | B | C | D | E | F | G | H | I | J | K | L | M | N | O | P | Q | R | S | T | U | V | W | Y | Z
The Oracle Library Navigation Copyright (c) 2000 O'Reilly & Associates. All rights reserved.
Symbols | A | B | C | D | E | F | G | H | I | J | K | L | M | N | O | P | Q | R | S | T | U | V | W | Y | Z
Index: Z ZERO_DIVIDE exception : 8.3.1. Named System Exceptions
Symbols | A | B | C | D | E | F | G | H | I | J | K | L | M | N | O | P | Q | R | S | T | U | V | W | Y | Z
The Oracle Library Navigation Copyright (c) 2000 O'Reilly & Associates. All rights reserved.
Previous: 8.2 The Exception Section
Chapter 8 Exception Handlers
Next: 8.4 Determining Exception-Handling Behavior
8.3 Types of Exceptions There are four kinds of exceptions in PL/SQL: ●
●
●
●
Named system exceptions. Exceptions that have been given names by PL/SQL and raised as a result of an error in PL/SQL or RDBMS processing. Named programmer-defined exceptions. Exceptions that are raised as a result of errors in your application code. You give these exceptions names by declaring them in the declaration section. You then raise the exceptions explicitly in the program. Unnamed system exceptions. Exceptions that are raised as a result of an error in PL/SQL or RDBMS processing but have not been given names by PL/SQL. Only the most common errors are so named; the rest have numbers and can be assigned names with the special PRAGMA EXCEPTION_INIT syntax. Unnamed programmer-defined exceptions. Exceptions that are defined and raised in the server by the programmer. In this case, the programmer provides both an error number (between 20000 and -20999) and an error message, and raises that exception with a call to RAISE_APPLICATION_ERROR. That error, along with its message, is propagated back to the client-side application.
The system exceptions (both named and unnamed) are raised by PL/SQL whenever a program violates a rule in the RDBMS (such as "duplicate value in index") or causes a resource limit to be exceeded (such as "maximum open cursors exceeded"). Each of these RDBMS errors has a number associated with it. In addition, PL/SQL predefines names for some of the most commonly encountered errors.
8.3.1 Named System Exceptions The exceptions which are already given names by PL/SQL are declared in the STANDARD package in PL/SQL. You do not have to declare them in your own programs.[1] Each of the predefined exceptions is listed in Table 8.1 along with its Oracle error number, the value returned by a call to SQLCODE, and a brief description. SQLCODE is a PL/SQL built-in function that returns the status code of the last-executed statement. SQLCODE returns zero if the last statement executed without errors. In most, but not all, cases, the SQLCODE value is the same as the Oracle error code.
[1] If you do so, in fact, you will have declared your own local exception. It will not be raised when the internal error with that name occurs. Avoid declaring an exception with the same name as a predefined exception. Here is an example of how you might use the exceptions table. Suppose that your program generates an unhandled exception for error ORA-6511. Looking up this error, you find that it is associated with the CURSOR_ALREADY_OPEN exception. Locate the PL/SQL block in which the error occurs and add an exception handler for CURSOR_ALREADY_OPEN, as shown below: EXCEPTION WHEN CURSOR_ALREADY_OPEN THEN CLOSE my_cursor; END; Of course, you would be even better off analyzing your code to determine proactively which of the predefined exceptions might occur. Then you could decide which of those exceptions you want to handle specifically, which should be covered by the WHEN OTHERS clause, and which would best be left unhandled.
Table 8.1: Predefined Exceptions in PL/SQL Oracle Error/SQLCODE
Description
CURSOR_ALREADY_OPEN
You tried to OPEN a cursor that was already OPEN. You must CLOSE a cursor before you try to OPEN or re-OPEN it.
ORA-6511 SQLCODE= -6511
DUP_VAL_ON_INDEX ORA-00001 SQLCODE= -1
INVALID_CURSOR ORA-01001 SQLCODE= -1001
Your INSERT or UPDATE statement attempted to store duplicate values in a column or columns in a row which is restricted by a unique index. You made reference to a cursor that did not exist. This usually happens when you try to FETCH from a cursor or CLOSE a cursor before that cursor is OPENed.
INVALID_NUMBER ORA-01722 SQLCODE = -1722
LOGIN_DENIED ORA-01017 SQLCODE= -1017
NO_DATA_FOUND ORA-01403 SQLCODE= +100
NOT_LOGGED_ON ORA-01012 SQLCODE= -1012
PROGRAM_ERROR ORA-06501 SQLCODE= -6501
STORAGE_ERRORORA-06500 SQLCODE= -6500
PL/SQL executes a SQL statement that cannot convert a character string successfully to a number. This exception is different from the VALUE_ERROR exception, as it is raised only from within a SQL statement. Your program tried to log onto the Oracle RDBMS with an invalid username-password combination. This exception is usually encountered when you embed PL/SQL in a 3GL language. This exception is raised in three different scenarios: (1) You executed a SELECT INTO statement (implicit cursor) that returned no rows. (2) You referenced an uninitialized row in a local PL/SQL table. (3) You read past end of file with UTL_FILE package. Your program tried to execute a call to the database (usually with a DML statement) before it had logged into the Oracle RDBMS. PL/SQL encounters an internal problem. The message text usually also tells you to "Contact Oracle Support." Your program ran out of memory or memory was in some way corrupted.
TIMEOUT_ON_RESOURCEORA-00051 SQLCODE= -51
A timeout occurred in the RDBMS while waiting for a resource.
TOO_MANY_ROWSORA-01422 SQLCODE= -1422
A SELECT INTO statement returned more than one row. A SELECT INTO can return only one row; if your SQL statement returns more than one row you should place the SELECT statement in an explicit CURSOR declaration and FETCH from that cursor one row at a time.
TRANSACTION_BACKED_OUTORA-00061 SQLCODE= - The remote part of a transaction is 61 rolled back, either with an explicit ROLLBACK command or as the result of some other action. VALUE_ERRORORA-06502 SQLCODE= -6502
PL/SQL raises the VALUE_ERROR whenever it encounters an error having to do with the conversion, truncation, or invalid constraining of numeric and character data. This is a very general and common exception. If this same type of error is encountered in a SQL DML statement within a PL/SQL block, then the INVALID_NUMBER exception is raised.
ZERO_DIVIDEORA-01476 SQLCODE= -1476
Your program tried to divide by zero.
8.3.2 Named Programmer-Defined Exceptions The exceptions that PL/SQL has declared in the STANDARD package cover internal or systemgenerated errors. Many of the problems a user will encounter (or cause) in an application, however, are specific to that application. Your program might need to trap and handle errors such as "negative balance in account" or "call date cannot be in the past." While different in nature from "division by
zero," these errors are still exceptions to normal processing and should be handled gracefully by your program. One of the most useful aspects of the PL/SQL exception handling model is that it does not make any structural distinction between internal errors and application-specific errors. Once an exception is raised, it can and should be handled in the exception section, regardless of the type or source of error. Of course, to handle an exception, you must have a name for that exception. Because PL/SQL cannot name these exceptions for you (they are specific to your application), you must do so yourself by declaring an exception in the declaration section of your PL/SQL block. You declare an exception by listing the name of the exception you want to raise in your program, followed by the keyword EXCEPTION, as follows: exception_name EXCEPTION; The following declaration section of the calc_annual_sales contains three programmer-defined exception declarations: PROCEDURE calc_annual_sales (company_id_in IN company.company_id%TYPE) IS invalid_company_id EXCEPTION; no_sales_for_company EXCEPTION; negative_balance EXCEPTION; duplicate_company BOOLEAN; BEGIN ... body of executable statements ... EXCEPTION WHEN invalid_company_id THEN ... WHEN no_sales_for_company THEN ... WHEN negative_balance THEN ... END; The names for exceptions are similar in format to (and "read" just like) Boolean variable names, but can be referenced in only two ways: ●
In a RAISE statement in the execution section of the program (to raise the exception), as in:
RAISE no_sales_for_company; ●
In the WHEN clauses of the exception section (to handle the raised exception), as in: WHEN no_sales_for_company THEN
8.3.3 Unnamed System Exceptions What do you do when you want to trap an internal error raised by PL/SQL or the SQL engine, but it is not one of the lucky errors that have been given a predefined name? Although this error is identified only by its internal error number, exception handlers need a name by which they can check for a match. Sure, you can always use the WHEN OTHERS clause to simply catch any exceptions not previously handled. (This is covered in detail in Section 8.6.3, "Using SQLCODE and SQLERRM in WHEN OTHERS Clause".) In many cases, however, you will want to trap specific errors in a way that clearly documents and highlights them in your code. To do this, you assign your own name to the Oracle or PL/SQL error that might be raised in your program, and then write a specific exception handler for that custom-named exception. 8.3.3.1 The EXCEPTION_INIT pragma You can use a compiler construct called a pragma to associate a name with an internal error code. A pragma (introduced in Chapter 2, PL/SQL Language Fundamentals) is a special instruction to the compiler that is processed at compile time instead of at runtime. A pragma called EXCEPTION_INIT instructs the compiler to associate or initialize a programmer-defined exception with a specific Oracle error number. With a name for that error, you can then raise this exception and write a handler which will trap that error. While in most cases you will leave it to Oracle to raise these system exceptions, you could also raise them yourself. The pragma EXCEPTION_INIT must appear in the declaration section of a block, after the declaration of the exception name used in the pragma, as shown below: DECLARE exception_name EXCEPTION; PRAGMA EXCEPTION_INIT (exception_name, error_code_literal); BEGIN where exception_name is the name of an exception and error_code_literal is the number of the Oracle error (including the minus sign, if the error code is negative, as is almost always the case). In the following program code, I declare and associate an exception for this error: ORA-2292 violated integrity constraining (OWNER. CONSTRAINT) -
child record found. This error occurs if I try to delete a parent record while there are child records still in that table. A child record is a record with a foreign key reference to the parent table: PROCEDURE delete_company (company_id_in IN NUMBER) IS /* Declare the exception. */ still_have_employees EXCEPTION; /* Associate the exception name with an error number. */ PRAGMA EXCEPTION_INIT (still_have_employees, -2292); BEGIN /* Try to delete the company. */ DELETE FROM company WHERE company_id = company_id_in; EXCEPTION /* If child records were found, this exception is raised! */ WHEN still_have_employees THEN DBMS_OUTPUT.PUT_LINE (' Please delete employees for company first.'); END; When you use EXCEPTION_INIT, you must supply a literal number for the second argument of the pragma call. By explicitly naming this system exception, the purpose of the exception handler is selfevident. The EXCEPTION_INIT pragma improves the readability of your programs by assigning names to otherwise obscure error numbers. You can employ the EXCEPTION_INIT pragma more than once in your program. You can even assign more than one exception name to the same error number.
8.3.4 Unnamed Programmer-Defined Exceptions The final type of exception is the unnamed, yet programmer-defined exception. This kind of exception occurs when you need to raise an application-specific error from within the server and communicate this error back to the client application process. This scenario is more common than you might at first imagine. For example, even when you run all your Oracle software in a single hardware environment (such as a character-based SQL*Forms applications running on UNIX against an Oracle server on the same UNIX platform), you still have a separation between your client (SQL*Forms screen) and your server (the RDBMS). You will trap some, perhaps most, application-specific errors on the client side. On the other hand,
the Oracle7 architecture allows you to embed many of your business rules directly into your database structure, using database triggers, constraints, and stored procedures. In many cases, you will want to let the RDBMS trap and reject invalid database actions. To do this, you need a way to identify application-specific errors and return information about those error back to the client. This kind of error communication is illustrated in Figure 8.2. Figure 8.2: Error communication from server to client
I have called this type of exception "unnamed" and "programmer-defined." The programmer-defined aspect should be clear: because the error is application-specific, you cannot expect PL/SQL to have already defined it for you. The reason this type of exception is also unnamed is that you cannot name or declare an exception within a server-based program or database trigger and have the client-side tool handle that named exception. This identifier simply doesn't cross the great divide between client and server. To get around this problem, Oracle provides a special procedure to allow communication of an unnamed, yet programmer-defined, server-side exception: RAISE_APPLICATION_ERROR. (The use of this procedure and exception type is discussed in Section 8.7, "Client-Server Error Communication" later in this chapter.) The specification for this procedure is as follows: PROCEDURE RAISE_APPLICATION_ERROR (error_number_in IN NUMBER, error_msg_in IN VARCHAR2); where error_number_in is the error number you have assigned to this error. The error_msg_in argument is the message that will be sent back with the error code to the client program.
Previous: 8.2 The Exception Section
Oracle PL/SQL Programming, 2nd Edition
Next: 8.4 Determining Exception-Handling Behavior
8.2 The Exception Section
Book Index
The Oracle Library Navigation Copyright (c) 2000 O'Reilly & Associates. All rights reserved.
8.4 Determining ExceptionHandling Behavior
Previous: 8.1 Why Exception Handling?
Chapter 8 Exception Handlers
Next: 8.3 Types of Exceptions
8.2 The Exception Section A PL/SQL block (of which procedures, functions, and anonymous blocks are all instances) consists of up to four parts: the header, declaration section, execution section, and exception section, as shown in the following anonymous block: DECLARE ... declarations ... BEGIN ... executable statements ... [ EXCEPTION ... exception handlers ... ] END; When an exception is raised within the execution section of a PL/SQL block, control passes to the exception section. PL/SQL then scans through the exception handlers to see if that exception is handled. The syntax for an exception section follows: EXCEPTION WHEN exception_name [ OR exception_name ... ] THEN <executable statements> END; You can have multiple exception handlers in a single exception section. The exception handlers are structured much like a conditional CASE statement, as shown below: The Exception Section
An English-like Translation
EXCEPTION WHEN NO_DATA_FOUND THEN executable_statements1;
If the NO_DATA_FOUND exception was raised, then execute the first set of statements.
WHEN payment_overdue THEN executable_statements2;
If the payment is overdue, then execute the second set of statements.
WHEN OTHERS THEN executable_statements3; END;
If any other exception is encountered, then execute the third set of statements.
An exception is handled if an exception that is named in a WHEN clause matches the exception that was raised. Notice that the WHEN clause traps errors only by exception name, not by error codes. If a match is found, then the executable statements associated with that exception are run. If the exception that has been raised is not handled or does not match any of the named exceptions, the executable statements associated with the WHEN OTHERS clause -- if present -- will be run. The WHEN OTHERS clause is optional; if it is not present, then any unhandled exception is immediately raised in the enclosing block, if any. If the exception is not handled by any PL/SQL block, then the error number and message are presented directly to the user of the application. The exception is, in other words, unhandled and it disrupts the execution of the application.
Previous: 8.1 Why Oracle PL/SQL Exception Handling? Programming, 2nd Edition 8.1 Why Exception Handling? Book Index The Oracle Library Navigation Copyright (c) 2000 O'Reilly & Associates. All rights reserved.
Next: 8.3 Types of Exceptions 8.3 Types of Exceptions
Previous: 7.7 Tips for PL/ SQL Loops
Chapter 8
Next: 8.2 The Exception Section
8. Exception Handlers Contents: Why Exception Handling? The Exception Section Types of Exceptions Determining Exception-Handling Behavior Raising an Exception Handling Exceptions Client-Server Error Communication NO_DATA_FOUND: Multipurpose Exception Exception Handler as IF Statement RAISE Nothing but Exceptions In the PL/SQL language, errors of any kind are treated as exceptions -- situations that should not occur -- in your program. An exception can be one of the following: ● ● ●
An error generated by the system (such as "out of memory" or "duplicate value in index") An error caused by a user action A warning issued by the application to the user
PL/SQL traps and responds to errors using an architecture of exception handlers. The exceptionhandler mechanism allows you to cleanly separate your error processing code from your executable statements. It also provides an event-driven model, as opposed to a linear code model, for processing errors. In other words, no matter how a particular exception is raised, it is handled by the same exception handler in the exception section. When an error occurs in PL/SQL, whether a system error or an application error, an exception is raised. The processing in the current PL/SQL block's execution section halts and control is transferred to the separate exception section of your program, if one exists, to handle the exception. You cannot return to that block after you finish handling the exception. Instead, control is passed to the enclosing block, if any.
Figure 8.1 illustrates how control is transferred to the exception section when an exception is raised. Figure 8.1: Exception handling architecture
8.1 Why Exception Handling? It is a sad fact of life that most programmers never take the time to properly bullet-proof their programs. Instead, wishful thinking often reigns. Most of us find it hard enough -- and more than enough work -- to simply write the code that implements the positive aspects of an application: maintaining customers, generating invoices, etc. It is devilishly difficult from both a psychological standpoint and a resources perspective to focus on the negative side of our life: what happens when the user presses the wrong key? If the database is unavailable, what should I do? As a result, we write applications that often assume the best of all possible worlds, hoping that our programs are bug-free, that users will enter only the correct data in only the correct fashion, and that all systems (hardware and software) will always be a "go." Of course, harsh reality dictates that no matter how hard you try, there will always be one more bug in your application. And your users will always find just the right sequence of keystrokes it takes to make a screen implode. The situation is clear: either you spend the time up front to properly debug and bulletproof your programs, or you will fight an unending series of rear-guard battles, taking frantic calls from your users and putting out the fires. You know what you should do. Fortunately, PL/SQL offers a powerful and flexible way to trap and handle errors in your programs. It is entirely feasible within the PL/SQL language to build an application which fully protects the user and the database from errors.
The exception handler model offers the following advantages: ●
●
●
Event-driven handling of errors. As we've mentioned, PL/SQL exception handling follows an event-driven rather than a linear code model. No matter how a particular exception is raised, it is handled by the same exception handler in the exception section. You do not have to check repeatedly for a condition in your code, but instead can insert an exception for that condition once in the exception section and be certain that it will be handled throughout that block (and all of its enclosing blocks). Clean separation of error-processing code. With the exception-handling model, whenever an exception is raised, program control transfers completely out of the normal execution sequence and into the exception section. Instead of placing error-handling logic throughout different sections of your program, you can consolidate all of this logic into a single, separate section. Furthermore, if you need to add new exceptions in your program (perhaps you overlooked a possible problem, or a new kind of system error has been identified), you do not have to figure out where in your executable code to put the error-handling logic. Simply add another exception handler at the bottom of the block. Improved reliability of error handling. It is quite difficult for errors to go undetected with the PL/SQL error-handling model. If there is a handler, then that exception will be dealt with in the current block or in an enclosing block. Even if there is no explicit handler for that error, normal code execution will still stop. Your program cannot simply "work through" an error -unless you explicitly organize your code to allow this.
There is no avoiding the fact that if you want to trap errors in your PL/SQL programs you will have to write some additional code. The exception handler architecture, however, minimizes the amount of code you will need to write, and offers the possibility of guarding against all problems that might arise in your application. The following sections look at how you define, raise, and handle exceptions in PL/SQL.
Previous: 7.7 Tips for PL/ SQL Loops 7.7 Tips for PL/SQL Loops
Oracle PL/SQL Programming, 2nd Edition Book Index
The Oracle Library Navigation Copyright (c) 2000 O'Reilly & Associates. All rights reserved.
Next: 8.2 The Exception Section 8.2 The Exception Section
Previous: 7.6 Managing Loop Execution
Chapter 7 Loops
Next: 8. Exception Handlers
7.7 Tips for PL/SQL Loops Loops are very powerful and useful constructs, but they are among the most complicated control structures in PL/SQL. The tips in this section will help you select the most efficient and easily maintained loops for your programs.
7.7.1 Naming Loop Indexes How would you like to try to understand -- much less maintain -- code that looks like this? FOR i IN start_id .. end_id LOOP FOR j IN 1 .. 7 LOOP FOR k IN 1 .. 24 LOOP build_schedule (i, j, k); END LOOP; END LOOP; END LOOP; It is hard to imagine that someone would write code based on such generic integer variable names (right out of Algebra 101), yet it happens all the time. The habits we pick up in our earliest days of programming have an incredible half-life. Unless you are constantly vigilant, you will find yourself writing the most abominable code. In this case, the solution is simple: use variable names for the loop indexes that are meaningful and therefore self-documenting: FOR focus_account IN start_id .. end_id LOOP FOR day_in_week IN 1 .. 7 LOOP FOR month_in_biyear IN 1 .. 24 LOOP build_schedule (focus_account, day_in_week,
month_in_biyear); END LOOP; END LOOP; END LOOP; Well, that cleared things up! Before I substituted the meaningless loop index names, I would wager that you were fairly sure the statement: FOR j IN 1 .. 7 meant that "j" stood for the seven days of the week. And I bet further that you were equally confident that: FOR k IN 1 .. 24 meant that "k" represented the hours in a day. Now that I have provided descriptive names for those index variables, however, you discover that the innermost loop actually spanned two sets of twelve months (12 × 2 = 24). Your deduction about "k", while reasonable, was wrong, but it would have been completely impossible to determine this without looking at the build_schedule code. Given PL/SQL's ability to hide information within packages, this code might not even be available. Software programmers should not have to make Sherlock Holmes-like deductions about the meaning of the start and end range values of the innermost FOR loops in order to understand their purpose. Use names that self-document the purposes of variables and loops. That way other people will understand your code and you will remember what your own code does when you review it three months later.
7.7.2 The Proper Way to Say Goodbye No matter what kind of loop you are using, there is always only one entry point into the loop: the first executable statement following the LOOP keyword. Your loops should also have just one way of leaving the loop. The method of exit, furthermore, should be compatible with the type of loop you use. The following tips will help you write well-structured and easily maintained loops. 7.7.2.1 Premature FOR loop termination The syntax of the FOR loop states your intent explicitly and should only be a FOR loop if you know in advance how many times the loop needs to execute. For example, the following loop is very clear: FOR month_count IN 1 .. 12 LOOP analyze_month (month_count);
END LOOP; It states: "I am going to execute the analyze_month procedure 12 times, once for each month in the year." Straightforward and easy to understand. Now take a look at the next numeric FOR loop: FOR year_count IN 1 .. years_displayed LOOP IF year_count > 10 AND :store.status = 'CLOSED' THEN EXIT; END IF; analyze_month (month_count); END LOOP; In this case, the loop boundary states: "Run the loop for the number of years displayed in the form." Yet in the body of the loop, an IF statement allows a premature termination of the loop. If the year count (the loop index) exceeds 10 and the current store status is CLOSED, then an EXIT statement is issued and the loop halts. This approach is very unstructured and contradictory. The loop boundary states one thing, but the loop body executes something very different. You should always let a FOR loop (whether numeric or cursor) complete its stated number of iterations. If you do need to conditionally halt loop execution, you should choose either an infinite or a WHILE loop. The above FOR loop could, for example, be easily recoded as follows: FOR year_count IN 1 .. LEAST (years_displayed, 11) LOOP analyze_month (month_count); END LOOP; Similar guidelines apply to the infinite and WHILE loop, as I explore in the next sections. 7.7.2.2 EXIT and EXIT WHEN statements Neither the FOR loop nor the WHILE loop should use the EXIT and EXIT WHEN statements. You have already seen why this is so in FOR loops. Consider the following WHILE loop: WHILE more_records LOOP NEXT_RECORD; EXIT WHEN :caller.name IS NULL; END LOOP;
In this case, even though my loop boundary indicates that the body should execute until more_records evaluates to FALSE, the EXIT WHEN in the loop body bypasses that condition. Instead of using EXITs in your WHILE loop, you should always rely exclusively on your loop condition to determine whether the looping should continue. The previous WHILE loop can be redesigned as follows: WHILE more_records LOOP NEXT_RECORD; more_records := :caller.name IS NOT NULL; END LOOP; 7.7.2.3 RETURN statement The RETURN statement will cause instant termination of a function and return the specified value back to the calling program. Never use a RETURN statement inside a loop. Unfortunately, such things have been known to happen. In the following example of terrifically poor programming practice (taken from an Oracle Corporation reference manual, I am sorry to say), the FOR loop is interrupted -- not with an EXIT, which would be unstructured enough, but with a RETURN statement: BEGIN the_rowcount := Get_Group_Row_Count( rg_id ); FOR j IN 1..the_rowcount LOOP col_val := Get_Group_Char_Cell( gc_id, j ); IF UPPER(col_val) = UPPER(the_value) THEN RETURN j; END IF; END LOOP; END; The author of this program was in a big hurry to return to the calling program! Once again, if the loop should be conditionally terminated, do not use a FOR loop. Instead, use a WHILE or infinite loop and then issue the RETURN after the loop is completed. The following code replaces the unstructured IF statement shown above:
BEGIN /* Initialize the loop boundary variables. */ row_index := 0; the_rowcount := Get_Group_Row_Count (rg_id); /* Use a WHILE loop. */ WHILE row_index <= the_rowcount AND match_not_found LOOP row_index := row_index + 1; col_val := Get_Group_Char_Cell (gc_id, row_index); match_not_found := UPPER (col_val) != UPPER (the_value) END LOOP; /* Now issue the RETURN statement. */ RETURN row_index; END; 7.7.2.4 GOTO statements inside a loop The same reasons for avoiding a RETURN apply to the GOTO statement. If you use a GOTO to exit from a loop, you bypass the logical structure of the loop. You end up with code that is very difficult to trace, debug, fix, and maintain.
7.7.3 Avoiding the Phony Loop As I have stated previously, you should not use a numeric FOR loop if you cannot specify in a range scheme of lowest and highest bounds the number of times the loop must execute. Just because you know the number of iterations of some code, however, doesn't mean that you should use a loop. I have run across a number of programs which execute variations on this kind of FOR loop: FOR i IN 1 .. 2 LOOP IF i = 1 THEN give_bonus (president_id, 2000000); ELSIF i = 2 THEN give_bonus (ceo_id, 5000000); END IF; END LOOP;
This loop provides hefty bonuses to the president and CEO of a company that just went deep into debt to acquire a competitor. I need to use the loop so the code executes twice to make sure both the president and CEO receive their just compensation. Right? Wrong. This code should not be inside a loop. It does not need iteration to perform its job; the LOOP syntax just confuses the issue. The two sections within the IF-THEN-ELSE construct in the previous example both need to be executed all the time; this is straight sequential code and should be written as follows: give_bonus (president_id, 2000000); give_bonus (ceo_id, 5000000);
7.7.4 PL/SQL Loops Versus SQL Processing One of the indicators that a numeric FOR loop is being used incorrectly is that the loop index is not used for anything but traffic control inside the loop. The actual body of executable statements completely ignores the loop index. When that is the case, there is a good chance that you don't need the loop at all. When should you use standard SQL to accomplish your task and when should you rely on PL/SQL loops? Sometimes the choice is clear: if you do not need to interact with the database, then there is clearly no need for SQL. In addition, SQL can't always provide the necessary flexibility to get the job done. Conversely, if you are performing a single record insert into a table then there is no need for a loop. Often, however, the choice is less obvious. For example, a SELECT statement queries one or more rows from the database. A cursor FOR loop also queries rows from the database based on a SELECT statement. In fact, PL/SQL and native SQL often can both accomplish the task at hand. Given that fact, you will need to choose your implementation according to more subtle issues like performance and maintainability of code. Before we look at some examples of scenarios which call for one or the other approach, let's review the difference between the implicit looping of the SQL set-at-a-time approach and the PL/SQL loop. SQL statements such as SELECT, UPDATE, INSERT, and DELETE work on a set of data. That set (actually, a collection of rows from a table or tables) is determined by the WHERE clause (or lack thereof) in the SQL statement. SQL derives much of its power and effectiveness as a database language from this set-at-a-time processing approach. There is, however, a drawback, as I mentioned earlier: SQL often does not give you the flexibility you might need to handle individual records and specialized logic which must be applied differently to different records. The PL/SQL cursor offers the ability to access a record at a time and to take action based on the contents of that specific record. It is not always clear, however, which language component would best fit the needs of the moment. I have seen a number of programs where developers went overboard in their drive to PL/SQL-ize the SQL access to their data. This happens most frequently when using a cursor FOR loop.
The PL/SQL block in the code below moves checked-out pets from the pet hotel occupancy table to the pets_history table using a cursor FOR loop. For each record fetched (implicitly) from the cursor (representing a pet who has hit the road), the body of the loop first inserts a record into the pet_history table and then deletes the record from the occupancy table: DECLARE CURSOR checked_out_cur IS SELECT pet_id, name, checkout_date FROM occupancy S checkout_date IS NOT NULL; BEGIN FOR checked_out_rec IN checked_out_cur LOOP INSERT INTO occupancy_history (pet_id, name, checkout_date) VALUES (checked_out_rec.pet_id, checked_out_rec. name, checked_out_rec.checkout_date); DELETE FROM occupancy WHERE pet_id = checked_out_rec.pet_id; END LOOP; END; This will work just fine. But do we really need to use a cursor FOR loop to accomplish this task? Suppose 20 animals checked out today. This block of code will then perform 20 distinct inserts and 20 distinct deletes. The same code can be written completely within the SQL language as shown below: INSERT INTO occupancy_history (pet_id, name, checkout_date) SELECT pet_id, name, checkout_date FROM occupancy WHERE checkout_date IS NOT NULL; DELETE FROM occupancy WHERE checkout_date IS NOT NULL; Here, a single insert (making use of the INSERT...SELECT syntax) and a single delete (which now checks for the checkout_date and not the employee_id) accomplish the transfer of the data to the history table. This reliance on native SQL, without the help of PL/SQL, allows you to take full advantage of array processing. It significantly reduces network traffic in a client-server environment because only two SQL statements (instead of 40) are passed to the RDBMS. The cursor FOR loop was not really needed here; the body of the loop did not perform any procedural logic which could not be handled by SQL itself. If, on the other hand, the program needed to selectively reject records for the transfer, or otherwise perform procedural logic not possible within SQL, then either the cursor FOR loop or a WHILE loop would make sense.
Previous: 7.6 Managing Oracle PL/SQL Loop Execution Programming, 2nd Edition 7.6 Managing Loop Execution Book Index The Oracle Library Navigation Copyright (c) 2000 O'Reilly & Associates. All rights reserved.
Next: 8. Exception Handlers 8. Exception Handlers
Previous: 7.5 The WHILE Loop
Chapter 7 Loops
Next: 7.7 Tips for PL/SQL Loops
7.6 Managing Loop Execution I've explained how to construct the different kinds of PL/SQL loops. The topics in this section address the following nuances of loop execution: Labels You can associate a label with a loop and use that label to increase your control over loop execution. Scope The loop boundary creates a scope similar to that of a PL/SQL block. Termination There is only one way to enter a loop, but a number of ways you can exit your loop.
7.6.1 Loop Labels You can associate a name with a loop by using a label. A loop label in PL/SQL has the following format: <> where label_name is the name of the label. (By the way, this is the same format used for GOTO labels.) In order to associate a name with a loop, however, the loop label must appear just before the LOOP statement as shown below: <> FOR emp_rec IN emp_cur LOOP ... END LOOP;
The label can also appear optionally after the END LOOP reserved words, as the following example demonstrates: <> WHILE year_number <= 1995 LOOP <<month_loop>> FOR month_number IN 1 .. 12 LOOP ... END LOOP month_loop; END LOOP year_loop; By providing a label for a loop, you give that loop a name. This allows you to use dot notation to refer to loop-related variables, such as the FOR loop index. In the following example of nested FOR loops, I qualify my reference to the year_number index with the loop name: <> WHILE year_number <= 1995 LOOP <<month_loop>> FOR month_number IN 1 .. 12 LOOP IF year_loop.year_number = 1900 THEN ... END IF; END LOOP month_loop; END LOOP year_loop; 7.6.1.1 Benefits of loop labels The loop label is useful in two particular situations: ●
●
When you have written a loop whose code length exceeds a single page, use a loop label to tie the end of the loop back explicitly to its start. This visual tag will make it easier for a developer to maintain and debug the program. Without the loop label, it can be very difficult to keep track of which LOOP goes with which END LOOP. When you have nested loops, you can use the label to both improve readability and increase control over the execution of your loops. This capability is explored in the next section.
7.6.1.2 Loop termination using labels You can affect loop execution by adding a loop label after the EXIT keyword in the EXIT statement of a loop, as follows: EXIT loop_label; EXIT loop_label WHEN condition; When you specify a loop label with the EXIT statement, PL/SQL terminates the specified loop. Consider the last example with nested year and month loops. You might encounter a condition in which both loops should be immediately terminated. The usual, unlabeled EXIT statement inside the month loop would simply halt the month processing for the current year. The year loop would, however, continue its iterations. If the EXIT statement includes the year_loop label, both loops will halt execution: <> WHILE year_number <= 1995 LOOP <<month_loop>> FOR month_number IN 1 .. 12 LOOP calc_totals (year_number, month_number, termination_condition); /* If the termination condition is TRUE exit ALL loops. */ EXIT year_loop WHEN termination_condition; END LOOP month_loop; END LOOP year_loop; In this way, the loop labels offer you added control. Nevertheless, don't use this variation of the EXIT WHEN statement unless absolutely necessary. This kind of EXIT is very unstructured, which makes it hard to test, debug, and maintain. If your loops do have exception conditions, you should instead code them into the boundary of the loop or allow the exception section to handle them. In other words, if you need to conditionally terminate your loop, then you should not use a FOR loop.
7.6.2 Loop Scope A PL/SQL block establishes a scope for all locally-declared variables. Outside of the block, those
variables do not exist. A similar kind of scope is created in the body of a loop. 7.6.2.1 Scope in FOR loops In both numeric and cursor FOR loops, the scope of the loop index is restricted to the body of the loop. You cannot make reference to this implicitly declared variable in code before or after the loop. If you declare a variable of the same name as the loop index, PL/SQL considers that to be a different variable. It will not be used within the loop. The loop index always takes precedence over a variable of the same name declared outside the scope of the loop. Suppose you have the following code: PROCEDURE calc_revenue (year_in IN NUMBER) IS month_number NUMBER (2) := 6; BEGIN FOR month_number IN 1 .. 12 LOOP calc_rev_for_month (month_number); END LOOP; END; The assignment of 6 to month_number in the declaration section has no impact whatsoever on the loop. Within the FOR loop, any reference to month_number is evaluated according to the current value of the loop index. If you insist on declaring a variable whose name is the same as that of a loop index, you can use dot notation to qualify your references to these variables. In the following example I have a duplicate use of the month_number identifier: PROCEDURE calc_revenue (year_in IN NUMBER) IS month_number NUMBER (2) := 6; BEGIN FOR month_number IN 1 .. 12 LOOP IF calc_revenue.month_number < 6 THEN ... END IF; calc_rev_for_month (month_number); END LOOP; END; Inside the loop, my first reference to month_number is qualified by the procedure name
(calc_revenue.month_number). As a result, the compiler can obtain the right value for that month_number (6), while also using the loop index value in the call to calc_rev_for_month. Of course, you can and should avoid this kind of confusion by using distinct names for your variables and loop indexes. 7.6.2.2 Scope with labels If you define a label for a loop, then this label can be used to qualify the name of identifiers (loop indexes and locally-declared variables) inside the loop. Once the loop has terminated, you cannot use the loop label to qualify identifiers. The scope of that label, in other words, is the boundary and body of the loop. In the following example, I created two nested loops, both of which use a loop index named date_number. (Warning! Do not try this at home. Although it will compile, it can be dangerous to your sanity.) <> FOR date_number IN 1994 .. 1999 LOOP <<month_loop>> FOR date_number IN 1 .. 12 LOOP IF year_loop.date_number = 1994 AND date_number = 1 THEN first_month_processing; END IF; END LOOP month_loop; END LOOP year_loop; The IF statement references the date_number loop index of both the outer and inner loops by prefixing the outer loop's name to the first reference to date_number, I tell the compiler which variable I want it to use. Again, you would be much better off simply changing the name of one or both of the loop indexes; date_number is much too vague a name for either of these loops.
Previous: 7.5 The WHILE Loop 7.5 The WHILE Loop
Oracle PL/SQL Programming, 2nd Edition Book Index
The Oracle Library Navigation Copyright (c) 2000 O'Reilly & Associates. All rights reserved.
Next: 7.7 Tips for PL/SQL Loops 7.7 Tips for PL/SQL Loops
Previous: 7.4 The Cursor FOR Loop
Chapter 7 Loops
Next: 7.6 Managing Loop Execution
7.5 The WHILE Loop The WHILE loop is a conditional loop that continues to execute as long as the Boolean condition defined in the loop boundary evaluates to TRUE. Because the WHILE loop execution depends on a condition and is not fixed, use a WHILE loop if you don't know ahead of time the number of times a loop must execute. Here is the general syntax for the WHILE loop: WHILE LOOP <executable statement(s)> END LOOP; where is a Boolean variable or an expression that evaluates to a Boolean value of TRUE, FALSE, or NULL. Each time an iteration of the loop's body is to be executed, the condition is checked. If it evaluates to TRUE, then the body is executed. If it evaluates to FALSE or to NULL, then the loop terminates and control passes to the next executable statement following the END LOOP statement. The following table summarizes the properties of the WHILE loop: Property
Description
How the loop is terminated
The WHILE loop terminates when the Boolean expression in its boundary evaluates to FALSE or NULL.
When the test for termination takes place
The test for termination of a WHILE loop takes place in the loop boundary. This evaluation occurs prior to the first and each subsequent execution of the body. The WHILE loop, therefore, cannot be guaranteed to always execute its loop even a single time.
Reason to use this loop
Use the WHILE loop when: ●
● ●
You are not sure how many times you must execute the loop body, and You will want to conditionally terminate the loop, and You don't have to execute the body at least one time.
The WHILE loop's condition is tested at the beginning of the loop's iteration, before the body of the loop is executed. There are two consequences to this pre-execution test: ●
●
All the information needed to evaluate the condition must be set before the loop is executed for the first time. It is possible that the WHILE loop will not execute even a single time.
7.5.1 The Infinite WHILE Loop One of the dangers of the simple loop is that it could be an infinite loop if the body of the loop never executes an EXIT statement. While this is less of a problem with the WHILE loop, you should be aware that it is certainly possible to construct a WHILE loop that is syntactically equivalent to the infinite LOOP. The most obvious version of an infinite WHILE loop is the following: WHILE TRUE LOOP <executable statement(s)> END LOOP; Sometimes, however, an infinite WHILE loop can be disguised by poor programming techniques. The following WHILE loop will terminate only when end_of_analysis is set to TRUE: WHILE NOT end_of_analysis LOOP perform_analysis; get_next_record; IF analysis_cursor%NOTFOUND AND next_analysis_step IS NULL THEN
end_of_analysis := TRUE; END IF; END LOOP; In this WHILE loop, the end_of_analysis Boolean variable is set to TRUE only if the analysis_cursor fetches no data and we are at the last step of the analysis. Unfortunately, both the cursor and the next_analysis_step variable are completely invisible in the loop itself. How is next_analysis_step set? Where is the cursor declared? How is a record fetched? This is a very dangerous way to structure code because if you do fall into an infinite loop, the information you need to resolve the problem is not readily available.
Previous: 7.4 The Cursor FOR Loop 7.4 The Cursor FOR Loop
Oracle PL/SQL Next: 7.6 Managing Loop Programming, 2nd Edition Execution 7.6 Managing Loop Execution Book Index
The Oracle Library Navigation Copyright (c) 2000 O'Reilly & Associates. All rights reserved.
Previous: 7.3 The Numeric FOR Loop
Chapter 7 Loops
Next: 7.5 The WHILE Loop
7.4 The Cursor FOR Loop A cursor FOR loop is a loop that is associated with (actually defined by) an explicit cursor or a SELECT statement incorporated directly within the loop boundary. Use the cursor FOR loop whenever (and only if) you need to fetch and process each and every record from a cursor, which is a high percentage of the time with cursors. The cursor FOR loop is one of my favorite PL/SQL features. It leverages fully the tight and effective integration of the procedural constructs with the power of the SQL database language. It reduces the volume of code you need to write to fetch data from a cursor. It greatly lessens the chance of introducing loop errors in your programming -- and loops are one of the more error-prone parts of a program. Does this loop sound too good to be true? Well, it isn't -- it's all true! Here is the basic syntax of a cursor FOR loop: FOR record_index IN cursor_name LOOP <executable statement(s)> END LOOP; where record_index is a record declared implicitly by PL/SQL with the %ROWTYPE attribute against the cursor specified by cursor_name. The following table summarizes the properties of the cursor FOR loop where record_index is a record declared implicitly by PL/SQL with the %ROWTYPE attribute against the cursor specified by cursor_name: Property
Description
How the loop is terminated
The cursor FOR loop terminates unconditionally when all of the records in the associated cursor have been fetched. You can also terminate the loop with an EXIT statement, but this is not recommended.
When the test for termination takes place After each execution of the loop body, PL/SQL performs another fetch. If the %NOTFOUND attribute of the cursor evalutes to TRUE, then the loop terminates. If the cursor returns no rows, then the loop never executes its body. Reason to use this loop
Use the cursor FOR loop when you want to fetch and process every record in a cursor.
Let's take a look at how you can use the cursor FOR loop to streamline your code and reduce opportunities for error.
7.4.1 Example of Cursor FOR Loops Suppose I need to update the bills for all pets staying in my pet hotel, the Share-a-Din-Din Inn. The example below contains an anonymous block that uses a cursor, occupancy_cur, to select the room number and pet ID number for all occupants at the Inn. The procedure update_bill adds any new changes to that pet's room charges: 1 DECLARE 2 CURSOR occupancy_cur IS 3 SELECT pet_id, room_number 4 FROM occupancy WHERE occupied_dt = SYSDATE; 5 occupancy_rec occupancy_cur%ROWTYPE; 6 BEGIN 7 OPEN occupancy_cur; 8 LOOP 9 FETCH occupancy_cur INTO occupancy_rec; 10 EXIT WHEN occupancy_cur%NOTFOUND; 11 update_bill 12 (occupancy_rec.pet_id, occupancy_rec. room_number); 13 END LOOP; 14 CLOSE occupancy_cur; 15 END; This code leaves nothing to the imagination. In addition to defining the cursor (line 2), you must
explicitly declare the record for the cursor (line 5), open the cursor (line 7), start up an infinite loop, fetch a row from the cursor set into the record (line 9), check for an end-of-data condition with the cursor attribute (line 10), and finally perform the update. When you are all done, you have to remember to close the cursor (line 14). If I convert this PL/SQL block to use a cursor FOR loop, then I have: DECLARE CURSOR occupancy_cur IS SELECT pet_id, room_number FROM occupancy WHERE occupied_dt = SYSDATE; BEGIN FOR occupancy_rec IN occupancy_cur LOOP update_bill (occupancy_rec.pet_id, occupancy_rec. room_number); END LOOP; END; Here you see the beautiful simplicity of the cursor FOR loop! Gone is the declaration of the record. Gone are the OPEN, FETCH, and CLOSE statements. Gone is the need to check the %FOUND attribute. Gone are the worries of getting everything right. Instead, you say to PL/SQL, in effect, "You and I both know that I want each row and I want to dump that row into a record that matches the cursor. Take care of that for me, will you?" And PL/SQL does take care of it, just the way any modern programming language should. As with all other cursors, you can pass parameters to the cursor in a cursor FOR loop. If any of the columns in the select list of the cursor is an expression, remember that you must specify an alias for that expression in the select list. Within the loop, the only way to access a particular value in the cursor record is with the dot notation (cursor_name.column_name, as in occupancy_rec. room_number), so you need a column name associated with the expression.
7.4.2 The Cursor FOR Loop Record The record which functions as the index for the cursor FOR loop is, like the loop index of a numeric FOR loop, defined only within the loop itself. You cannot reference that record outside of the loop. Furthermore, PL/SQL declares that record itself. You, the programmer, should never declare a record for use as the index in a cursor FOR loop. If you do include such a declaration, the effect will not be as you intended. Consider the code shown below. This code contains explicit declarations for both the cursor (line 2) and a record for that cursor (line 5). The block then uses a cursor FOR loop with that cursor and specifies as its index a record with the same name as the declared record: 1
DECLARE
2 CURSOR occupancy_cur IS 3 SELECT pet_id, room_number 4 FROM occupancy WHERE occupied_dt = SYSDATE; 5 occupancy_rec occupancy_cur%ROWTYPE; 6 7 BEGIN 8 FOR occupancy_rec IN occupancy_cur 9 LOOP 10 update_bill 11 (occupancy_rec.pet_id, occupancy_rec. room_number); 12 END LOOP; 13 14 DBMS_OUTPUT.PUT_LINE 15 ('Last pet ID updated: ' || TO_CHAR (occupancy_rec. pet_id)); 16 END; I frequently run across this kind of code. Every time I see it, I shudder because it is fraught with the potential for hard-to-trace bugs. In this example, the declaration of the occupancy_rec record on line 5 is completely unnecessary and completely ignored by the cursor FOR loop. Remember: the record named as the index of the cursor FOR loop index is always declared by PL/SQL -- even if another record of the same name is defined in the declaration section. Inside the loop, any references to occupancy_rec refer to the record declared by the loop, which is completely different from the record defined explicitly in the declaration section. The danger of this redundant declaration is that an inexperienced developer may try to reference the loop record outside of the loop. In this case, the code will compile anyway because a record is defined in the scope of that PL/SQL block. The contents of that record will, however, come as a big surprise. For example, lines 14-15 of the code above call the DBMS_OUTPUT.PUT_LINE built-in function to display (or so the developer thinks) the ID of that last pet updated by the cursor. This block compiles successfully because a record called occupancy_rec is declared outside of the loop. The reference to occupancy_rec.pet_id in line 15 does not, however, return the value of the last pet ID from the cursor. It returns NULL, because it refers to the record declared explicitly on line 5, which is not the same record as that used inside the loop to receive fetched rows. If you really do need to refer to the contents of the loop's record outside of the loop, don't use a cursor FOR loop. Instead, use a WHILE loop or infinite loop. Then the record you defined on line 5 will be the same as the record used inside the loop and will contain the last row fetched by the cursor. If, on the other hand, you need to reference the record only inside the loop, strip out any declarations that match the loop indexes. Leave it to PL/SQL to handle all references correctly.
7.4.3 When to Use the Cursor FOR Loop
As you have seen, the cursor FOR loop offers many advantages when you want to loop through all of the records returned by a cursor. This type of loop is not appropriate, however, when you need to apply conditions to each fetched record to determine if you should halt execution of the loop. Suppose you need to scan through each of the records from a cursor and stop when a total accumulation of a column like the maximum number of pets exceeds a maximum, as shown in the code below. Although you can do this with a cursor FOR loop by issuing an EXIT statement inside the loop, that is an inappropriate use of this construct: 1 DECLARE 2 CURSOR occupancy_cur IS 3 SELECT pet_id, room_number 4 FROM occupancy WHERE occupied_dt = SYSDATE; 5 pet_count INTEGER := 0; 6 BEGIN 7 FOR occupancy_rec IN occupancy_cur 8 LOOP 9 update_bill 10 (occupancy_rec.pet_id, occupancy_rec. room_number); 11 pet_count := pet_count + 1; 12 EXIT WHEN pet_count > :GLOBAL.max_pets; 13 END LOOP; 14 END; The FOR loop explicitly states: "I am going to execute the body of this loop n times" (where n is a number in a numeric FOR loop, or each record in a cursor FOR loop). An EXIT inside the FOR loop short-circuits this logic. The result is code which is difficult to follow and debug. If you need to terminate a loop based on information fetched by the cursor FOR loop, you should use a WHILE loop or infinite loop in its place. Then the structure of the code will more clearly state your intentions.
Previous: 7.3 The Numeric FOR Loop 7.3 The Numeric FOR Loop
Oracle PL/SQL Programming, 2nd Edition Book Index
The Oracle Library Navigation Copyright (c) 2000 O'Reilly & Associates. All rights reserved.
Next: 7.5 The WHILE Loop 7.5 The WHILE Loop
Previous: 7.2 The Simple Loop
Chapter 7 Loops
Next: 7.4 The Cursor FOR Loop
7.3 The Numeric FOR Loop There are two kinds of PL/SQL FOR loops: the numeric FOR loop and the cursor FOR loop. The numeric FOR loop is the traditional and familiar "counted" loop. The number of iterations of the FOR loop is known when the loop starts; it is specified in the loop boundary's range scheme. The number of times the loop executes is actually determined by the range scheme found between the FOR and LOOP keywords in the boundary. The range scheme implicitly declares the loop index (if it has not already been declared), specifies the start and end points of the range, and optionally dictates the order in which the loop index proceeds (from lowest to highest or highest to lowest). Here is the general syntax of the numeric FOR loop: FOR IN [REVERSE] .. LOOP <executable statement(s)> END LOOP; You must have at least one executable statement between the LOOP and END LOOP key words. The following table summarizes the properties of the numeric FOR loop: Property
Description
How the loop is terminated
The numeric FOR loop terminates unconditionally when the number of times specified in its range scheme has been satisfied. You can also terminate the loop with an EXIT statement, but this is not recommended.
When the test for termination takes place After each execution of the loop body, PL/SQL checks the value of the loop index. When it exceeds the difference between the upper and lower bounds of the range scheme, the loop terminates. If the lower bound is greater than the upper bound of the range scheme, the loop never executes its body. Reason to use this loop
Use the numeric FOR loop when you want to execute a body of code a fixed number of times, and you do not want to halt that looping prematurely.
7.3.1 Rules for Numeric FOR Loops ●
●
●
●
●
Do not declare the loop index. PL/SQL automatically and implicitly declares it as a local variable with datatype INTEGER. The scope of this index is the loop itself; you cannot reference the loop index outside the loop. Expressions used in the range scheme (both for lowest and highest bounds) are evaluated once, when the loop starts. The range is not re-evaluated during the execution of the loop. If you make changes within the loop to the variables which you used to determine the FOR loop range, those changes will have no effect. Never change the values of either the loop index or the range boundary from within the loop. This is an extremely bad programming practice. In most cases, PL/SQL will not let you compile such code. Do not use an EXIT statement inside a FOR loop in order to cause early execution of the loop. If you are going to use a numeric FOR loop, then you should let the loop execute as it is designed: from start value to end value. If you need more control over how frequently a loop is to execute and, particularly, when it is to terminate, do not use the FOR loop. Instead, use the WHILE loop or simple loop with EXIT WHEN constructs. Use the REVERSE keyword to force the loop to decrement from the upper bound to the lower bound. You must still make sure that the first value in the range specification (the N in N .. M) is less than the second value. Do not reverse the order in which you specify these values when you use the REVERSE keyword.
7.3.2 Examples of Numeric FOR Loops The following examples demonstrate some variations of the numeric FOR loop syntax: ●
The loop executes ten times; loop_counter starts at 1 and ends at 10: FOR loop_counter IN 1 .. 10 LOOP ... executable statements ...
END LOOP; ●
The loop executes ten times; loop_counter starts at 10 and ends at 1: FOR loop_counter IN REVERSE 1 .. 10 LOOP ... executable statements ... END LOOP;
●
Here is a loop that doesn't execute even once. I specified REVERSE so the loop index, loop_counter, will start at the highest value and end with the lowest. I then mistakenly concluded that I should switch the order in which I list the highest and lowest bounds: FOR loop_counter IN REVERSE 10 .. 1 LOOP /* This loop body will never execute even once! */ END LOOP; Even when you specify a REVERSE direction, you must still list the lowest bound before the highest bound. If the first number is greater than the second number, the body of the loop will not execute at all. If the lowest and highest bounds have the same value, then the loop will execute just once.
●
Loop executes for a range determined by the values in the variable and expression: FOR calc_index IN start_period_number .. LEAST (end_period_number, current_period) LOOP ... executable statements ... END LOOP; Note that in this example we do not know the values for the lowest and highest bounds at the time of the writing of the code. The actual or dynamic range is determined at runtime and is fully supported by PL/SQL. In other words, the numeric FOR loop needs to know when it starts and how many times it will execute, but you do not have to know this when you write the program.
7.3.3 Handling Nontrivial Increments PL/SQL does not provide a "step" syntax, whereby you can specify that the loop index increment. In all variations of the PL/SQL numeric FOR loop, the loop index is always incremented or decremented by one. If you have a loop body which you want executed for a nontrivial (different from one) increment, you will have to write some cute code. For example, what if you want your loop to execute only for all
even numbers between 1 and 100? You can make use of the numeric MOD function, as follows: FOR loop_index IN 1 .. 100 LOOP IF MOD (loop_index, 2) = 0 THEN /* We have an even number, so perform calculation */ calc_values (loop_index); END IF; END LOOP; Or you can use simple multiplication inside a loop with half the iterations: FOR even_number IN 1 .. 50 LOOP calc_values (even_number*2); END LOOP; In both cases, the calc_values procedure executes only for even numbers. In the first example, the FOR loop executes 100 times. In the second example, the FOR loop executes only 50 times. Whichever approach you decide to take, be sure to document this kind of technique clearly. You are, in essence, manipulating the numeric FOR loop to do something for which it is not designed. Comments would be very helpful for the maintenance programmer who has to understand why you would code something like that.
Previous: 7.2 The Simple Loop 7.2 The Simple Loop
Oracle PL/SQL Programming, 2nd Edition Book Index
The Oracle Library Navigation Copyright (c) 2000 O'Reilly & Associates. All rights reserved.
Next: 7.4 The Cursor FOR Loop 7.4 The Cursor FOR Loop
Previous: 7.1 Loop Basics
Chapter 7 Loops
Next: 7.3 The Numeric FOR Loop
7.2 The Simple Loop The structure of the simple loop is the most basic of all the loop constructs. It consists of the LOOP keyword, the body of executable code, and the END LOOP keywords, as shown here: LOOP <executable statement(s)> END LOOP; The loop boundary consists solely of the LOOP and END LOOP reserved words. The body must consist of at least one executable statement. The following table summarizes the properties of the single loop: Property
Description
How the loop is terminated
The simple loop is terminated when an EXIT statement is executed in the body of the loop. If this statement is not executed, the simple loop becomes a true infinite loop.
When the test for termination takes place
The test takes place inside the body of the loop -- and then only if an EXIT or EXIT WHEN statement is executed. Therefore, the body -- or part of the body -- of the simple loop will always execute at least once.
Reason to use this loop
Use the simple loop when: ●
●
You are not sure how many times you will want the loop to execute, and You want the loop to run at least once.
This loop is useful when you want to guarantee that the body (or at least part of the body) executes at least one time. Because there is no condition associated with the loop boundary that determines whether or not it should execute, the body of the loop will always execute the first time. The simple loop will terminate only when an EXIT statement is executed in its body (see "Terminating a Single Loop: EXIT and EXIT WHEN" below). Because this doesn't have to be the case, a simple loop can also become an infinite loop. This could cause difficulties in your program and is something to be avoided. The following example shows a simple loop which is truly infinite; it keeps checking for messages from a particular pipe so that it can respond immediately and display the information in the pipe. (This is the central concept behind a DBMS_PIPE-based debugger for PL/SQL code -- a prototype of which may be found in the dbg.doc file on the companion disk. See Appendix A, What's on the Companion Disk?, for details.) DECLARE pipe_status INTEGER; message_text VARCHAR2 BEGIN LOOP pipe_status := DBMS_PIPE.RECEIVE_MESSAGE ('execution_trace'); IF pipe_status = 0 THEN DBMS_PIPE.UNPACK_MESSAGE (message_text); DBMS_OUTPUT.PUT_LINE (message_text); END IF; END LOOP; END;
7.2.1 Terminating a Simple Loop: EXIT and EXIT WHEN Be very careful when you use simple loops. Make sure they always have a way to stop. To force a simple loop to stop processing, execute an EXIT or EXIT WHEN statement within the body of the loop. The syntax for these statements is as follows: EXIT: EXIT WHEN condition; where condition is a Boolean expression. The following example demonstrates how the EXIT forces the loop to immediately halt execution and pass control to the next statement after the END LOOP statement. The account_balance procedure returns the amount of money remaining in the account specified by the account ID. If there is less than $1000 left, the EXIT statement is executed and the loop is terminated. Otherwise, the
program applies the balance to the outstanding orders for that account. LOOP balance_remaining := account_balance (account_id); IF balance_remaining < 1000 THEN EXIT; ELSE apply_balance (account_id, balance_remaining); END IF; END LOOP; You can use an EXIT statement only within a LOOP. PL/SQL also offers the EXIT WHEN statement, which supports the concept of "conditional termination" of the loop. Essentially, the EXIT WHEN combines an IF-THEN statement with the EXIT statement. Using the same example I showed above, the EXIT WHEN changes the loop to: LOOP /* Calculate the balance */ balance_remaining := account_balance (account_id); /* Embed the IF logic into the EXIT statement */ EXIT WHEN balance_remaining < 1000; /* Apply balance if still executing the loop */ apply_balance (account_id, balance_remaining); END LOOP; Notice that the loop no longer requires an IF statement to determine when it should exit. Instead, that conditional logic is embedded inside the EXIT WHEN statement. EXIT WHEN is a very concise and readable way to terminate a simple loop; I recommend its use over the unconditional EXIT statement. After all, you should always have an EXIT statement nested within an IF-THEN. If you don't, then you either have an infinite loop or you have a loop that executes just once. In the latter case, it is better to execute the body of the loop without using a loop. If the EXIT is always included within the IF-THEN, you'd be better off using a language construct built specifically for the purpose. The EXIT WHEN construct also reduces the amount of code you need to write.
7.2.2 Emulating a REPEAT UNTIL Loop PL/SQL does not provide a REPEAT UNTIL loop in which the condition is tested after the body of the loop is executed and thus guarantees that the loop always executes at least once. You can, however, emulate a REPEAT UNTIL with a simple loop, as follows:
LOOP ... body of loop ... EXIT WHEN boolean_condition; END LOOP; where boolean_condition is a Boolean variable or an expression that evaluates to a Boolean value of TRUE or FALSE.
Previous: 7.1 Loop Basics 7.1 Loop Basics
Oracle PL/SQL Programming, 2nd Edition Book Index
The Oracle Library Navigation Copyright (c) 2000 O'Reilly & Associates. All rights reserved.
Next: 7.3 The Numeric FOR Loop 7.3 The Numeric FOR Loop
Previous: 6.13 Working with Cursors
Chapter 7
Next: 7.2 The Simple Loop
7. Loops Contents: Loop Basics The Simple Loop The Numeric FOR Loop The Cursor FOR Loop The WHILE Loop Managing Loop Execution Tips for PL/SQL Loops This chapter explores the iterative control structures of PL/SQL, otherwise known as loops, which let you execute the same code repeatedly. PL/SQL provides three different kinds of loop constructs: ● ● ●
The simple or infinite loop The FOR loop (numeric and cursor) The WHILE loop
Each type of loop is designed for a specific purpose with its own nuances, rules for use, and guidelines for high-quality construction. As I explain each of the loops, I will include a table (based on the following one) describing the following properties of the loop: Property
Description
How the loop is terminated
A loop executes code repetitively. How do you make the loop stop executing its body?
When the test for termination takes place
Does the test for termination take place at the beginning or end of the loop? What are the consequences?
Reason to use this loop
What are the special factors you should consider to determine if this loop is right for your situation?
7.1 Loop Basics Why are there three different kinds of loops? To provide you with the flexibility you need to write the most straightforward code to handle any particular situation. Most situations which require a loop could be written with any of the three loop constructs. If you do not pick the construct best-suited for that particular requirement, however, you could end up having to write many additional lines of code. The resulting module would also be harder to understand and maintain.
7.1.1 Examples of Different Loops To give you a feeling for the way the different loops solve their problems in different ways, consider the following three procedures. In each case, the procedure executes the same body of code inside a loop: set_rank (ranking_level); where set_rank performs a ranking for the specified level. ●
The simple loop. My procedure accepts a maximum ranking as an argument and then sets the rank until the level exceeds the maximum. Notice the IF statement to guard against executing the loop when the maximum rank is negative. Notice also the EXIT WHEN statement used to terminate the loop: PROCEDURE set_all_ranks (max_rank_in IN INTEGER) IS ranking_level NUMBER(3) := 1; BEGIN IF max_rank_in >= 1 THEN LOOP set_rank (ranking_level); ranking_level := ranking_level + 1; EXIT WHEN ranking_level > max_rank_in; END LOOP; END IF; END;
●
The FOR loop. In this case, I rank for the fixed range of values, from one to the maximum number: PROCEDURE set_all_ranks (max_rank_in IN INTEGER) IS BEGIN FOR ranking_level IN 1 .. max_rank_in
LOOP set_rank (ranking_level); END LOOP; END; ●
The WHILE loop. My procedure accepts a maximum ranking as an argument and then sets the rank until the level exceeds the maximum. Notice that the condition which terminates the loop comes on the same line as the WHILE keyword: PROCEDURE set_all_ranks (max_rank_in IN INTEGER) IS ranking_level NUMBER(3) := 1; BEGIN WHILE ranking_level <= max_rank_in LOOP set_rank (ranking_level); ranking_level := ranking_level + 1; END LOOP; END;
In the above example, the FOR loop clearly requires the smallest amount of code. Yet I could only use i