Oracle® Database PL/SQL Language Reference 11g Release 1 (11.1) Part Number B28370-02 |
|
|
View PDF |
PL/SQL, the Oracle procedural extension of SQL, is a completely portable, high-performance transaction-processing language. This chapter explains its advantages and briefly describes its main features and its architecture.
Topics:
PL/SQL has the following advantages:
SQL has become the standard database language because it is flexible, powerful, and easy to learn. A few English-like statements such as SELECT
, INSERT
, UPDATE
, and DELETE
make it easy to manipulate the data stored in a relational database.
PL/SQL is tightly integrated with SQL. With PL/SQL, you can use all SQL data manipulation, cursor control, and transaction control statements, and all SQL functions, operators, and pseudocolumns.
PL/SQL fully supports SQL datatypes. You do not have to convert between PL/SQL and SQL datatypes. For example, if your PL/SQL program retrieves a value from a database column of the SQL type VARCHAR2
, it can store that value in a PL/SQL variable of the type VARCHAR2
. Special PL/SQL language features let you work with table columns and rows without specifying the datatypes, saving on maintenance work when the table definitions change.
Running a SQL query and processing the result set is as easy in PL/SQL as opening a text file and processing each line in popular scripting languages. Using PL/SQL to access metadata about database objects and handle database error conditions, you can write utility programs for database administration that are reliable and produce readable output about the success of each operation. Many database features, such as triggers and object types, use PL/SQL. You can write the bodies of triggers and methods for object types in PL/SQL.
PL/SQL supports both static and dynamic SQL. Static SQL is SQL whose full text is known at compilation time. Dynamic SQL is SQL whose full text is not known until run time. Dynamic SQL enables you to make your applications more flexible and versatile. For information about using static SQL with PL/SQL, see Chapter 6, "Using Static SQL". For information about using dynamic SQL, see Chapter 7, "Using Dynamic SQL".
With PL/SQL, an entire block of statements can be sent to Oracle Database at one time. This can drastically reduce network traffic between the database and an application. As Figure 1-1 shows, you can use PL/SQL blocks and subprograms (procedures and functions) to group SQL statements before sending them to the database for execution. PL/SQL also has language features to further speed up SQL statements that are issued inside a loop.
PL/SQL stored subprograms are compiled once and stored in executable form, so subprogram calls are efficient. Because stored subprograms execute in the database server, a single call over the network can start a large job. This division of work reduces network traffic and improves response times. Stored subprograms are cached and shared among users, which lowers memory requirements and call overhead.
PL/SQL lets you write very compact code for manipulating data. In the same way that scripting languages such as PERL can read, transform, and write data from files, PL/SQL can query, transform, and update data in a database. PL/SQL saves time on design and debugging by offering a full range of software-engineering features, such as exception handling, encapsulation, data hiding, and object-oriented datatypes.
PL/SQL extends tools such as Oracle Forms. With PL/SQL in these tools, you can use familiar language constructs to build applications. For example, you can use an entire PL/SQL block in an Oracle Forms trigger, instead of multiple trigger steps, macros, or user exits. PL/SQL is the same in all environments. After you learn PL/SQL with one Oracle Database tool, you can transfer your knowledge to other tools.
Applications written in PL/SQL can run on any operating system and platform where Oracle Database runs. With PL/SQL, you can write portable program libraries and re-use them in different environments.
PL/SQL stored subprograms move application code from the client to the server, where you can protect it from tampering, hide the internal details, and restrict who has access. For example, you can grant users access to a subprogram that updates a table, but not grant them access to the table itself or to the text of the UPDATE
statement. Triggers written in PL/SQL can control or record changes to data, making sure that all changes obey your business rules.
For information about wrapping, or hiding, the source of a PL/SQL unit, see Appendix A, "Wrapping PL/SQL Source Code".
Oracle provides product-specific packages that define APIs you can invoke from PL/SQL to perform many useful tasks. These packages include DBMS_ALERT
for using triggers, DBMS_FILE
for reading and writing operating system text files, UTL_HTTP
for making hypertext transfer protocol (HTTP) callouts, DBMS_OUTPUT
for display output from PL/SQL blocks and subprograms, and DBMS_PIPE
for communicating over named pipes. For more information about these packages, see "Overview of Product-Specific PL/SQL Packages".
For complete information about the packages supplied by Oracle, see Oracle Database PL/SQL Packages and Types Reference.
Object types are an ideal object-oriented modeling tool, which you can use to reduce the cost and time required to build complex applications. Besides enabling you to create software components that are modular, maintainable, and re-usable, object types allow different teams of programmers to develop software components concurrently.
By encapsulating operations with data, object types let you move data-maintenance code out of SQL scripts and PL/SQL blocks into methods. Also, object types hide implementation details, so that you can change the details without affecting client programs.
In addition, object types allow for realistic data modeling. Complex real-world entities and relationships map directly into object types. This direct mapping helps your programs better reflect the world they are trying to simulate. For information about object types, see Oracle Database Object-Relational Developer's Guide.
You can use PL/SQL to develop Web applications and Server Pages (PSPs). For an overview of the use of PL/SQL with the Web, see "Using PL/SQL to Create Web Applications and Server Pages".
PL/SQL combines the data-manipulating power of SQL with the processing power of procedural languages.
When a problem can be solved using SQL, you can issue SQL statements from your PL/SQL programs, without learning new APIs.
Like other procedural programming languages, PL/SQL lets you declare constants and variables, control program flow, define subprograms, and trap run-time errors.
You can break complex problems into easily understandable subprograms, which you can re-use in multiple applications.
Topics:
The basic unit of a PL/SQL source program is the block, which groups related declarations and statements.
A PL/SQL block is defined by the keywords DECLARE
, BEGIN
, EXCEPTION
, and END
. These keywords partition the block into a declarative part, an executable part, and an exception-handling part. Only the executable part is required.
Declarations are local to the block and cease to exist when the block completes execution, helping to avoid cluttered namespaces for variables and subprograms.
Blocks can be nested: Because a block is an executable statement, it can appear in another block wherever an executable statement is allowed.
Example 1-1 shows the basic structure of a PL/SQL block. For the formal syntax description, see "Block Declaration".
Example 1-1 PL/SQL Block Structure
DECLARE -- Declarative part (optional) -- Declarations of local types, variables, & subprograms BEGIN -- Executable part (required) -- Statements (which can use items declared in declarative part) [EXCEPTION -- Exception-handling part (optional) -- Exception handlers for exceptions raised in executable part] END;
An anonymous PL/SQL block can be submitted to an interactive tool (such as SQL*Plus or Enterprise Manager), or embedded in an Oracle Precompiler or OCI program. The interactive tool or program executes the anonymous block only once.
A named PL/SQL block—a subprogram—can be invoked repeatedly (see "PL/SQL Subprograms").
PL/SQL makes it easy to detect and process error conditions known as exceptions. When an error occurs, an exception is raised: normal execution stops and control transfers to special exception-handling code, which comes at the end of any PL/SQL block. Each different exception is processed by a particular exception handler.
PL/SQL's exception handling is different from the manual checking you might be used to from C programming, where you insert a check to make sure that every operation succeeded. Instead, the checks and calls to error routines are performed automatically, similar to the exception mechanism in Java programming.
Predefined exceptions are raised automatically for certain common error conditions involving variables or database operations. For example, if you try to divide a number by zero, PL/SQL raises the predefined exception ZERO_DIVIDE
automatically.
You can declare exceptions of your own, for conditions that you decide are errors, or to correspond to database errors that normally result in ORA- error messages. When you detect a user-defined error condition, you execute a RAISE
statement. See the exception comm_missing
in Example 1-17. In the example, if the commission is null, the exception comm_missing
is raised.
Typically, you put an exception handler at the end of a subprogram to handle exceptions that are raised anywhere inside the subprogram. To continue executing from the spot where an exception happens, enclose the code that might raise an exception inside another BEGIN-END
block with its own exception handler. For example, you might put separate BEGIN-END
blocks around groups of SQL statements that might raise NO_DATA_FOUND
, or around arithmetic operations that might raise DIVIDE_BY_ZERO
. By putting a BEGIN-END
block with an exception handler inside a loop, you can continue executing the loop even if some loop iterations raise exceptions. See Example 5-38.
For information about PL/SQL errors, see "Overview of PL/SQL Run-Time Error Handling". For information about PL/SQL warnings, see "Overview of PL/SQL Compile-Time Warnings".
Most PL/SQL input and output (I/O) is through SQL statements that store data in database tables or query those tables. All other PL/SQL I/O is done through APIs, such as the PL/SQL package DBMS_OUTPUT
.
To display output passed to DBMS_OUTPUT
, you need another program, such as SQL*Plus. To see DBMS_OUTPUT
output with SQL*Plus, you must first issue the SQL*Plus command SET
SERVEROUTPUT
ON
. For more information about SQL*Plus, see SQL*Plus User's Guide and Reference.
Other PL/SQL APIs for processing I/O are:
HTF
and HTP
for displaying output on a web page
DBMS_PIPE
for passing information back and forth between PL/SQL and operating-system commands
UTL_FILE
for reading and writing operating-system files
UTL_HTTP
for communicating with web servers
UTL_SMTP
for communicating with mail servers
Although some of the preceding APIs can accept input as well as display output, they have cannot accept data directly from the keyboard. For that, use the PROMPT
and ACCEPT
statements in SQL*Plus.
For more information about the preceding APIs, see "Overview of Product-Specific PL/SQL Packages".
PL/SQL lets you declare variables and constants, and then use them in SQL and procedural statements anywhere an expression can be used. You must declare a variable or constant before referencing it in any other statements. For more information, see "Declarations".
Topics:
A PL/SQL variable can have any SQL datatype (such as CHAR
, DATE
, or NUMBER
) or a PL/SQL-only datatype (such as BOOLEAN
or PLS_INTEGER
).
The PL/SQL code fragment in Example 1-2 declares several PL/SQL variables. One has a PL/SQL-only datatype; the others have SQL datatypes.
Example 1-2 PL/SQL Variable Declarations
DECLARE part_number NUMBER(6); -- SQL datatype part_name VARCHAR2(20); -- SQL datatype in_stock BOOLEAN; -- PL/SQL-only datatype part_price NUMBER(6,2); -- SQL datatype part_description VARCHAR2(50); -- SQL datatype
For more information about PL/SQL datatypes, see Chapter 3, "PL/SQL Datatypes".
PL/SQL also lets you declare composite datatypes, such as nested tables, variable-size arrays, and records. For more informations, see Chapter 5, "Using PL/SQL Collections and Records".
You can assign a value to a variable in the following ways:
With the assignment operator (:=), as in Example 1-3.
Note that you can assign a value to a variable when you declare it.
By selecting (or fetching) database values into it, as in Example 1-4.
By passing it as an OUT
or IN
OUT
parameter to a subprogram, and then assigning the value inside the subprogram, as in Example 1-5
Example 1-3 Assigning Values to Variables with the Assignment Operator
DECLARE -- You can assign values here wages NUMBER; hours_worked NUMBER := 40; -- Assign 40 to hours_worked hourly_salary NUMBER := 22.50; -- Assign 22.50 to hourly_salary bonus NUMBER := 150; -- Assign 150 to bonus country VARCHAR2(128); counter NUMBER := 0; -- Assign 0 to counter done BOOLEAN; valid_id BOOLEAN; emp_rec1 employees%ROWTYPE; emp_rec2 employees%ROWTYPE; TYPE commissions IS TABLE OF NUMBER INDEX BY PLS_INTEGER; comm_tab commissions; BEGIN -- You can assign values here too wages := (hours_worked * hourly_salary) + bonus; country := 'France'; country := UPPER('Canada'); done := (counter > 100); valid_id := TRUE; emp_rec1.first_name := 'Antonio'; emp_rec1.last_name := 'Ortiz'; emp_rec1 := emp_rec2; comm_tab(5) := 20000 * 0.15; END; /
In Example 1-4, 10% of an employee's salary is selected into the bonus
variable. Now you can use the bonus
variable in another computation or insert its value into a database table.
Example 1-4 Using SELECT INTO to Assign Values to Variables
DECLARE bonus NUMBER(8,2); emp_id NUMBER(6) := 100; BEGIN SELECT salary * 0.10 INTO bonus FROM employees WHERE employee_id = emp_id; END; /
Example 1-5 passes the new_sal
variable to a subprogram, and the subprogram updates the variable.
Example 1-5 Assigning Values to Variables as Parameters of a Subprogram
REM SERVEROUTPUT must be set to ON REM to display output with DBMS_OUTPUT SET SERVEROUTPUT ON FORMAT WRAPPED DECLARE new_sal NUMBER(8,2); emp_id NUMBER(6) := 126; PROCEDURE adjust_salary (emp_id NUMBER, sal IN OUT NUMBER) IS emp_job VARCHAR2(10); avg_sal NUMBER(8,2); BEGIN SELECT job_id INTO emp_job FROM employees WHERE employee_id = emp_id; SELECT AVG(salary) INTO avg_sal FROM employees WHERE job_id = emp_job; DBMS_OUTPUT.PUT_LINE ('The average salary for ' || emp_job || ' employees: ' || TO_CHAR(avg_sal)); sal := (sal + avg_sal)/2; END; BEGIN SELECT AVG(salary) INTO new_sal FROM employees; DBMS_OUTPUT.PUT_LINE ('The average salary for all employees: ' || TO_CHAR(new_sal)); adjust_salary(emp_id, new_sal); END; /
Declaring a PL/SQL constant is like declaring a PL/SQL variable except that you must add the keyword CONSTANT
and immediately assign a value to the constant. For example:
credit_limit CONSTANT NUMBER := 5000.00;
No further assignments to the constant are allowed.
Bind variables improve performance by allowing Oracle Database to re-use SQL statements.
When you embed a SQL INSERT
, UPDATE
, DELETE
, or SELECT
statement directly in your PL/SQL code, PL/SQL turns the variables in the WHERE
and VALUES
clauses into bind variables automatically. Oracle Database can re-use these SQL statements each time the same code is executed. To run similar statements with different variable values, you can save parsing overhead by invoking a stored subprogram that accepts parameters and then issues the statements with the parameters substituted in the appropriate places.
PL/SQL does not create bind variables automatically when you use dynamic SQL, but you can use them with dynamic SQL by specifying them explicitly.
Data abstraction lets you work with the essential properties of data without being too involved with details. After you design a data structure, you can focus on designing algorithms that manipulate the data structure.
Topics:
A cursor is a name for a specific private SQL area in which information for processing the specific statement is kept. PL/SQL uses both implicit and explicit cursors. PL/SQL implicitly declares a cursor for all SQL data manipulation statements on a set of rows, including queries that return only one row. For queries that return more than one row, you can explicitly declare a cursor to process the rows individually. For example, Example 1-6 declares an explicit cursor.
For information about cursors, see "Managing Cursors in PL/SQL".
The %TYPE
attribute provides the datatype of a variable or database column. This is particularly useful when declaring variables that will hold database values. For example, assume there is a column named last_name
in a table named employees
. To declare a variable named v_last_name
that has the same datatype as column last_name
, use dot notation and the %TYPE
attribute, as follows:
v_last_name employees.last_name%TYPE;
Declaring v_last_name
with %TYPE
has two advantages. First, you need not know the exact datatype of last_name
. Second, if you change the database definition of last_name
, perhaps to make it a longer character string, the datatype of v_last_name
changes accordingly at run time.
For more information about %TYPE
, see "Using the %TYPE Attribute" and "%TYPE Attribute".
In PL/SQL, records are used to group data. A record consists of a number of related fields in which data values can be stored. The %ROWTYPE
attribute provides a record type that represents a row in a table. The record can store an entire row of data selected from the table or fetched from a cursor or cursor variable. See "Cursors".
Columns in a row and corresponding fields in a record have the same names and datatypes. In the following example, you declare a record named dept_rec
. Its fields have the same names and datatypes as the columns in the departments
table.
DECLARE dept_rec departments%ROWTYPE; -- declare record variable
You use dot notation to reference fields, as the following example shows:
v_deptid := dept_rec.department_id;
If you declare a cursor that retrieves the last name, salary, hire date, and job class of an employee, you can use %ROWTYPE
to declare a record that stores the same information as shown in Example 1-6. When you execute the FETCH
statement, the value in the last_name
column of the employees
table is assigned to the last_name
field of employee_rec
, the value in the salary
column is assigned to the salary
field, and so on.
Example 1-6 Using %ROWTYPE with an Explicit Cursor
DECLARE CURSOR c1 IS SELECT last_name, salary, hire_date, job_id FROM employees WHERE employee_id = 120; -- declare record variable that represents a row -- fetched from the employees table employee_rec c1%ROWTYPE; BEGIN -- open the explicit cursor -- and use it to fetch data into employee_rec OPEN c1; FETCH c1 INTO employee_rec; DBMS_OUTPUT.PUT_LINE('Employee name: ' || employee_rec.last_name); END; /
For more information about %ROWTYPE
, see "Using the %ROWTYPE Attribute" and "%ROWTYPE Attribute".
PL/SQL collection types let you declare high-level datatypes similar to arrays, sets, and hash tables found in other languages. In PL/SQL, array types are known as varrays (short for variable-size arrays), set types are known as nested tables, and hash table types are known as associative arrays. Each kind of collection is an ordered group of elements, all of the same type. Each element has a unique subscript that determines its position in the collection. When declaring collections, you use a TYPE
definition. See "Defining Collection Types".
To reference an element, use subscript notation with parentheses, as shown in Example 1-7.
Example 1-7 Using a PL/SQL Collection Type
DECLARE TYPE staff_list IS TABLE OF employees.employee_id%TYPE; staff staff_list; lname employees.last_name%TYPE; fname employees.first_name%TYPE; BEGIN staff := staff_list(100, 114, 115, 120, 122); FOR i IN staff.FIRST..staff.LAST LOOP SELECT last_name, first_name INTO lname, fname FROM employees WHERE employees.employee_id = staff(i); DBMS_OUTPUT.PUT_LINE (TO_CHAR(staff(i)) || ': ' || lname || ', ' || fname ); END LOOP; END; /
Collections can be passed as parameters, so that subprograms can process arbitrary numbers of elements.You can use collections to move data into and out of database tables using high-performance language features known as bulk SQL.
For information about collections, see Chapter 5, "Using PL/SQL Collections and Records".
Records are composite data structures whose fields can have different datatypes. You can use records to hold related items and pass them to subprograms with a single parameter. When declaring records, you use a TYPE
definition. See "Defining and Declaring Records".
Example 1-8 shows how are records are declared.
Example 1-8 Declaring a Record Type
DECLARE TYPE timerec IS RECORD (hours SMALLINT, minutes SMALLINT); TYPE meetin_typ IS RECORD ( date_held DATE, duration timerec, -- nested record location VARCHAR2(20), purpose VARCHAR2(50)); BEGIN -- NULL does nothing but allows unit to be compiled and tested NULL; END; /
You can use the %ROWTYPE
attribute to declare a record that represents a row in a table or a row from a query result set, without specifying the names and types for the fields.
For information about records, see Chapter 5, "Using PL/SQL Collections and Records".
PL/SQL supports object-oriented programming through object types. An object type encapsulates a data structure along with the subprograms needed to manipulate the data. The variables that form the data structure are known as attributes. The subprograms that manipulate the attributes are known as methods.
Object types reduce complexity by breaking down a large system into logical entities. This lets you create software components that are modular, maintainable, and re-usable. Object-type definitions, and the code for the methods, are stored in the database. Instances of these object types can be stored in tables or used as variables inside PL/SQL code. Example 1-9 shows an object type definition for a bank account.
Example 1-9 Defining an Object Type
CREATE TYPE bank_account AS OBJECT ( acct_number NUMBER(5), balance NUMBER, status VARCHAR2(10), MEMBER PROCEDURE open (SELF IN OUT NOCOPY bank_account, amount IN NUMBER), MEMBER PROCEDURE close (SELF IN OUT NOCOPY bank_account, num IN NUMBER, amount OUT NUMBER), MEMBER PROCEDURE deposit (SELF IN OUT NOCOPY bank_account, num IN NUMBER, amount IN NUMBER), MEMBER PROCEDURE withdraw (SELF IN OUT NOCOPY bank_account, num IN NUMBER, amount IN NUMBER), MEMBER FUNCTION curr_bal (num IN NUMBER) RETURN NUMBER); /
For information about object types, see Oracle Database Object-Relational Developer's Guide.
Control structures are the most important PL/SQL extension to SQL. Not only does PL/SQL let you manipulate Oracle Database data, it lets you process the data using flow-of-control statements.
Topics:
For more information, see Chapter 4, "Using PL/SQL Control Structures".
Often, it is necessary to take alternative actions depending on circumstances. The IF-THEN-ELSE
statement lets you execute a sequence of statements conditionally. The IF
clause checks a condition, the THEN
clause defines what to do if the condition is true and the ELSE
clause defines what to do if the condition is false or null. Example 1-10 shows the use of IF-THEN-ELSE
to determine the salary raise an employee receives based on the current salary of the employee.
To choose among several values or courses of action, you can use CASE
constructs. The CASE
expression evaluates a condition and returns a value for each case. The case statement evaluates a condition and performs an action for each case, as in Example 1-10.
Example 1-10 Using the IF-THEN_ELSE and CASE Statement for Conditional Control
DECLARE jobid employees.job_id%TYPE; empid employees.employee_id%TYPE := 115; sal employees.salary%TYPE; sal_raise NUMBER(3,2); BEGIN SELECT job_id, salary INTO jobid, sal from employees WHERE employee_id = empid; CASE WHEN jobid = 'PU_CLERK' THEN IF sal < 3000 THEN sal_raise := .12; ELSE sal_raise := .09; END IF; WHEN jobid = 'SH_CLERK' THEN IF sal < 4000 THEN sal_raise := .11; ELSE sal_raise := .08; END IF; WHEN jobid = 'ST_CLERK' THEN IF sal < 3500 THEN sal_raise := .10; ELSE sal_raise := .07; END IF; ELSE BEGIN DBMS_OUTPUT.PUT_LINE('No raise for this job: ' || jobid); END; END CASE; UPDATE employees SET salary = salary + salary * sal_raise WHERE employee_id = empid; COMMIT; END; /
A sequence of statements that uses query results to select alternative actions is common in database applications. Another common sequence inserts or deletes a row only if an associated entry is found in another table. You can bundle these common sequences into a PL/SQL block using conditional logic.
LOOP
statements let you execute a sequence of statements multiple times. You place the keyword LOOP
before the first statement in the sequence and the keywords END
LOOP
after the last statement in the sequence. The following example shows the simplest kind of loop, which repeats a sequence of statements continually:
LOOP -- sequence of statements END LOOP;
The FOR-LOOP
statement lets you specify a range of integers, then execute a sequence of statements once for each integer in the range. In Example 1-11 the loop inserts 100 numbers, square roots, squares, and the sum of squares into a database table:
Example 1-11 Using the FOR-LOOP
CREATE TABLE sqr_root_sum (num NUMBER, sq_root NUMBER(6,2), sqr NUMBER, sum_sqrs NUMBER); DECLARE s PLS_INTEGER; BEGIN FOR i in 1..100 LOOP s := (i * (i + 1) * (2*i +1)) / 6; -- sum of squares INSERT INTO sqr_root_sum VALUES (i, SQRT(i), i*i, s ); END LOOP; END; /
The WHILE-LOOP
statement associates a condition with a sequence of statements. Before each iteration of the loop, the condition is evaluated. If the condition is true, the sequence of statements is executed, then control resumes at the top of the loop. If the condition is false or null, the loop is bypassed and control passes to the next statement.
In Example 1-12, you find the first employee who has a salary over $15000 and is higher in the chain of command than employee 120:
Example 1-12 Using WHILE-LOOP for Control
CREATE TABLE temp (tempid NUMBER(6), tempsal NUMBER(8,2), tempname VARCHAR2(25)); DECLARE sal employees.salary%TYPE := 0; mgr_id employees.manager_id%TYPE; lname employees.last_name%TYPE; starting_empid employees.employee_id%TYPE := 120; BEGIN SELECT manager_id INTO mgr_id FROM employees WHERE employee_id = starting_empid; WHILE sal <= 15000 LOOP -- loop until sal > 15000 SELECT salary, manager_id, last_name INTO sal, mgr_id, lname FROM employees WHERE employee_id = mgr_id; END LOOP; INSERT INTO temp VALUES (NULL, sal, lname); -- insert NULL for tempid COMMIT; EXCEPTION WHEN NO_DATA_FOUND THEN INSERT INTO temp VALUES (NULL, NULL, 'Not found'); -- insert NULLs COMMIT; END; /
The EXIT-WHEN
statement lets you complete a loop if further processing is impossible or undesirable. When the EXIT
statement is encountered, the condition in the WHEN
clause is evaluated. If the condition is true, the loop completes and control passes to the next statement. In Example 1-13, the loop completes when the value of total
exceeds 25,000:
Similarly, the CONTINUE-WHEN
statement immediately transfers control to the next iteration of the loop when there is no need to continue working on this iteration.
Example 1-13 Using the EXIT-WHEN Statement
DECLARE total NUMBER(9) := 0; counter NUMBER(6) := 0; BEGIN LOOP counter := counter + 1; total := total + counter * counter; -- exit loop when condition is true EXIT WHEN total > 25000; END LOOP; DBMS_OUTPUT.PUT_LINE ('Counter: ' || TO_CHAR(counter) || ' Total: ' || TO_CHAR(total)); END; /
The GOTO
statement lets you branch to a label unconditionally. The label, an undeclared identifier enclosed by double angle brackets, must precede an executable statement or a PL/SQL block. When executed, the GOTO
statement transfers control to the labeled statement or block, as shown in Example 1-14.
Example 1-14 Using the GOTO Statement
DECLARE total NUMBER(9) := 0; counter NUMBER(6) := 0; BEGIN <<calc_total>> counter := counter + 1; total := total + counter * counter; -- branch to print_total label when condition is true IF total > 25000 THEN GOTO print_total; ELSE GOTO calc_total; END IF; <<print_total>> DBMS_OUTPUT.PUT_LINE ('Counter: ' || TO_CHAR(counter) || ' Total: ' || TO_CHAR(total)); END; /
A PL/SQL subprogram is a named PL/SQL block that can be invoked with a set of parameters. PL/SQL has two types of subprograms, procedures and functions. A function returns a result.
The PL/SQL code fragment in Example 1-15 declares a PL/SQL procedure.
Example 1-15 PL/SQL Procedure Declaration
DECLARE in_string VARCHAR2(100) := 'This is my test string.'; out_string VARCHAR2(200); PROCEDURE double (original IN VARCHAR2, new_string OUT VARCHAR2 ) AS BEGIN new_string := original || original; END;
A PL/SQL subprogram can be invoked from an interactive tool (such as SQL*Plus or Enterprise Manager), from an Oracle Precompiler or OCI program, from another PL/SQL subprogram, or from a trigger.
Example 1-16 shows invokes the stored subprogram in Example 1-17 from SQL*Plus
twice, first with the CALL
statement, and then from inside a BEGIN-END
block.
Example 1-16 Techniques for Invoking a Standalone Procedure from SQL*Plus
CALL award_bonus(179, 1000); BEGIN award_bonus(179, 10000); END; / -- using named notation BEGIN award_bonus(emp_id=>179, bonus=>10000); END; /
Using the BEGIN-END
block is recommended in several situations. For example, using the CALL
statement can suppress an ORA-01403:
no
data
found
error that was not handled in the PL/SQL subprogram.
For additional examples of invoking PL/SQL subprograms, see Example 8-5. For information about the CALL
statement, see Oracle Database SQL Language Reference
Topics:
For more information about PL/SQL subprograms, see Chapter 8, "Using PL/SQL Subprograms".
You create standalone subprograms at schema level with the SQL statements CREATE
PROCEDURE
and CREATE
FUNCTION
. They are compiled and stored in Oracle Database, where they can be used by any number of applications connected to the database. When invoked, they are loaded and processed immediately. Subprograms use shared memory, so that only one copy of a subprogram is loaded into memory for execution by multiple users.
The standalone procedure in Example 1-17 accepts an employee ID and a bonus amount, uses the ID to select the employee's commission percentage from a database table and to convert the commission percentage to a decimal amount, and then checks the commission amount. If the commission is null, the procedure raises an exception; otherwise, it updates the employee's salary.
Example 1-17 Creating a Standalone PL/SQL Procedure
CREATE OR REPLACE PROCEDURE award_bonus (emp_id NUMBER, bonus NUMBER) AS commission REAL; comm_missing EXCEPTION; BEGIN -- executable part starts here SELECT commission_pct / 100 INTO commission FROM employees WHERE employee_id = emp_id; IF commission IS NULL THEN RAISE comm_missing; ELSE UPDATE employees SET salary = salary + bonus*commission WHERE employee_id = emp_id; END IF; EXCEPTION -- exception-handling part starts here WHEN comm_missing THEN DBMS_OUTPUT.PUT_LINE ('This employee does not receive a commission.'); commission := 0; WHEN OTHERS THEN NULL; -- for other exceptions do nothing END award_bonus; / CALL award_bonus(150, 400);
For information, about the CREATE
PROCEDURE
statment, see Oracle Database SQL Language Reference.
For more information about the SQL CREATE
FUNCTION
, see the Oracle Database SQL Language Reference.
A trigger is a stored subprogram associated with a table, view, or event. The trigger can be invoked once, when some event occurs, or many times, once for each row affected by an INSERT
, UPDATE
, or DELETE
statement. The trigger can be invoked before or after the event.
The trigger in Example 1-18 is invoked whenever salaries in the employees
table are updated. For each update, the trigger writes a record to the emp_audit
table. (Example 1-10 would invoke this trigger.)
Example 1-18 Creating a Trigger
CREATE TABLE emp_audit (emp_audit_id NUMBER(6), up_date DATE, new_sal NUMBER(8,2), old_sal NUMBER(8,2)); CREATE OR REPLACE TRIGGER audit_sal AFTER UPDATE OF salary ON employees FOR EACH ROW BEGIN -- bind variables are used here for values INSERT INTO emp_audit VALUES( :old.employee_id, SYSDATE, :new.salary, :old.salary ); END; /
For more information about triggers, see Chapter 9, "Using Triggers".
A PL/SQL package bundles logically related types, variables, cursors, and subprograms into a database object called a package. The package defines a simple, clear, interface to a set of related subprograms and types that can be accessed by SQL statements.
PL/SQL allows you to access many predefined packages (see "Access to Predefined Packages") and to create your own packages.
A package usually has two parts: a specification and a body.
The specification defines the application programming interface (API); it declares the types, constants, variables, exceptions, cursors, and subprograms. To create a package specification, use the SQL statement CREATE
PACKAGE
. For more information, see Oracle Database SQL Language Reference.
The body contains the SQL queries for cursors and the code for subprograms.To create a package body, use the SQL statement CREATE
PACKAGE
BODY
. For more information, see Oracle Database SQL Language Reference.
In Example 1-19, the emp_actions
package contains two procedures that update the employees
table and one function that provides information.
Example 1-19 Creating a Package and Package Body
-- Package specification: CREATE OR REPLACE PACKAGE emp_actions AS PROCEDURE hire_employee (employee_id NUMBER, last_name VARCHAR2, first_name VARCHAR2, email VARCHAR2, phone_number VARCHAR2, hire_date DATE, job_id VARCHAR2, salary NUMBER, commission_pct NUMBER, manager_id NUMBER, department_id NUMBER); PROCEDURE fire_employee (emp_id NUMBER); FUNCTION num_above_salary (emp_id NUMBER) RETURN NUMBER; END emp_actions; / -- Package body: CREATE OR REPLACE PACKAGE BODY emp_actions AS -- Code for procedure hire_employee: PROCEDURE hire_employee (employee_id NUMBER, last_name VARCHAR2, first_name VARCHAR2, email VARCHAR2, phone_number VARCHAR2, hire_date DATE, job_id VARCHAR2, salary NUMBER, commission_pct NUMBER, manager_id NUMBER, department_id NUMBER) IS BEGIN INSERT INTO employees VALUES (employee_id, last_name, first_name, email, phone_number, hire_date, job_id, salary, commission_pct, manager_id, department_id); END hire_employee; -- Code for procedure fire_employee: PROCEDURE fire_employee (emp_id NUMBER) IS BEGIN DELETE FROM employees WHERE employee_id = emp_id; END fire_employee; -- Code for function num_above_salary: FUNCTION num_above_salary (emp_id NUMBER) RETURN NUMBER IS emp_sal NUMBER(8,2); num_count NUMBER; BEGIN SELECT salary INTO emp_sal FROM employees WHERE employee_id = emp_id; SELECT COUNT(*) INTO num_count FROM employees WHERE salary > emp_sal; RETURN num_count; END num_above_salary; END emp_actions; /
To invoke a packaged subprogram, you need to know only name of the package and the name and parameters of the subprogram (therefore, you can change the implementation details inside the package body without affecting the invoking applications).
Example 1-20 invokes the emp_actions
package procedures hire_employee
and fire_employee
.
Example 1-20 Invoking a Procedure in a Package
CALL emp_actions.hire_employee(300, 'Belden', 'Enrique', 'EBELDEN', '555.111.2222', '31-AUG-04', 'AC_MGR', 9000, .1, 101, 110); BEGIN DBMS_OUTPUT.PUT_LINE ('Number of employees with higher salary: ' || TO_CHAR(emp_actions.num_above_salary(120))); emp_actions.fire_employee(300); END; /
Packages are stored in Oracle Database, where they can be shared by many applications. Invoking a packaged subprogram for the first time loads the whole package and caches it in memory, saving on disk I/O for subsequent invocations. Thus, packages enhance re-use and improve performance in a multiuser, multi-application environment.
For more information about packages, see Chapter 10, "Using PL/SQL Packages".
PL/SQL provides conditional compilation, which allows you to customize the functionality in a PL/SQL application without having to remove any source code. For example, you can:
Use the latest functionality with the latest database release and disable the new features to run the application against an older release of the database.
Activate debugging or tracing functionality in the development environment and hide that functionality in the application while it runs at a production site.
For more information, see "Conditional Compilation".
Processing a SQL query with PL/SQL is like processing files with other languages. For example, a PERL program opens a file, reads the file contents, processes each line, then closes the file. In the same way, a PL/SQL program issues a query and processes the rows from the result set as shown in Example 1-21.
Example 1-21 Processing Query Results in a LOOP
BEGIN FOR someone IN (SELECT * FROM employees WHERE employee_id < 120 ) LOOP DBMS_OUTPUT.PUT_LINE('First name = ' || someone.first_name || ', Last name = ' || someone.last_name); END LOOP; END; /
You can use a simple loop like the one shown here, or you can control the process precisely by using individual statements to perform the query, retrieve data, and finish processing.
Topics:
The PL/SQL compilation and run-time system is an engine that compiles and executes PL/SQL compilation units. The engine can be installed in Oracle Database or in an application development tool, such as Oracle Forms.
In either environment, the PL/SQL engine accepts as input any valid PL/SQL compilation unit. The engine executes procedural statements, but sends SQL statements to the SQL engine in the Oracle Database, as shown in Figure 1-2.
Typically, Oracle Database processes PL/SQL compilation units.
When an application development tool processes PL/SQL compilation units, it passes them to its local PL/SQL engine. If a compilation unit contains no SQL statements, the local engine processes the entire compilation unit. This is useful if the application development tool can benefit from conditional and iterative control.
For example, Oracle Forms applications frequently use SQL statements to test the values of field entries and do simple computations. By using PL/SQL instead of SQL, these applications can avoid calls to Oracle Database.
A PL/SQL compilation unit is any one of the following:
FUNCTION
PACKAGE
PACKAGE
BODY
PROCEDURE
TRIGGER
TYPE
TYPE
BODY
Compilation units are affected by PL/SQL compilation parameters (a category of Oracle Database initialization parameters). Different compilation units—for example, a package specification and its body— can have different compilation parameter settings.
Table 1-1 lists and briefly describes the PL/SQL compilation parameters. For more information about these parameters, see Oracle Database Reference.
To display the values of these parameters, use the static data dictionary view ALL_PLSQL_OBJECT_SETTINGS
. For more information about this view, see Oracle Database Reference.
Table 1-1 PL/SQL Compilation Parameters
Parameter | Description |
---|---|
Controls the compile-time collection, cross reference, and storage of PL/SQL source code identifier data. Used by the PL/Scope tool, which is described in Oracle Database Advanced Application Developer's Guide. |
|
Enables you to control conditional compilation of each PL/SQL unit independently. |
|
Specifies the compilation mode for PL/SQL program units— If the optimization level (set by
|
|
Specifies whether or not PL/SQL units will be compiled for debugging. See note following table. |
|
Specifies the name of the directory where shared objects produced by the native compiler are stored. See note following table. |
|
Specifies the number of subdirectories in the directory specified by |
|
Specifies the optimization level at which to compile PL/SQL units (the higher the level, the more optimizations the compiler tries to make). If |
|
Enables or disables the reporting of warning messages by the PL/SQL compiler, and specifies which warning messages to show as errors. |
|
Enables you to create |
Footnote 1 The compile-time value of this parameter is stored with the metadata of the PL/SQL program unit.
Note:
The following compilation parameters are deprecated and might be unavailable in future Oracle Database releases:PLSQL_DEBUG
Instead of PLSQL_DEBUG
, Oracle recommends using PLSQL_OPTIMIZE_LEVEL=1
.
PLSQL_NATIVE_LIBRARY_DIR
PLSQL_NATIVE_LIBRARY_SUBDIR_COUNT
For Release 11.1, they have the same effects as they had for Release 10.2—described in Table 1-1—but the compiler warns you that they are deprecated.
The compile-time values of most of the parameters in Table 1-1 are stored with the metadata of the PL/SQL program unit, which means you can re-use those values when you explicitly recompile the program unit by doing the following:
Use one of the following statements to recompile the program unit:
ALTER
FUNCTION
COMPILE
ALTER
PACKAGE
COMPILE
ALTER
PROCEDURE
COMPILE
Include the REUSE
SETTINGS
clause in the statement.
This clause preserves the existing settings and uses them for the recompilation of any parameters for which values are not specified elsewhere in the statement.
If you use the SQL statement CREATE
OR
REPLACE
to explicitly compile a PL/SQL subprogram, or if you do not include the REUSE
SETTINGS
clause in the ALTER
COMPILE
statement, then the value of the compilation parameter is its value for the session.
See Also:
Oracle Database SQL Language Reference for more information about the ALTER
FUNCTION
statement
Oracle Database SQL Language Reference for more information about the ALTER
PACKAGE
statement
Oracle Database SQL Language Reference for more information about the ALTER
PROCEDURE
statement