PL/SQL is a modern, block-structured programming language. It provides several features that make developing powerful database applications very convenient. For example, PL/SQL provides procedural constructs, such as loops and conditional statements, that are not available in standard SQL.
You can directly enter SQL data manipulation language (DML) statements inside PL/SQL blocks, and you can use subprograms supplied by Oracle to perform data definition language (DDL) statements.
PL/SQL code runs on the server, so using PL/SQL lets you centralize significant parts of your database applications for increased maintainability and security. It also enables you to achieve a significant reduction of network overhead in client/server applications.
Note:Some Oracle tools, such as Oracle Forms, contain a PL/SQL engine that lets you run PL/SQL locally.
You can even use PL/SQL for some database applications in place of 3GL programs that use embedded SQL or Oracle Call Interface (OCI).
PL/SQL units include:
Oracle Database PL/SQL Language Reference for syntax and examples of operations on PL/SQL packages
Oracle Database PL/SQL Packages and Types Reference for information about the PL/SQL packages that come with Oracle Database
Oracle Database Concepts for information about dependencies among stored PL/SQL units
The declarative part declares PL/SQL variables, exceptions, and cursors. The executable part contains PL/SQL code and SQL statements, and can contain nested blocks.
Exception handlers contain code that is invoked when the exception is raised, either as a predefined PL/SQL exception (such as
ZERO_DIVIDE) or as an exception that you define.
Anonymous blocks are usually used interactively from a tool, such as SQL*Plus, or in a precompiler, OCI, or SQL*Module application. They are usually used to invoke stored subprograms or to open cursor variables.
The anonymous block in Example 7-1 uses the
DBMS_OUTPUT package to print the names of all employees in the
EMPLOYEES table who are in department 20.
SQL> DECLARE 2 last_name VARCHAR2(10); 3 cursor c1 IS SELECT LAST_NAME 4 FROM EMPLOYEES 5 WHERE DEPARTMENT_ID = 20; 6 BEGIN 7 OPEN c1; 8 LOOP 9 FETCH c1 INTO last_name; 10 EXIT WHEN c1%NOTFOUND; 11 DBMS_OUTPUT.PUT_LINE(last_name); 12 END LOOP; 13 END; 14 / Hartstein Fay PL/SQL procedure successfully completed. SQL>
Exceptions let you handle Oracle Database error conditions with PL/SQL program logic. This enables your application to prevent the server from issuing an error that can cause the client application to end. The anonymous block in Example 7-2 handles the predefined Oracle Database exception
NO_DATA_FOUND (which results in ORA-01403 if not handled).
SQL> DECLARE 2 Emp_number INTEGER := 9999 3 Emp_name VARCHAR2(10); 4 BEGIN 5 SELECT LAST_NAME INTO Emp_name 6 FROM EMPLOYEES 7 WHERE EMPLOYEE_ID = Emp_number; 8 DBMS_OUTPUT.PUT_LINE('Employee name is ' || Emp_name); 9 EXCEPTION 10 WHEN NO_DATA_FOUND THEN 11 DBMS_OUTPUT.PUT_LINE('No such employee: ' || Emp_number); 12 END; 13 / No such employee: 9999 PL/SQL procedure successfully completed. SQL>
You can also define your own exceptions, declare them in the declaration part of a block, and define them in the exception part of the block, as in Example 7-3.
SQL> DECLARE 2 Emp_name VARCHAR2(10); 3 Emp_number INTEGER; 4 Empno_out_of_range EXCEPTION; 5 BEGIN 6 Emp_number := 10001; 7 IF Emp_number > 9999 OR Emp_number < 1000 THEN 8 RAISE Empno_out_of_range; 9 ELSE 10 SELECT LAST_NAME INTO Emp_name FROM EMPLOYEES 11 WHERE EMPLOYEE_ID = Emp_number; 12 DBMS_OUTPUT.PUT_LINE('Employee name is ' || Emp_name); 13 END IF; 14 EXCEPTION 15 WHEN Empno_out_of_range THEN 16 DBMS_OUTPUT.PUT_LINE('Employee number ' || Emp_number || 17 ' is out of range.'); 18 END; 19 / Employee number 10001 is out of range. PL/SQL procedure successfully completed. SQL>
Oracle Database PL/SQL Packages and Types Reference for complete information about the
Has a name.
Can take parameters, and can return values.
Is stored in the data dictionary.
Can be invoked by many users.
Because a subprogram is stored in the database, it must be named. This distinguishes it from other stored subprograms and makes it possible for applications to invoke it. Each publicly-visible subprogram in a schema must have a unique name, and the name must be a legal PL/SQL identifier.
Note:If you plan to invoke a stored subprogram using a stub generated by SQL*Module, then the stored subprogram name must also be a legal identifier in the invoking host 3GL language, such as Ada or C.
Stored subprograms can take parameters. In the procedure in Example 7-4, the department number is an input parameter that is used when the parameterized cursor
c1 is opened.
SQL> CREATE OR REPLACE PROCEDURE get_emp_names ( 2 dept_num IN NUMBER 3 ) 4 IS 5 emp_name VARCHAR2(10); 6 CURSOR c1 (dept_num NUMBER) IS 7 SELECT LAST_NAME FROM EMPLOYEES 8 WHERE DEPARTMENT_ID = dept_num; 9 BEGIN 10 OPEN c1(dept_num); 11 LOOP 12 FETCH c1 INTO emp_name; 13 EXIT WHEN C1%NOTFOUND; 14 DBMS_OUTPUT.PUT_LINE(emp_name); 15 END LOOP; 16 CLOSE c1; 17 END; 18 / Procedure created. SQL>
The formal parameters of a subprogram have three major attributes, described in Table 7-1.
This must be a legal PL/SQL identifier.
This indicates whether the parameter is an input-only parameter (
This is a standard PL/SQL data type.
Parameter modes define the action of formal parameters. You can use the three parameter modes,
IN (the default),
OUT, with any subprogram. Avoid using the
OUT modes with functions. Good programming practice dictates that a function returns a single value and does not change the values of variables that are not local to the subprogram.
Table 7-2 summarizes the information about parameter modes.
Must be specified.
Must be specified.
Passes values to a subprogram.
Returns values to the caller.
Passes initial values to a subprogram; returns updated values to the caller.
Formal parameter acts like a constant.
Formal parameter acts like an uninitialized variable.
Formal parameter acts like an initialized variable.
Formal parameter cannot be assigned a value.
Formal parameter cannot be used in an expression; must be assigned a value.
Formal parameter must be assigned a value.
Actual parameter can be a constant, initialized variable, literal, or expression.
Actual parameter must be a variable.
Actual parameter must be a variable.
See Also:Oracle Database PL/SQL Language Reference for details about parameter modes
An unconstrained type name, such as
A type that is constrained using the
Note:Numerically constrained types such as
20) are not allowed in a parameter list.
Use the type attributes
%ROWTYPE to constrain the parameter. For example, the procedure heading in Example 7-4 can be written as follows:
PROCEDURE get_emp_names(dept_num IN EMPLOYEES.DEPARTMENT_ID%TYPE)
This gives the
dept_num parameter the same data type as the
DEPARTMENT_ID column in the
EMPLOYEES table. The column and table must be available when a declaration using
%ROWTYPE) is elaborated.
%TYPE is recommended, because if the type of the column in the table changes, it is not necessary to change the application code.
get_emp_names procedure is part of a package, you can use previously-declared public (package) variables to constrain its parameter data types. For example:
dept_number NUMBER(2); ... PROCEDURE get_emp_names(dept_num IN dept_number%TYPE);
%ROWTYPE attribute to create a record that contains all the columns of the specified table. The procedure in Example 7-5 returns all the columns of the
EMPLOYEES table in a PL/SQL record for the given employee ID.
SQL> CREATE OR REPLACE PROCEDURE get_emp_rec ( 2 emp_number IN EMPLOYEES.EMPLOYEE_ID%TYPE, 3 emp_info OUT EMPLOYEES%ROWTYPE 4 ) 5 IS 6 BEGIN 7 SELECT * INTO emp_info 8 FROM EMPLOYEES 9 WHERE EMPLOYEE_ID = emp_number; 10 END; 11 / Procedure created. SQL> SQL> -- Invoke procedure from PL/SQL block: SQL> SQL> DECLARE 2 emp_row EMPLOYEES%ROWTYPE; 3 BEGIN 4 get_emp_rec(206, emp_row); 5 DBMS_OUTPUT.PUT('EMPLOYEE_ID: ' || emp_row.EMPLOYEE_ID); 6 DBMS_OUTPUT.NEW_LINE; 7 DBMS_OUTPUT.PUT('FIRST_NAME: ' || emp_row.FIRST_NAME); 8 DBMS_OUTPUT.NEW_LINE; 9 DBMS_OUTPUT.PUT('LAST_NAME: ' || emp_row.LAST_NAME); 10 DBMS_OUTPUT.NEW_LINE; 11 DBMS_OUTPUT.PUT('EMAIL: ' || emp_row.EMAIL); 12 DBMS_OUTPUT.NEW_LINE; 13 DBMS_OUTPUT.PUT('PHONE_NUMBER: ' || emp_row.PHONE_NUMBER); 14 DBMS_OUTPUT.NEW_LINE; 15 DBMS_OUTPUT.PUT('HIRE_DATE: ' || emp_row.HIRE_DATE); 16 DBMS_OUTPUT.NEW_LINE; 17 DBMS_OUTPUT.PUT('JOB_ID: ' || emp_row.JOB_ID); 18 DBMS_OUTPUT.NEW_LINE; 19 DBMS_OUTPUT.PUT('SALARY: ' || emp_row.SALARY); 20 DBMS_OUTPUT.NEW_LINE; 21 DBMS_OUTPUT.PUT('COMMISSION_PCT: ' || emp_row.COMMISSION_PCT); 22 DBMS_OUTPUT.NEW_LINE; 23 DBMS_OUTPUT.PUT('MANAGER_ID: ' || emp_row.MANAGER_ID); 24 DBMS_OUTPUT.NEW_LINE; 25 DBMS_OUTPUT.PUT('DEPARTMENT_ID: ' || emp_row.DEPARTMENT_ID); 26 DBMS_OUTPUT.NEW_LINE; 27 END; 28 / EMPLOYEE_ID: 206 FIRST_NAME: William LAST_NAME: Gietz EMAIL: WGIETZ PHONE_NUMBER: 415.555.0100 HIRE_DATE: 07-JUN-94 JOB_ID: AC_ACCOUNT SALARY: 8300 COMMISSION_PCT: MANAGER_ID: 205 DEPARTMENT_ID: 110 PL/SQL procedure successfully completed. SQL>
Stored functions can return values that are declared using
%ROWTYPE. For example:
FUNCTION get_emp_rec (dept_num IN EMPLOYEES.DEPARTMENT_ID%TYPE) RETURN EMPLOYEES%ROWTYPE IS ...
Note:When passing a user defined type, such as a PL/SQL table or record to a remote subprogram, to make PL/SQL use the same definition so that the type checker can verify the source, you must create a redundant loop back DBLINK so that when the PL/SQL compiles, both sources pull from the same location.
Parameters can take default values. Use the
DEFAULT keyword or the assignment operator to give a parameter a default value. For example, the specification for the
Get_emp_names procedure can be written as the following:
PROCEDURE Get_emp_names (Dept_num IN NUMBER DEFAULT 20) IS ...
PROCEDURE Get_emp_names (Dept_num IN NUMBER := 20) IS ...
When a parameter takes a default value, it can be omitted from the actual parameter list when you invoke the subprogram. When you do specify the parameter value on the invocation, it overrides the default value.
Note:Unlike in an anonymous PL/SQL block, you do not use the keyword
DECLAREbefore the declarations of variables, cursors, and exceptions in a stored subprogram. In fact, it is an error to use it.
This loads the procedure into the current schema from the
sql file (
.sql is the default file extension). The slash (/) at the end of the code is not part of the code, it only activates the loading of the procedure.
Caution:When developing a new subprogram, it is usually preferable to use the statement
FUNCTION. This statement replaces any previous version of that subprogram in the same schema with the newer version, but without warning.
You can use either the keyword
AS after the subprogram parameter list.
You must have the
PROCEDURE system privilege to create a subprogram or package in your schema, or the
PROCEDURE system privilege to create a subprogram or package in another user's schema. In either case, the package body must be created in the same schema as the package.
Note:To create without errors (to compile the subprogram or package successfully) requires the following additional privileges:
The owner of the subprogram or package must be explicitly granted the necessary object privileges for all objects referenced within the body of the code.
The owner cannot obtain required privileges through roles.
If the privileges of the owner of a subprogram or package change, then the subprogram must be reauthenticated before it is run. If a necessary privilege to a referenced object is revoked from the owner of the subprogram or package, then the subprogram cannot be run.
EXECUTE privilege on a subprogram gives a user the right to run a subprogram owned by another user. Privileged users run the subprogram under the security domain of the owner of the subprogram. Therefore, users need not be granted the privileges to the objects referenced by a subprogram. This allows for more disciplined and efficient security strategies with database applications and their users. Furthermore, all subprograms and packages are stored in the data dictionary (in the
SYSTEM tablespace). No quota controls the amount of space available to a user who creates subprograms and packages.
Note:Package creation requires a sort. The user creating the package must be able to create a sort segment in the temporary tablespace with which the user is associated.
To alter a subprogram, you must first drop it using the
FUNCTION statement, then re-create it using the
FUNCTION statement. Alternatively, use the
FUNCTION statement, which first drops the subprogram if it exists, then re-creates it as specified.
Caution:The subprogram is dropped without warning.
A standalone subprogram, a standalone function, a package body, or an entire package can be dropped using the SQL statements
PACKAGE, respectively. A
PACKAGE statement drops both the specification and body of a package.
The following statement drops the
Old_sal_raise procedure in your schema:
DROP PROCEDURE Old_sal_raise;
To drop a subprogram or package, the subprogram or package must be in your schema, or you must have the
PROCEDURE privilege. An individual subprogram within a package cannot be dropped; the containing package specification and body must be re-created without the subprograms to be dropped.
A PL/SQL subprogram executing on an Oracle Database instance can invoke an external subprogram written in a third-generation language (3GL). The 3GL subprogram runs in a separate address space from that of the database.
See Also:Chapter 14, "Developing Applications Using Multiple Programming Languages," for information about external subprograms
Using the PL/SQL function result cache can save significant space and time. Each time a result-cached PL/SQL function is invoked with different parameter values, those parameters and their result are stored in the cache. Subsequently, when the same function is invoked with the same parameter values, the result is retrieved from the cache, instead of being recomputed. Because the cache is stored in a shared global area (SGA), it is available to any session that runs your application.
If a database object that was used to compute a cached result is updated, the cached result becomes invalid and must be recomputed.
The best candidates for result-caching are functions that are invoked frequently but depend on information that changes infrequently or never.
For more information about the PL/SQL function result cache, see Oracle Database PL/SQL Language Reference.
Let you organize your application development more efficiently.
Let you grant privileges more efficiently.
Let you modify package objects without recompiling dependent schema objects.
Enable Oracle Database to read multiple package objects into memory at once.
Can contain global variables and cursors that are available to all subprograms in the package.
See Also:Oracle Database PL/SQL Language Reference for more information about subprogram name overloading
The specification part of a package declares the public types, variables, constants, and subprograms that are visible outside the immediate scope of the package. The body of a package defines the objects declared in the specification, as well as private objects that are not visible to applications outside the package.
The SQL*Plus script in Example 7-6 creates a package that contains one stored function and two stored procedures, and then invokes one of the procedures.
SQL> -- Sequence that packaged function needs: SQL> SQL> CREATE SEQUENCE emp_sequence 2 START WITH 8000 3 INCREMENT BY 10; Sequence created. SQL> SQL> -- Package specification: SQL> SQL> CREATE or REPLACE PACKAGE employee_management IS 2 3 FUNCTION hire_emp ( 4 firstname VARCHAR2, 5 lastname VARCHAR2, 6 email VARCHAR2, 7 phone VARCHAR2, 8 hiredate DATE, 9 job VARCHAR2, 10 sal NUMBER, 11 comm NUMBER, 12 mgr NUMBER, 13 deptno NUMBER 14 ) RETURN NUMBER; 15 16 PROCEDURE fire_emp( 17 emp_id IN NUMBER 18 ); 19 20 PROCEDURE sal_raise ( 21 emp_id IN NUMBER, 22 sal_incr IN NUMBER 23 ); 24 END employee_management; 25 / Package created. SQL> -- Package body: SQL> SQL> CREATE or REPLACE PACKAGE BODY employee_management IS 2 3 FUNCTION hire_emp ( 4 firstname VARCHAR2, 5 lastname VARCHAR2, 6 email VARCHAR2, 7 phone VARCHAR2, 8 hiredate DATE, 9 job VARCHAR2, 10 sal NUMBER, 11 comm NUMBER, 12 mgr NUMBER, 13 deptno NUMBER 14 ) RETURN NUMBER 15 IS 16 new_empno NUMBER(10); 17 BEGIN
18 new_empno := emp_sequence.NEXTVAL; 19 20 INSERT INTO EMPLOYEES VALUES ( 21 new_empno, 22 firstname, 23 lastname, 24 email, 25 phone, 26 hiredate, 27 job, 28 sal, 29 comm, 30 mgr, 31 deptno 32 ); 33 34 RETURN (new_empno); 35 END hire_emp; 36 37 PROCEDURE fire_emp ( 38 emp_id IN NUMBER 39 ) IS 40 BEGIN 41 DELETE FROM EMPLOYEES 42 WHERE EMPLOYEE_ID = emp_id; 43 44 IF SQL%NOTFOUND THEN 45 raise_application_error( 46 -20011, 47 'Invalid Employee Number: ' || TO_CHAR(Emp_id) 48 ); 49 END IF; 50 END fire_emp; 51 52 PROCEDURE sal_raise ( 53 emp_id IN NUMBER, 54 sal_incr IN NUMBER 55 ) IS 56 BEGIN 57 UPDATE EMPLOYEES 58 SET SALARY = SALARY + sal_incr 59 WHERE EMPLOYEE_ID = emp_id; 60 61 IF SQL%NOTFOUND THEN 62 raise_application_error( 63 -20011, 64 'Invalid Employee Number: ' || TO_CHAR(Emp_id) 65 ); 66 END IF; 67 END sal_raise; 68 END employee_management; 69 / Package body created. SQL> SQL> -- Invoke packaged procedures: SQL> SQL> DECLARE 2 empno NUMBER(6); 3 sal NUMBER(6); 4 temp NUMBER(6); 5 BEGIN 6 empno := employee_management.hire_emp( 7 'John', 8 'Doe', 9 'email@example.com', 10 '555-0100', 11 '20-SEP-07', 12 'ST_CLERK', 13 2500, 14 0, 15 100, 16 20); 17 18 DBMS_OUTPUT.PUT_LINE('New employee ID is ' || TO_CHAR(empno)); 19 END; 20 / New employee ID is 8000 PL/SQL procedure successfully completed. SQL>
The size limit for PL/SQL stored database objects such as subprograms, triggers, and packages is the size of the Descriptive Intermediate Attributed Notation for Ada (DIANA) code in the shared pool in bytes. The Linux and UNIX limit on the size of the flattened DIANA/code size is 64K but the limit might be 32K on desktop platforms.
The most closely related number that a user can access is the
PARSED_SIZE in the static data dictionary view
*_OBJECT_SIZE. That gives the size of the DIANA in bytes as stored in the
SYS.IDL_xxx$ tables. This is not the size in the shared pool. The size of the DIANA part of PL/SQL code (used during compilation) is significantly larger in the shared pool than it is in the system table.
To create a package body, use the
BODY statement. The
BODY statement defines the procedural code of the public subprograms declared in the package specification.
You can also define private, or local, package subprograms, and variables in a package body. These objects can only be accessed by other subprograms in the body of the same package. They are not visible to external users, regardless of the privileges they hold.
It is often more convenient to add the
REPLACE clause in the
BODY statements when you are first developing your application. The effect of this option is to drop the package or the package body without warning. The
CREATE statements are:
CREATE OR REPLACE PACKAGE Package_name AS ...
CREATE OR REPLACE PACKAGE BODY Package_name AS ...
The body of a package can contain:
Subprograms declared in the package specification.
Definitions of cursors declared in the package specification.
Local subprograms, not declared in the package specification.
Subprograms, cursors, and variables that are declared in the package specification are global. They can be invoked, or used, by external users that have
EXECUTE permission for the package or that have
When you create the package body, ensure that each subprogram that you define in the body has the same parameters, by name, data type, and mode, as the declaration in the package specification. For functions in the package body, the parameters and the return type must agree in name and type.
The names of a package and all public objects in the package must be unique within a given schema. The package specification and its body must have the same name. All package constructs must have unique names within the scope of the package, unless overloading of subprogram names is desired.
Each session that references a package object has its own instance of the corresponding package, including persistent state for any public and private variables, cursors, and constants. If any of the session's instantiated packages (specification or body) are invalidated, then all package instances in the session are invalidated and recompiled. As a result, the session state is lost for all package instances in the session.
When a package in a given session is invalidated, the session receives ORA-04068 the first time it attempts to use any object of the invalid package instance. The second time a session makes such a package call, the package is reinstantiated for the session without error.
Note:For optimal performance, Oracle Database returns this error message only once—each time the package state is discarded.
If you handle this error in your application, ensure that your error handling strategy can accurately handle this error. For example, when a subprogram in one package invokes a subprogram in another package, your application must be aware that the session state is lost for both packages.
In most production environments, DDL operations that can cause invalidations are usually performed during inactive working hours; therefore, this situation might not be a problem for end-user applications. However, if package invalidations are common in your system during working hours, then you might want to code your applications to handle this error when package calls are made.
There are many packages provided with Oracle Database, either to extend the functionality of the database or to give PL/SQL access to SQL features. You can invoke these packages from your application.
See Also:Oracle Database PL/SQL Packages and Types Reference for an overview of these Oracle Database packages
Oracle Database uses two engines to run PL/SQL blocks and subprograms. The PL/SQL engine runs procedural statements, while the SQL engine runs SQL statements. During execution, every SQL statement causes a context switch between the two engines, resulting in performance overhead.
Performance can be improved substantially by minimizing the number of context switches required to run a particular block or subprogram. When a SQL statement runs inside a loop that uses collection elements as bind variables, the large number of context switches required by the block can cause poor performance. Collections include the following:
Binding is the assignment of values to PL/SQL variables in SQL statements. Bulk binding is binding an entire collection at once. Bulk binds pass the entire collection back and forth between the two engines in a single operation.
Typically, using bulk binds improves performance for SQL statements that affect four or more database rows. The more rows affected by a SQL statement, the greater the performance gain from bulk binds.
Note:This section provides an overview of bulk binds to help you decide whether to use them in your PL/SQL applications. For detailed information about using bulk binds, including ways to handle exceptions that occur in the middle of a bulk bind operation, see Oracle Database PL/SQL Language Reference.
Parallel DML is disabled with bulk binds.
The PL/SQL block in Example 7-7 increases the salary for employees whose manager's ID number is 7902, 7698, or 7839, with and without bulk binds. Without bulk bind, PL/SQL sends a SQL statement to the SQL engine for each updated employee, leading to context switches that slow performance.
SQL> DECLARE 2 TYPE numlist IS VARRAY (100) OF NUMBER; 3 id NUMLIST := NUMLIST(7902, 7698, 7839); 4 BEGIN 5 -- Efficient method, using bulk bind: 6 7 FORALL i IN id.FIRST..id.LAST 8 UPDATE EMPLOYEES 9 SET SALARY = 1.1 * SALARY 10 WHERE MANAGER_ID = id(i); 11 12 -- Slower method: 13 14 FOR i IN id.FIRST..id.LAST LOOP 15 UPDATE EMPLOYEES 16 SET SALARY = 1.1 * SALARY 17 WHERE MANAGER_ID = id(i); 18 END LOOP; 19 END; 20 / PL/SQL procedure successfully completed. SQL>
The PL/SQL block in Example 7-8 queries multiple values into PL/SQL tables, with and without bulk binds. Without bulk bind, PL/SQL sends a SQL statement to the SQL engine for each selected employee, leading to context switches that slow performance.
SQL> DECLARE 2 TYPE var_tab IS TABLE OF VARCHAR2(20) 3 INDEX BY PLS_INTEGER; 4 5 empno VAR_TAB; 6 ename VAR_TAB; 7 counter NUMBER; 8 9 CURSOR c IS 10 SELECT EMPLOYEE_ID, LAST_NAME 11 FROM EMPLOYEES 12 WHERE MANAGER_ID = 7698; 13 BEGIN 14 -- Efficient method, using bulk bind: 15 16 SELECT EMPLOYEE_ID, LAST_NAME BULK COLLECT 17 INTO empno, ename 18 FROM EMPLOYEES 19 WHERE MANAGER_ID = 7698; 20 21 -- Slower method: 22 23 counter := 1; 24 25 FOR rec IN c LOOP 26 empno(counter) := rec.EMPLOYEE_ID; 27 ename(counter) := rec.LAST_NAME; 28 counter := counter + 1; 29 END LOOP; 30 END; 31 / PL/SQL procedure successfully completed. SQL>
The PL/SQL block in Example 7-9 updates the
EMPLOYEES table by computing bonuses for a collection of employees. Then it returns the bonuses in a column called
bonus_list_inst. The actions are performed with and without bulk binds. Without bulk bind, PL/SQL sends a SQL statement to the SQL engine for each updated employee, leading to context switches that slow performance.
SQL> DECLARE 2 TYPE emp_list IS VARRAY(100) OF EMPLOYEES.EMPLOYEE_ID%TYPE; 3 empids emp_list := emp_list(182, 187, 193, 200, 204, 206); 4 5 TYPE bonus_list IS TABLE OF EMPLOYEES.SALARY%TYPE; 6 bonus_list_inst bonus_list; 7 8 BEGIN 9 -- Efficient method, using bulk bind: 10 11 FORALL i IN empids.FIRST..empids.LAST 12 UPDATE EMPLOYEES 13 SET SALARY = 0.1 * SALARY 14 WHERE EMPLOYEE_ID = empids(i) 15 RETURNING SALARY BULK COLLECT INTO bonus_list_inst; 16 17 -- Slower method: 18 19 FOR i IN empids.FIRST..empids.LAST LOOP 20 UPDATE EMPLOYEES 21 SET SALARY = 0.1 * SALARY 22 WHERE EMPLOYEE_ID = empids(i) 23 RETURNING SALARY INTO bonus_list_inst(i); 24 END LOOP; 25 END; 26 / PL/SQL procedure successfully completed. SQL>
A trigger is a special kind of PL/SQL anonymous block. You can define triggers to fire before or after SQL statements, either on a statement level or for each row that is affected. You can also define
OF triggers or system triggers (triggers on
See Also:Oracle Database PL/SQL Language Referencefor more information about triggers
You can use native compilation with both the supplied packages and the subprograms you write yourself. Subprograms compiled this way work in all server environments, such as the shared server configuration (formerly known as multithreaded server) and Oracle Real Application Clusters (Oracle RAC).
This technique is most effective for computation-intensive subprograms that do not spend much time executing SQL, because it can do little to speed up SQL statements invoked from these subprograms.
With Java, you can use the
ncomp tool to compile your own packages and classes.
A cursor is a static object; a cursor variable is a pointer to a cursor. Because cursor variables are pointers, they can be passed and returned as parameters to subprograms. A cursor variable can also refer to different cursors in its lifetime.
Additional advantages of cursor variables include the following:
Queries are centralized in the stored subprogram that opens the cursor variable.
If you must change the cursor, then you only make the change in the stored subprogram, not in each application.
The user of the application is the username used when the application connects to the server. The user must have
EXECUTE permission on the stored subprogram that opens the cursor. But, the user need not have
READ permission on the tables used in the query. This capability can be used to limit access to the columns in the table, as well as access to other stored subprograms.
See Also:Oracle Database PL/SQL Language Reference for more information about cursor variables
Memory is usually allocated for a cursor variable in the client application using the appropriate
ALLOCATE statement. In Pro*C, use the
cursor_name statement. In OCI, use the Cursor Data Area.
You can also use cursor variables in applications that run entirely in a single server session. You can declare cursor variables in PL/SQL subprograms, open them, and use them as parameters for other PL/SQL subprograms.
See Also:For additional cursor variable examples that use programmatic interfaces:
Example 7-10 creates a package that defines a PL/SQL cursor variable type and two procedures, and then invokes the procedures from a PL/SQL block. The first procedure opens a cursor variable using a bind variable in the
WHERE clause. The second procedure uses a cursor variable to fetch rows from the
SQL> CREATE OR REPLACE PACKAGE emp_data AS 2 3 TYPE emp_val_cv_type IS REF CURSOR 4 RETURN EMPLOYEES%ROWTYPE; 5 6 PROCEDURE open_emp_cv ( 7 emp_cv IN OUT emp_val_cv_type, 8 dept_number IN EMPLOYEES.DEPARTMENT_ID%TYPE 9 ); 10 11 PROCEDURE fetch_emp_data ( 12 emp_cv IN emp_val_cv_type, 13 emp_row OUT EMPLOYEES%ROWTYPE 14 ); 15 END emp_data; 16 / Package created. SQL> CREATE OR REPLACE PACKAGE BODY emp_data AS 2 PROCEDURE open_emp_cv ( 3 emp_cv IN OUT emp_val_cv_type, 4 dept_number IN EMPLOYEES.DEPARTMENT_ID%TYPE 5 ) IS 6 BEGIN 7 OPEN emp_cv FOR 8 SELECT * FROM EMPLOYEES 9 WHERE DEPARTMENT_ID = dept_number; 10 END open_emp_cv; 11 12 PROCEDURE fetch_emp_data ( 13 emp_cv IN emp_val_cv_type, 14 emp_row OUT EMPLOYEES%ROWTYPE 15 ) IS 16 BEGIN 17 FETCH emp_cv INTO emp_row; 18 END fetch_emp_data; 19 END emp_data; 20 / Package body created. SQL> SQL> -- Invoke packaged procedures: SQL> SQL> DECLARE 2 emp_curs emp_data.emp_val_cv_type; 3 dept_number EMPLOYEES.DEPARTMENT_ID%TYPE; 4 emp_row EMPLOYEES%ROWTYPE; 5 6 BEGIN 7 dept_number := 20; 8 9 -- Open cursor, using variable: 10 11 emp_data.open_emp_cv(emp_curs, dept_number); 12 13 -- Fetch and display data: 14 15 LOOP 16 emp_data.fetch_emp_data(emp_curs, emp_row); 17 EXIT WHEN emp_curs%NOTFOUND; 18 DBMS_OUTPUT.PUT(emp_row.LAST_NAME || ' '); 19 DBMS_OUTPUT.PUT_LINE(emp_row.SALARY); 20 END LOOP; 21 END; 22 / Hartstein 13000 Fay 6000 PL/SQL procedure successfully completed. SQL>
In Example 7-11, the procedure opens a cursor variable for either the
EMPLOYEES table or the
DEPARTMENTS table, depending on the value of the parameter
discrim. The anonymous block invokes the procedure to open the cursor variable for the
EMPLOYEES table, but fetches from the
DEPARTMENTS table, which raises the predefined exception
SQL> CREATE OR REPLACE PACKAGE emp_dept_data AS 2 TYPE cv_type IS REF CURSOR; 3 4 PROCEDURE open_cv ( 5 cv IN OUT cv_type, 6 discrim IN POSITIVE 7 ); 8 END emp_dept_data; 9 / Package created. SQL> CREATE OR REPLACE PACKAGE BODY emp_dept_data AS 2 PROCEDURE open_cv ( 3 cv IN OUT cv_type, 4 discrim IN POSITIVE) IS 5 BEGIN 6 IF discrim = 1 THEN 7 OPEN cv FOR 8 SELECT * FROM EMPLOYEES; 9 ELSIF discrim = 2 THEN 10 OPEN cv FOR 11 SELECT * FROM DEPARTMENTS; 12 END IF; 13 END open_cv; 14 END emp_dept_data; 15 / Package body created. SQL> DECLARE 2 emp_rec EMPLOYEES%ROWTYPE; 3 dept_rec DEPARTMENTS%ROWTYPE; 4 cv Emp_dept_data.CV_TYPE; 5 BEGIN 6 emp_dept_data.open_cv(cv, 1); -- Open cv for EMPLOYEES fetch. 7 FETCH cv INTO dept_rec; -- Fetch from DEPARTMENTS. 8 DBMS_OUTPUT.PUT(dept_rec.DEPARTMENT_ID); 9 DBMS_OUTPUT.PUT_LINE(' ' || dept_rec.LOCATION_ID); 10 EXCEPTION 11 WHEN ROWTYPE_MISMATCH THEN 12 BEGIN 13 DBMS_OUTPUT.PUT_LINE 14 ('Row type mismatch, fetching EMPLOYEES data ...'); 15 FETCH cv INTO emp_rec; 16 DBMS_OUTPUT.PUT(emp_rec.DEPARTMENT_ID); 17 DBMS_OUTPUT.PUT_LINE(' ' || emp_rec.LAST_NAME); 18 END; 19 END; 20 / Row type mismatch, fetching EMPLOYEES data ... 90 King PL/SQL procedure successfully completed. SQL>
To list compile-time errors, query the static data dictionary view
*_ERRORS. From these views, you can retrieve original source code. The error text associated with the compilation of a subprogram is updated when the subprogram is replaced, and it is deleted when the subprogram is dropped.
SQL*Plus issues a warning message for compile-time errors, but for more information about them, you must use the command
Note:Before issuing the
ERRORSstatement, use the
LINESIZEstatement to get long lines on output. The value 132 is usually a good choice. For example:
SET LINESIZE 132
Example 7-12 has two compile-time errors:
WHER should be
END should be followed by a semicolon.
ERRORS shows the line, column, and description of each error.
SQL> CREATE OR REPLACE PROCEDURE fire_emp ( 2 emp_id NUMBER 3 ) AS 4 BEGIN 5 DELETE FROM EMPLOYEES 6 WHER EMPLOYEE_ID = Emp_id; 7 END 8 / Warning: Procedure created with compilation errors. SQL> SHOW ERRORS; Errors for PROCEDURE FIRE_EMP: LINE/COL ERROR -------- ----------------------------------------------------------------- 5/3 PL/SQL: SQL Statement ignored 6/10 PL/SQL: ORA-00933: SQL command not properly ended 7/3 PLS-00103: Encountered the symbol "end-of-file" when expecting one of the following: ; <an identifier> <a double-quoted delimited-identifier> current delete exists prior <a single-quoted SQL string> The symbol ";" was substituted for "end-of-file" to continue. SQL>
RAISE_APPLICATION_ERROR(error_number, 'text', keep_error_stack)
This procedure stops subprogram execution, rolls back any effects of the subprogram, and returns a user-specified error number and message (unless the error is trapped by an exception handler).
error_number must be in the range of -20000 to -20999.
Use error number -20000 as a generic number for messages where it is important to relay information to the user, but having a unique error number is not required.
Text must be a character expression, 2 Kbytes or less (longer messages are ignored).
Keep_error_stack can be
TRUE if you want to add the error to any already on the stack, or
FALSE if you want to replace the existing errors. By default, this option is
Note:Some of the Oracle Database packages, such as
DBMS_ALERT, use application error numbers in the range -20000 to -20005. See the descriptions of these packages for more information.
RAISE_APPLICATION_ERROR procedure is often used in exception handlers or in the logic of PL/SQL code. For example, the following exception handler selects the string for the associated user-defined error message and invokes the
... WHEN NO_DATA_FOUND THEN SELECT Error_string INTO Message FROM Error_table, V$NLS_PARAMETERS V WHERE Error_number = -20101 AND Lang = v.value AND v.parameter = "NLS_LANGUAGE"; Raise_application_error(-20101, Message); ...
User-defined exceptions are explicitly defined and signaled within the PL/SQL block to control processing of errors specific to the application. When an exception is raised (signaled), the usual execution of the PL/SQL block stops, and a routine called an exception handler is invoked. Specific exception handlers can be written to handle any internal or user-defined exception.
Application code can check for a condition that requires special attention using an
IF statement. If there is an error condition, then two options are available:
You can also define an exception handler to handle user-specified error messages. For example, Figure 7-1 shows the following:
An exception and associated exception handler in a subprogram
A conditional statement that checks for an error (such as transferring funds not available) and enters a user-specified error number and message within a trigger
How user-specified error numbers are returned to the invoking environment (in this case, a subprogram), and how that application can define an exception that corresponds to the user-specified error number
Declare a user-defined exception in a subprogram or package body (private exceptions), or in the specification of a package (public exceptions). Define an exception handler in the body of a subprogram (standalone or package).
In database PL/SQL units, an unhandled user-error condition or internal error condition that is not trapped by an appropriate exception handler causes the implicit rollback of the program unit. If the program unit includes a
COMMIT statement before the point at which the unhandled exception is observed, then the implicit rollback of the program unit can only be completed back to the previous
Additionally, unhandled exceptions in database-stored PL/SQL units propagate back to client-side applications that invoke the containing program unit. In such an application, only the application program unit invocation is rolled back (not the entire application program unit), because it is submitted to the database as a SQL statement.
If unhandled exceptions in database PL/SQL units are propagated back to database applications, modify the database PL/SQL code to handle the exceptions. Your application can also trap for unhandled exceptions when invoking database program units and handle such errors appropriately.
You can use a trigger or a stored subprogram to create a distributed query. This distributed query is decomposed by the local Oracle Database instance into a corresponding number of remote queries, which are sent to the remote nodes for execution. The remote nodes run the queries and send the results back to the local node. The local node then performs any necessary post-processing and returns the results to the user or application.
If a portion of a distributed statement fails, possibly due to a constraint violation, then Oracle Database returns ORA-02055. Subsequent statements, or subprogram invocations, return ORA-02067 until a rollback or a rollback to savepoint is entered.
Design your application to check for any returned error messages that indicates that a portion of the distributed update has failed. If you detect a failure, rollback the entire transaction (or rollback to a savepoint) before allowing the application to proceed.
PL/SQL user-defined exceptions, which must be declared using the keyword
PL/SQL predefined exceptions, such as
SQL errors, such as ORA-00900
Application exceptions, which are generated using the
When using local subprograms, all of these messages can be trapped by writing an exception handler, such as shown in the following example:
EXCEPTION WHEN ZERO_DIVIDE THEN /* Handle the exception */
Notice that the
WHEN clause requires an exception name. If the exception that is raised does not have a name, such as those generated with
RAISE_APPLICATION_ERROR, then one can be assigned using
PRAGMA_EXCEPTION_INIT, as shown in the following example:
DECLARE ... Null_salary EXCEPTION; PRAGMA EXCEPTION_INIT(Null_salary, -20101); BEGIN ... RAISE_APPLICATION_ERROR(-20101, 'salary is missing'); ... EXCEPTION WHEN Null_salary THEN ...
When invoking a remote subprogram, exceptions are also handled by creating a local exception handler. The remote subprogram must return an error number to the local invoking subprogram, which then handles the exception, as shown in the previous example. Because PL/SQL user-defined exceptions always return ORA-06510 to the local subprogram, these exceptions cannot be handled. All other remote exceptions can be handled in the same manner as local exceptions.
Compiling a stored subprogram involves fixing any syntax errors in the code. You might need to do additional debugging to ensure that the subprogram works correctly, performs well, and recovers from errors. Such debugging might involve:
Adding extra output statements to verify execution progress and check data values at certain points within the subprogram.
Running a separate debugger to analyze execution in greater detail.
PL/Scope is a compiler-driven tool that collects and organizes data about user-defined identifiers from PL/SQL source code. Because PL/Scope is a compiler-driven tool, you use it through interactive development environments (such as SQL Developer and JDeveloper), rather than directly.
PL/Scope enables the development of powerful and effective PL/Scope source code browsers that increase PL/SQL developer productivity by minimizing time spent browsing and understanding source code.
For more information about PL/Scope, see Chapter 8, "Using PL/Scope."
The PL/SQL hierarchical profiler reports the dynamic execution profile of your PL/SQL program, organized by subprogram calls. It accounts for SQL and PL/SQL execution times separately. Each subprogram-level summary in the dynamic execution profile includes information such as number of calls to the subprogram, time spent in the subprogram itself, time spent in the subprogram's subtree (that is, in its descendent subprograms), and detailed parent-children information.
You can browse the generated HTML reports in any browser. The browser's navigational capabilities, combined with well chosen links, provide a powerful way to analyze performance of large applications, improve application performance, and lower development costs.
For a detailed description of PL/SQL hierarchical profiler, see Chapter 9, "Using the PL/SQL Hierarchical Profiler."
Recent releases of Oracle JDeveloper have extensive features for debugging PL/SQL, Java, and multi-language programs. You can get Oracle JDeveloper as part of various Oracle product suites. Often, a more recent release is available as a download at
You can also debug stored subprograms and triggers using the Oracle package
PUT_LINE statements in your code to output the value of variables and expressions to your terminal.
Starting with Oracle Database 10g, a new privilege model applies to debugging PL/SQL and Java code running within the database. This model applies whether you are using Oracle JDeveloper, Oracle Developer, or any of the various third-party PL/SQL or Java development environments, and it affects both the
For a session to connect to a debugger, the effective user at the time of the connect operation must have the
SESSION system privilege. This effective user might be the owner of a DR routine involved in making the connect call.
When a debugger becomes connected to a session, the session login user and the currently enabled session-level roles are fixed as the privilege environment for that debugging connection. Any
EXECUTE privileges needed for debugging must be granted to that combination of user and roles.
To be able to display and change Java public variables or variables declared in a PL/SQL package specification, the debugging connection must be granted either
DEBUG privilege on the relevant code.
To be able to either display and change private variables or breakpoint and execute code lines step by step, the debugging connection must be granted
DEBUG privilege on the relevant code
DEBUGprivilege allows a debugging session to do anything that the subprogram being debugged could have done if that action had been included in its code.
In addition to these privilege requirements, the ability to stop on individual code lines and debugger access to variables are allowed only in code compiled with debug information generated. Use the PL/SQL compilation parameter
PLSQL_DEBUG and the
DEBUG keyword on statements such as
PACKAGE to control whether the PL/SQL compiler includes debug information in its results. If not, variables are not accessible, and neither stepping nor breakpoints stop on code lines. The PL/SQL compiler never generates debug information for code hidden with the PL/SQL
See Also:Oracle Database PL/SQL Language Reference, for information about the
PROCEDURE system privilege is equivalent to the
DEBUG privilege granted on all objects in the database. Objects owned by
SYS are included if the value of the
O7_DICTIONARY_ACCESSIBILITY parameter is
A debug role mechanism is available to carry privileges needed for debugging that are not normally enabled in the session. See the documentation on the
DBMS_DEBUG_JDWP packages for details on how to specify a debug role and any necessary related password.
JAVADEBUGPRIV role carries the
PROCEDURE privileges. Grant it only with the care those privileges warrant.
PROCEDUREprivilege, or granting
DEBUGprivilege on any object owned by
SYS, means granting complete rights to the database.
DBMS_DEBUG_JDWP package, provided starting with Oracle9i Release 2, provides a framework for multi-language debugging that is expected to supersede the
DBMS_DEBUG package over time. It is especially useful for programs that combine PL/SQL and Java.
DBMS_DEBUG package, provided starting with Oracle8i, implements server-side debuggers and provides a way to debug server-side PL/SQL units. Several of the debuggers available, such as Oracle Procedure Builder and various third-party vendor solutions, use this API.
Oracle Procedure Builder Developer's Guide
Oracle Database PL/SQL Packages and Types Reference for more information about the
DBMS_DEBUG package and associated privileges
Oracle Database PL/SQL Packages and Types Reference for more information about the
DBMS_OUTPUT package and associated privileges
The Oracle JDeveloper documentation for information about using package
Oracle Database SQL Language Reference for more details on privileges
The PL/SQL page at
http://www.oracle.com/technology/ for information about writing low-level debug code
Interactively, using an Oracle Database tool
From the body of another subprogram
From within an application (such as a SQL*Forms or a precompiler)
From the body of a trigger
Stored PL/SQL functions (but not procedures) can also be invoked from from within SQL statements. For details, see Invoking Stored PL/SQL Functions from SQL Statements.
Standalone subprograms that you own
Subprograms in packages that you own
Public standalone subprograms
Subprograms in public packages
To invoke a standalone or packaged subprogram owned by another user:
You must have the
EXECUTE privilege for the standalone subprogram or for the package containing the subprogram, or you must have the
PROCEDURE system privilege.
If you are executing a remote subprogram, then you must be granted the
EXECUTE privilege or
PROCEDURE system privilege directly, not through a role.
You must include the name of the owner in the invocation. For example:
EXECUTE jdoe.Fire_emp (1043); EXECUTE jdoe.Hire_fire.Fire_emp (1043);
If the subprogram is an invoker's-rights (IR) subprogram, then it runs with your privileges. You must have all the necessary object privileges for any referenced objects; that is, all objects accessed by the subprogram through external references that are resolved in your schema. You can hold these privileges either directly or through a role. Roles are enabled unless an IR subprogram is invoked directly or indirectly by a DR subprogram.
You can invoke a subprogram interactively from an Oracle Database tool, such as SQL*Plus. Example 7-13 uses SQL*Plus to create a procedure and then invokes it in two different ways.
SQL> CREATE OR REPLACE PROCEDURE salary_raise ( 2 employee EMPLOYEES.EMPLOYEE_ID%TYPE, 3 raise EMPLOYEES.SALARY%TYPE 4 ) IS 5 BEGIN 6 UPDATE EMPLOYEES 7 SET SALARY = SALARY + raise 8 WHERE EMPLOYEE_ID = employee; 9 END; 10 / Procedure created. SQL> SQL> -- Invoke procedure from within PL/SQL block: SQL> SQL> BEGIN 2 salary_raise(205, 200); 3 END; 4 / PL/SQL procedure successfully completed. SQL> -- Invoke procedure with EXECUTE statement: SQL> SQL> EXECUTE salary_raise(205, 200); PL/SQL procedure successfully completed. SQL>
Some interactive tools allow you to create session variables, which you can use for the duration of the session. Using SQL*Plus, Example 7-14 creates, uses, and prints a session variable.
SQL> -- Create function for later use: SQL> SQL> CREATE OR REPLACE FUNCTION get_job_id ( 2 emp_id EMPLOYEES.EMPLOYEE_ID%TYPE 3 ) RETURN EMPLOYEES.JOB_ID%TYPE 4 IS 5 job_id EMPLOYEES.JOB_ID%TYPE; 6 BEGIN 7 SELECT JOB_ID INTO job_id 8 FROM EMPLOYEES 9 WHERE EMPLOYEE_ID = emp_id; 10 RETURN job_id; 11 END; 12 / Function created. SQL> SQL> -- Create session variable: SQL> SQL> VARIABLE job VARCHAR2(10); SQL> SQL> -- Execute function and store returned value in session variable: SQL> SQL> EXECUTE :job := get_job_id(204); PL/SQL procedure successfully completed. SQL> SQL> PRINT job; JOB -------------------------------- PR_REP SQL>
SQL*Plus User's Guide and Reference for information about the
Your tools documentation for information about performing similar operations using your development tool
A subprogram or a trigger can invoke another stored subprogram. In Example 7-15, the procedure
print_mgr_name invokes the procedure
Recursive subprogram invocations are allowed (that is, a subprogram can invoke itself).
SQL> -- Create procedure that takes employee's ID and prints employee's name: SQL> SQL> CREATE OR REPLACE PROCEDURE print_emp_name ( 2 emp_id EMPLOYEES.EMPLOYEE_ID%TYPE 3 ) 4 IS 5 fname EMPLOYEES.FIRST_NAME%TYPE; 6 lname EMPLOYEES.LAST_NAME%TYPE; 7 BEGIN 8 SELECT FIRST_NAME, LAST_NAME 9 INTO fname, lname 10 FROM EMPLOYEES 11 WHERE EMPLOYEE_ID = emp_id; 12 13 DBMS_OUTPUT.PUT_LINE ( 14 'Employee #' || emp_id || ': ' || fname || ' ' || lname 15 ); 16 END; 17 / Procedure created. SQL> -- Create procedure that takes employee's ID and prints manager's name: SQL> SQL> CREATE OR REPLACE PROCEDURE print_mgr_name ( 2 emp_id EMPLOYEES.EMPLOYEE_ID%TYPE 3 ) 4 IS 5 mgr_id EMPLOYEES.MANAGER_ID%TYPE; 6 BEGIN 7 SELECT MANAGER_ID 8 INTO mgr_id 9 FROM EMPLOYEES 10 WHERE EMPLOYEE_ID = emp_id; 11 12 DBMS_OUTPUT.PUT_LINE ( 13 'Manager of employee #' || emp_id || ' is: ' 14 ); 15 16 print_emp_name(mgr_id); 17 END; 18 / Procedure created. SQL> BEGIN 2 print_emp_name(200); 3 print_mgr_name(200); 4 END; 5 / Employee #200: Jennifer Whalen Manager of employee #200 is: Employee #101: Neena Kochhar PL/SQL procedure successfully completed. SQL>
Assume that the procedure
Fire_emp1 was created as follows:
CREATE OR REPLACE PROCEDURE fire_emp1 (Emp_id NUMBER) AS BEGIN DELETE FROM Emp_tab WHERE Empno = Emp_id; END;
To run a subprogram within the code of a precompiler application, you must use the
EXEC call interface. For example, the following statement invokes the
Fire_emp procedure in the code of a precompiler application:
EXEC SQL EXECUTE BEGIN Fire_emp1(:Empnum); END; END-EXEC;
Remote subprograms (standalone and packaged) can be invoked from within a subprogram, OCI application, or precompiler by specifying the remote subprogram name, a database link, and the parameters for the remote subprogram.
For example, the following SQL*Plus statement invokes the procedure
fire_emp1, which is located in the database and referenced by the local database link named
You must specify values for all remote subprogram parameters, even if there are defaults. You cannot access remote package variables and constants.
Remote subprogram invocations use run-time binding. The user account to which you connect depends on the database link. (Stored subprograms use compile-time binding.)
If a local subprogram invokes a remote subprogram, and a timestamp mismatch is found during execution of the local subprogram, then the remote subprogram is not run, and the local subprogram is invalidated.
See Also:Handling Errors in Remote Subprograms for information about exception handling when invoking remote subprograms
CREATE SYNONYM synonym1 for fire_emp1@boston_server; EXECUTE synonym1(1043); /
The synonym enables you to invoke the remote subprogram from an Oracle Database tool application, such as a SQL*Forms application, as well from within a subprogram, OCI application, or precompiler.
Synonyms provide both data independence and location transparency. Synonyms permit applications to function without modification regardless of which user owns the object and regardless of which database holds the object. However, synonyms are not a substitute for privileges on database objects. Appropriate privileges must be granted to a user before the user can use the synonym.
Because subprograms defined within a package are not individual objects (the package is the object), synonyms cannot be created for individual subprograms within a package.
If you do not want to use a synonym, you can create a local subprogram to invoke the remote subprogram. For example:
CREATE OR REPLACE PROCEDURE local_procedure (arg IN NUMBER) AS BEGIN fire_emp1@boston_server(arg); END; / DECLARE arg NUMBER; BEGIN local_procedure(arg); END; /
All invocations to remotely stored subprograms are assumed to perform updates; therefore, this type of referencing always requires two-phase commit of that transaction (even if the remote subprogram is read-only). Furthermore, if a transaction that includes a remote subprogram invocation is rolled back, then the work done by the remote subprogram is also rolled back.
A subprogram invoked remotely can usually execute a
SAVEPOINT statement, the same as a local subprogram. However, there are some differences in action:
If the transaction was originated by a database that is not an Oracle database, as might be the case in XA applications, these operations are not allowed in the remote subprogram.
After doing one of these operations, the remote subprogram cannot start any distributed transactions of its own.
If the remote subprogram does not commit or roll back its work, the commit is done implicitly when the database link is closed. In the meantime, further invocations to the remote subprogram are not allowed because it is still considered to be performing a transaction.
A distributed update modifies data on two or more databases. A distributed update is possible using a subprogram that includes two or more remote updates that access data on different databases. Statements in the construct are sent to the remote databases, and the execution of the construct succeeds or fails as a unit. If part of a distributed update fails and part succeeds, then a rollback (of the entire transaction or to a savepoint) is required to proceed. Consider this when creating subprograms that perform distributed updates.
Caution:Because SQL is a declarative language, rather than an imperative (or procedural) one, you cannot know how many times a function invoked from a SQL statement will execute—even if the function is written in PL/SQL, an imperative language.
If your application requires that a function be executed a certain number of times, do not invoke that function from a SQL statement. Use a cursor instead.
For example, if your application requires that a function be called once for each selected row, then open a cursor, select rows from the cursor, and call the function for each row. This guarantees that the number of calls to the function is the same as the number of rows fetched from the cursor.
The following SQL statements can invoke stored PL/SQL functions:
CALL can also invoke a stored PL/SQL procedure.)
To invoke a PL/SQL subprogram from SQL, you must either own or have
EXECUTE privileges on the subprogram. To select from a view defined with a PL/SQL function, you must have
SELECT privileges on the view. No separate
EXECUTE privileges are necessary to select from the view.
For general information about invoking subprograms, including passing parameters, see Oracle Database PL/SQL Language Reference.
Invoking PL/SQL subprograms in SQL statements enables you to do the following:
Increase user productivity by extending SQL.
Expressiveness of the SQL statement increases where activities are too complex, too awkward, or unavailable with SQL.
Increase query efficiency.
Functions used in the
WHERE clause of a query can filter data using criteria that must otherwise be evaluated by the application.
Manipulate character strings to represent special data types (for example, latitude, longitude, or temperature).
Provide parallel query execution.
If the query is parallelized, then SQL statements in your PL/SQL subprogram might also be run in parallel (using the parallel query option).
A PL/SQL function can appear in a SQL statement wherever a built-in SQL function or an expression can appear in a SQL statement. For example, a PL/SQL function can appear in the following:
Select list of the
Condition of the
VALUES clause of the
SET clause of the
A PL/SQL table function (which returns a collection of rows) can appear in a
SELECT statement in place of the following:
Column name in the
Table name in the
A PL/SQL function cannot appear in the following contexts, which require unchanging definitions:
CHECK constraint clause of a
Default value specification for a column
To be invoked from a SQL expression, a PL/SQL function must satisfy the following requirements:
It must be a row function, not a column (group) function; that is, its argument cannot be an entire column.
Its formal parameters must be
IN parameters, not
Its formal parameters and its return value (if any) must have Oracle built-in data types (such as
NUMBER), not PL/SQL data types (such as
There is an exception to this rule: A formal parameter can have a PL/SQL data type if the corresponding actual parameter is implicitly converted to the data type of the formal parameter (as in Example 7-17).
The function in Example 7-16 satisfies the preceding requirements.
SQL> DROP TABLE payroll; DROP TABLE payroll * ERROR at line 1: ORA-00942: table or view does not exist SQL> CREATE TABLE payroll ( 2 srate NUMBER, 3 orate NUMBER, 4 acctno NUMBER 5 ); Table created. SQL> CREATE OR REPLACE FUNCTION gross_pay ( 2 emp_id IN NUMBER, 3 st_hrs IN NUMBER DEFAULT 40, 4 ot_hrs IN NUMBER DEFAULT 0 5 ) RETURN NUMBER 6 IS 7 st_rate NUMBER; 8 ot_rate NUMBER; 9 BEGIN 10 SELECT srate, orate 11 INTO st_rate, ot_rate 12 FROM payroll 13 WHERE acctno = emp_id; 14 15 RETURN st_hrs * st_rate + ot_hrs * ot_rate; 16 END gross_pay; 17 / Function created. SQL>
In the SQL*Plus script in Example 7-17, the SQL statement
CALL invokes the PL/SQL function
f1, whose formal parameter and return value have PL/SQL data type
CALL statement succeeds because the actual parameter, 2, is implicitly converted to the data type
PLS_INTEGER. If the actual parameter had a value outside the range of
CALL statement would fail.
SQL> CREATE OR REPLACE FUNCTION f1 ( 2 b IN PLS_INTEGER 3 ) RETURN PLS_INTEGER 4 IS 5 BEGIN 6 RETURN 7 CASE 8 WHEN b > 0 THEN 1 9 WHEN b <= 0 THEN -1 10 ELSE NULL 11 END; 12 END f1; 13 / Function created. SQL> VARIABLE x NUMBER; SQL> CALL f1(b=>2) INTO :x; Call completed. SQL> / Call completed. SQL> PRINT x; X ---------- 1 SQL>
The purity of a stored subprogram refers to the side effects of that subprogram on database tables or package variables. Side effects can prevent the parallelization of a query, yield order-dependent (and therefore, indeterminate) results, or require that package state be maintained across user sessions. Various side effects are not allowed when a function is invoked from a SQL query or DML statement.
In releases prior to Oracle8i, Oracle Database leveraged the PL/SQL compiler to enforce restrictions during the compilation of a stored subprogram or a SQL statement. Starting with Oracle8i, the compile-time restrictions were relaxed, and a smaller set of restrictions are enforced during execution.
This change provides uniform support for stored subprograms written in PL/SQL, Java, and C, and it allows programmers the most flexibility possible.
When a SQL statement is run, checks are made to see if it is logically embedded within the execution of an already running SQL statement. This occurs if the statement is run from a trigger or from a subprogram that was in turn invoked from the already running SQL statement. In these cases, further checks occur to determine if the new SQL statement is safe in the specific context.
The following restrictions are enforced on subprograms:
A subprogram invoked from a query or DML statement might not end the current transaction, create or rollback to a savepoint, or
ALTER the system or session.
A subprogram invoked from a query (
SELECT) statement or from a parallelized DML statement might not execute a DML statement or otherwise modify the database.
A subprogram invoked from a DML statement might not read or modify the particular table being modified by that DML statement.
These restrictions apply regardless of what mechanism is used to run the SQL statement inside the subprogram or trigger. For example:
They apply to a SQL statement invoked from PL/SQL, whether embedded directly in a subprogram or trigger body, run using the native dynamic mechanism (
IMMEDIATE), or run using the
They apply to statements embedded in Java with SQLJ syntax or run using JDBC.
They apply to statements run with OCI using the callback context from within an "external" C function.
You can avoid these restrictions if the execution of the new SQL statement is not logically embedded in the context of the already running statement. PL/SQL's autonomous transactions provide one escape (see Autonomous Transactions ). Another escape is available using Oracle Call Interface (OCI) from an external C function, if you create a new connection rather than using the handle available from the
You can use the keywords
PARALLEL_ENABLE in the syntax for declaring a function. These are optimization hints that inform the query optimizer and other software components about the following:
Functions that need not be invoked redundantly
Functions permitted within a parallelized query or parallelized DML statement
Only functions that are
DETERMINISTIC are allowed in function-based indexes and in certain snapshots and materialized views.
A deterministic function depends solely on the values passed into it as arguments and does not reference or modify the contents of package variables or the database or have other side-effects. Such a function produces the same result value for any combination of argument values passed into it.
You place the
DETERMINISTIC keyword after the return value type in a declaration of the function. For example:
SQL> CREATE OR REPLACE FUNCTION f1 ( 2 p1 NUMBER 3 ) RETURN NUMBER DETERMINISTIC 4 IS 5 BEGIN 6 RETURN p1 * 2; 7 END; 8 / Function created. SQL>
You might place this keyword in the following places:
On a function defined in a
In a function declaration in a
On a method declaration in a
Do not repeat the keyword on the function or method body in a
Certain performance optimizations occur on invocations of functions that are marked
DETERMINISTIC without any other action being required. The following features require that any function used with them be declared
Any user-defined function used in a function-based index.
Any function used in a materialized view, if that view is to qualify for Fast Refresh or is marked
The preceding functions features attempt to use previously calculated results rather than invoking the function when it is possible to do so.
It is good programming practice to make functions that fall in the following categories
Functions used in a
ORDER methods of a SQL type
Functions that help determine whether or where a row appears in a result set
Keep the following points in mind when you create
The database cannot recognize if the action of the function is indeed deterministic. If the
DETERMINISTIC keyword is applied to a function whose action is not truly deterministic, then the result of queries involving that function is unpredictable.
If you change the semantics of a
DETERMINISTIC function and recompile it, then existing function-based indexes and materialized views report results for the prior version of the function. Thus, if you change the semantics of a function, you must manually rebuild any dependent function-based indexes and materialized views.
See Also:Oracle Database PL/SQL Language Reference for
Oracle Database's parallel execution feature divides the work of executing a SQL statement across multiple processes. Functions invoked from a SQL statement that is run in parallel might have a separate copy run in each of these processes, with each copy invoked for only the subset of rows that are handled by that process.
Each process has its own copy of package variables. When parallel execution begins, these are initialized based on the information in the package specification and body as if a new user is logging into the system; the values in package variables are not copied from the original login session. And changes made to package variables are not automatically propagated between the various sessions or back to the original session. Java
STATIC class attributes are similarly initialized and modified independently in each process. Because a function can use package (or Java
STATIC) variables to accumulate some value across the various rows it encounters, Oracle Database cannot assume that it is safe to parallelize the execution of all user-defined functions.
SELECT statements in Oracle Database versions prior to 8.1.5, the parallel query optimization allowed functions noted as both
WNPS in a
RESTRICT_REFERENCES declaration to run in parallel. Functions defined with
FUNCTION statements had their code implicitly examined to determine if they were pure enough; parallelized execution might occur even though a pragma cannot be specified on these functions.
For DML statements in Oracle Database versions prior to 8.1.5, the parallelization optimization looked to see if a function was noted as having all four of
WNPS specified in a
RESTRICT_REFERENCES declaration; those functions that were marked as neither reading nor writing to either the database or package variables could run in parallel. Again, those functions defined with a
FUNCTION statement had their code implicitly examined to determine if they were actually pure enough; parallelized execution might occur even though a pragma cannot be specified on these functions.
Oracle Database versions 8.1.5 and later continue to parallelize those functions that earlier versions recognize as parallelizable. The
PARALLEL_ENABLE keyword is the preferred way to mark your code as safe for parallel execution. This keyword is syntactically similar to
DETERMINISTIC as described in Declaring a Function; it is placed after the return value type in a declaration of the function, as in:
SQL> CREATE OR REPLACE FUNCTION f1 ( 2 p1 NUMBER 3 ) RETURN NUMBER PARALLEL_ENABLE 4 IS 5 BEGIN 6 RETURN p1 * 2; 7 END; 8 / Function created. SQL>
A PL/SQL function defined with
FUNCTION might still be run in parallel without any explicit declaration that it is safe to do so, if the system can determine that it neither reads nor writes package variables nor invokes any function that might do so. A Java method or C function is never seen by the system as safe to run in parallel, unless the programmer explicitly indicates
PARALLEL_ENABLE on the call specification, or provides a
RESTRICT_REFERENCES indicating that the function is sufficiently pure.
An additional run-time restriction is imposed on functions run in parallel as part of a parallelized DML statement. Such a function is not permitted to in turn execute a DML statement; it is subject to the same restrictions that are enforced on functions that are run inside a query (
In Oracle Database versions prior to 8.1.5 (Oracle8i), programmers used
RESTRICT_REFERENCES to assert the purity level of a subprogram. In subsequent versions, use the hints
DETERMINISTIC, instead, to communicate subprogram purity to Oracle Database.
You can remove
RESTRICT_REFERENCES from your code. However, this pragma remains available for backward compatibility in situations where one of the following is true:
It is impossible or impractical to edit existing code to remove
RESTRICT_REFERENCES completely. If you do not remove it from a subprogram S1 that depends on another subprogram S2, then
RESTRICT_REFERENCES might also be needed in S2, so that S1 will compile.
RESTRICT_REFERENCES in existing code with hints
DETERMINISTIC would negatively affect the action of new, dependent code. Use
RESTRICT_REFERENCES to preserve the action of the existing code.
An existing PL/SQL application can thus continue using the pragma even on new functionality, to ease integration with the existing code. Do not use the pragma in a new application.
If you use
RESTRICT_REFERENCES, place it in a package specification, not in a package body. It must follow the declaration of a subprogram, but it need not follow immediately. Only one pragma can reference a given subprogram declaration.
To code the
RESTRICT_REFERENCES, use the following syntax:
PRAGMA RESTRICT_REFERENCES ( Function_name, WNDS [, WNPS] [, RNDS] [, RNPS] [, TRUST] );
||The subprogram writes no database state (does not modify database tables).|
||The subprogram reads no database state (does not query database tables).|
||The subprogram writes no package state (does not change the values of packaged variables).|
||The subprogram reads no package state (does not reference the values of packaged variables).|
||The other restrictions listed in the pragma are not enforced; they are simply assumed to be true. This allows easy invocation from functions that have
You can pass the arguments in any order. If any SQL statement inside the subprogram body violates a rule, then you get an error when the statement is parsed.
In Example 7-18, the function
compound neither reads nor writes database or package state; therefore, you can assert the maximum purity level. Always assert the highest purity level that a subprogram allows, so that the PL/SQL compiler never rejects the subprogram unnecessarily.
SQL> DROP TABLE accounts; DROP TABLE accounts * ERROR at line 1: ORA-00942: table or view does not exist SQL> CREATE TABLE accounts ( 2 acctno INTEGER, 3 balance NUMBER 4 ); Table created. SQL> SQL> INSERT INTO accounts 2 VALUES (12345, 1000.00); 1 row created. SQL> SQL> CREATE OR REPLACE PACKAGE finance AS 2 FUNCTION compound ( 3 years IN NUMBER, 4 amount IN NUMBER, 5 rate IN NUMBER 6 ) RETURN NUMBER; 7 PRAGMA RESTRICT_REFERENCES (compound, WNDS, WNPS, RNDS, RNPS); 8 END finance; 9 / Package created. SQL> CREATE PACKAGE BODY finance AS 2 FUNCTION compound ( 3 years IN NUMBER, 4 amount IN NUMBER, 5 rate IN NUMBER 6 ) RETURN NUMBER 7 IS 8 BEGIN 9 RETURN amount * POWER((rate / 100) + 1, years); 10 END compound; 11 -- No pragma in package body 12 END finance; 13 / Package body created. SQL> DECLARE 2 interest NUMBER; 3 BEGIN 4 SELECT finance.compound(5, 1000, 6) 5 INTO interest 6 FROM accounts 7 WHERE acctno = 12345; 8 END; 9 / PL/SQL procedure successfully completed. SQL>
When you invoke a routine that is in a section of code that does not use pragmas (such as a Java method), from a section of PL/SQL code that does use pragmas, specify
TRUST for either the invoked routine or the invoking routine.
In both Example 7-19 and Example 7-20, the PL/SQL function
f invokes the Java procedure
java_sleep. In Example 7-19, this is possible because
java_sleep is declared to be
TRUST. In Example 7-20, it is possible because
f is declared to be
TRUST, which allows it to invoke any routine.
SQL> CREATE OR REPLACE PACKAGE p IS 2 PROCEDURE java_sleep (milli_seconds IN NUMBER) 3 AS LANGUAGE JAVA NAME 'java.lang.Thread.sleep(long)'; 4 PRAGMA RESTRICT_REFERENCES(java_sleep,WNDS,TRUST); 5 6 FUNCTION f (n NUMBER) RETURN NUMBER; 7 END p; 8 / Package created. SQL> CREATE OR REPLACE PACKAGE BODY p IS 2 FUNCTION f ( 3 n NUMBER 4 ) RETURN NUMBER 5 IS 6 BEGIN 7 java_sleep(n); 8 END f; 9 END p; 10 / Package body created. SQL>
SQL> CREATE OR REPLACE PACKAGE p IS 2 PROCEDURE java_sleep (milli_seconds IN NUMBER) 3 AS LANGUAGE JAVA NAME 'java.lang.Thread.sleep(long)'; 4 5 FUNCTION f (n NUMBER) RETURN NUMBER; 6 PRAGMA RESTRICT_REFERENCES(f,WNDS,TRUST); 7 END p; 8 / Package created. SQL> CREATE OR REPLACE PACKAGE BODY p IS 2 FUNCTION f ( 3 n NUMBER 4 ) RETURN NUMBER 5 IS 6 BEGIN 7 java_sleep(n); 8 END f; 9 END p; 10 / Package body created. SQL>
DELETE statements do not violate
RNDS if these statements do not explicitly read any database states, such as columns of a table. However, dynamic
DELETE statements always violate
RNDS, regardless of whether or not the statements explicitly read database states.
RNDS if it is executed dynamically, but it does not violate
RNDS if it is executed statically.
INSERT INTO my_table values(3, 'BOB');
UPDATE always violates
RNDS statically and dynamically, because it explicitly reads the column
UPDATE my_table SET id=777 WHERE name='BOB';
PL/SQL lets you overload packaged (but not standalone) functions; that is, you can use the same name for different functions if their formal parameters differ in number, order, or data type family. However,
RESTRICT_REFERENCES applies to only one function declaration (the most recently declared one).
In Example 7-21, the pragma applies to the second declaration of
PL/SQL packages usually consume user global area (UGA) memory corresponding to the number of package variables and cursors in the package. This limits scalability, because the memory increases linearly with the number of users. The solution is to allow some packages to be marked as
SERIALLY_REUSABLE (using pragma syntax).
For serially reusable packages, the package global memory is not kept in the UGA for each user; rather, it is kept in a small pool and reused for different users. Therefore, the global memory for such a package is only used within a unit of work. At the end of that unit of work, the memory can therefore be released to the pool to be reused by another user (after running the initialization code for all the global variables).
The unit of work for serially reusable packages is implicitly a call to the server; for example, an OCI call to the server, or a PL/SQL RPC call from a client to a server, or an RPC call from a server to another server.
The state of a serially reusable package persists only for the lifetime of a call to the server. On a subsequent call to the server, if a reference is made to the serially reusable package, then Oracle Database creates a new instantiation of the serially reusable package and initializes all the global variables to
NULL or to the default values provided. Any changes made to the serially reusable package state in the previous calls to the server are not visible.
Note:Creating a new instantiation of a serially reusable package on a call to the server does not necessarily imply that Oracle Database allocates memory or configures the instantiation object. Oracle Database looks for an available instantiation work area (which is allocated and configured) for this package in a least-recently used (LRU) pool in the SGA.
At the end of the call to the server, this work area is returned back to the LRU pool. The reason for keeping the pool in the SGA is that the work area can be reused across users who have requests for the same package.
Because the state of a nonreusable package persists for the lifetime of the session, this locks up UGA memory for the whole session. In some applications, such as Oracle Office, a log-on session typically exists for days. Applications often need certain packages only for short periods of the session. Ideally, such applications could de-instantiate the package state in after they finish using the package (the middle of the session).
SERIALLY_REUSABLE packages enable you to design applications that manage memory better for scalability. Package states that matter only for the duration of a call to the server can be captured in
A package specification can be marked serially reusable, whether or not it has a corresponding package body. If the package has a body, then the body must have the serially reusable pragma, if its corresponding specification has the pragma; it cannot have the serially reusable pragma unless the specification also has the pragma.
A package that is marked
SERIALLY_REUSABLE has the following properties:
Its package variables are meant for use only within the work boundaries, which correspond to calls to the server (either OCI call boundaries or PL/SQL RPC calls to the server).
Note:If the application programmer makes a mistake and depends on a package variable that is set in a previous unit of work, then the application program can fail. PL/SQL cannot check for such cases.
A pool of package instantiations is kept, and whenever a "unit of work" needs this package, one of the instantiations is "reused", as follows:
The package variables are reinitialized (for example, if the package variables have default values, then those values are reinitialized).
The initialization code in the package body is run again.
At the "end work" boundary, cleanup is done.
If any cursors were left open, then they are silently closed.
Some nonreusable secondary memory is freed (such as memory for collection variables or long
This package instantiation is returned back to the pool of reusable instantiations kept for this package.
Serially reusable packages cannot be accessed from database triggers or other PL/SQL subprograms that are invoked from SQL statements. If you try, then Oracle Database generates an error.
The two packages specified in Example 7-22 are the same, except that one is serially reusable and the other is not. Neither package has a body.
SQL> CREATE OR REPLACE PACKAGE pkg IS 2 n NUMBER := 5; 3 END pkg; 4 / Package created. SQL> CREATE OR REPLACE PACKAGE sr_pkg IS 2 PRAGMA SERIALLY_REUSABLE; 3 n NUMBER := 5; 4 END sr_pkg; 5 / Package created. SQL> BEGIN 2 pkg.n := 10; 3 sr_pkg.n := 10; 4 END; 5 / PL/SQL procedure successfully completed. SQL> BEGIN 2 DBMS_OUTPUT.PUT_LINE('pkg.n: ' || pkg.n); 3 DBMS_OUTPUT.PUT_LINE('sr_pkg.n: ' || sr_pkg.n); 4 END; 5 / pkg.n: 10 sr_pkg.n: 5 PL/SQL procedure successfully completed. SQL>
The package in Example 7-23 has a body. Because the package specification is serially reusable, the package body must also be serially reusable.
SQL> CREATE OR REPLACE PACKAGE sr_pkg IS 2 PRAGMA SERIALLY_REUSABLE; 3 TYPE str_table_type IS TABLE OF VARCHAR2(200) INDEX BY PLS_INTEGER; 4 num NUMBER := 10; 5 str VARCHAR2(200) := 'default-init-str'; 6 str_tab STR_TABLE_TYPE; 7 8 PROCEDURE print_pkg; 9 10 PROCEDURE init_and_print_pkg ( 11 n NUMBER, 12 v VARCHAR2 13 ); 14 END sr_pkg; 15 / Package created. SQL> CREATE OR REPLACE PACKAGE BODY sr_pkg IS 2 PRAGMA SERIALLY_REUSABLE; 3 4 PROCEDURE print_pkg IS 5 num NUMBER; 6 str VARCHAR2(200); 7 str_tab STR_TABLE_TYPE; 8 BEGIN 9 DBMS_OUTPUT.PUT_LINE('num: ' || sr_pkg.num); 10 DBMS_OUTPUT.PUT_LINE('str: ' || sr_pkg.str); 11 DBMS_OUTPUT.PUT_LINE 12 ('number of table elements: ' || sr_pkg.str_tab.count); 13 FOR i IN 1..sr_pkg.str_tab.count LOOP 14 DBMS_OUTPUT.PUT_LINE(sr_pkg.str_tab(i)); 15 END LOOP; 16 END print_pkg; 17 18 PROCEDURE init_and_print_pkg ( 19 n NUMBER, 20 v VARCHAR2 21 ) IS 22 BEGIN 23 sr_pkg.num := n; 24 sr_pkg.str := v; 25 26 FOR i IN 1..n LOOP 27 sr_pkg.str_tab(i) := v || ' ' || i; 28 END LOOP; 29 30 Print_pkg; 31 END init_and_print_pkg; 32 END sr_pkg; 33 / Package body created. SQL> BEGIN 2 DBMS_OUTPUT.PUT_LINE('Initializing and printing package state ...'); 3 sr_pkg.init_and_print_pkg(4, 'abracadabra'); 4 DBMS_OUTPUT.PUT_LINE('Printing package state in the same CALL ...'); 5 sr_pkg.print_pkg; 6 END; 7 / Initializing and printing package state ... num: 4 str: abracadabra number of table elements: 4 abracadabra 1 abracadabra 2 abracadabra 3 abracadabra 4 Printing package state in the same CALL ... num: 4 str: abracadabra number of table elements: 4 abracadabra 1 abracadabra 2 abracadabra 3 abracadabra 4 PL/SQL procedure successfully completed. SQL>
Open cursors in serially reusable packages are closed automatically at the end of a server call, and must be re-opened in a new server call. A server call can be different from a subprogram call, as Example 7-24 shows.
SQL> DROP TABLE people; DROP TABLE people * ERROR at line 1: ORA-00942: table or view does not exist SQL> CREATE TABLE people (name VARCHAR2(20)); Table created. SQL> INSERT INTO people VALUES ('John Smith'); 1 row created. SQL> INSERT INTO people VALUES ('Mary Jones'); 1 row created. SQL> INSERT INTO people VALUES ('Joe Brown'); 1 row created. SQL> INSERT INTO people VALUES ('Jane White'); 1 row created. SQL> CREATE OR REPLACE PACKAGE sr_pkg IS 2 PRAGMA SERIALLY_REUSABLE; 3 CURSOR c IS SELECT name FROM people; 4 END sr_pkg; 5 / Package created. SQL> CREATE OR REPLACE PROCEDURE fetch_from_cursor IS 2 name VARCHAR2(200); 3 BEGIN 4 IF sr_pkg.c%ISOPEN THEN 5 DBMS_OUTPUT.PUT_LINE('Cursor is already open.'); 6 ELSE 7 DBMS_OUTPUT.PUT_LINE('Cursor is closed; opening now.'); 8 OPEN sr_pkg.c; 9 END IF; 10 11 FETCH sr_pkg.c INTO name; 12 DBMS_OUTPUT.PUT_LINE('Fetched: ' || name); 13 14 FETCH sr_pkg.c INTO name; 15 DBMS_OUTPUT.PUT_LINE('Fetched: ' || name); 16 END fetch_from_cursor; 17 / Procedure created. SQL> -- First call to server: SQL> BEGIN 2 fetch_from_cursor; 3 fetch_from_cursor; 4 END; 5 / Cursor is closed; opening now. Fetched: John Smith Fetched: Mary Jones Cursor is already open. Fetched: Joe Brown Fetched: Jane White PL/SQL procedure successfully completed. SQL> -- New call to server: SQL> BEGIN 2 fetch_from_cursor; 3 fetch_from_cursor; 4 END; 5 / Cursor is closed; opening now. Fetched: John Smith Fetched: Mary Jones Cursor is already open. Fetched: Joe Brown Fetched: Jane White PL/SQL procedure successfully completed. SQL>
In a data warehousing environment, you might use PL/SQL functions to transform large amounts of data. Perhaps the data is passed through a series of transformations, each performed by a different function. PL/SQL table functions let you perform such transformations without significant memory overhead or the need to store the data in tables between each transformation stage. These functions can accept and return multiple rows, can return rows as they are ready rather than all at once, and can be parallelized.
See Also:Oracle Database PL/SQL Language Reference for more information about performing multiple transformations with pipelined table functions
Define a SQL object type that defines these member functions:
Code the member functions. In particular,
ODCIAggregateIterate accumulates the result as it is invoked once for each row that is processed. Store any intermediate results using the attributes of the object type.
Create the aggregate function, and associate it with the new object type.
Call the aggregate function from SQL queries, DML statements, or other places that you might use the built-in aggregates. You can include typical options such as
ALL in the invocation of the aggregate function.
See Also:Oracle Database Data Cartridge Developer's Guide for more information about user-defined aggregate functions