Entry Topic
PL/SQL User's Guide and Reference

PL/SQL™ User's Guide and Reference

PREFACE

PART  I . USER'S GUIDE

CHAPTER 1. OVERVIEW

CHAPTER 2. FUNDAMENTALS

CHAPTER 3. CONTROL STRUCTURES

CHAPTER 4. INTERACTION WITH ORACLE

CHAPTER 5. ERROR HANDLING

CHAPTER 6. SUBPROGRAMS

CHAPTER 7. PACKAGES

CHAPTER 8. EXECUTION ENVIRONMENTS

PART  II . LANGUAGE REFERENCE

CHAPTER 9. LANGUAGE ELEMENTS

CHAPTER 10. ERROR MESSAGES

PART  III . APPENDIXES

APPENDIX A. NEW FEATURES IN VERSION 2

APPENDIX B. SAMPLE PROGRAMS

APPENDIX C. STRING COMPARISON AND ASSIGNMENT SEMANTICS

APPENDIX D. THE WITH INTERFACE CLAUSE

APPENDIX E. RESERVED WORDS


This help file created via:

 Version 1.0n

© 1994 Oracle Corporation Inc.

Authored by KM .


PL/SQL User's Guide and Reference


PL/SQLä User's Guide and Reference
PL/SQL™ User's Guide and Reference

August, 1993

Part No. A12715-1

PL/SQL User's Guide and Reference

Part No. A12715-1

Primary Author: Tom Portfolio

Contributors:  Steve Bobrowski, Peter Clare, Gray Clossman, Pierre Dufour, Steve Faris, Ken Jacobs, Ken Jensen, Bob Kooi, Brian Linden, Jeffrey Olkin, Terry Olkin, Ken Rudin, Phil Shaw, Tim Smith, Kevin Wharton

Copyright  1993 Oracle Corporation, 1993

This software/documentation contains proprietary information of Oracle Corporation; it is provided under a license agreement containing restrictions on use and disclosure and is also protected by copyright law.  Reverse engineering of the software is prohibited.

If this software/documentation is delivered to a U.S. Government Agency of the Department of Defense, then it is delivered with Restricted Rights and the following legend is applicable:

Restricted Rights Legend

Use, duplication, or disclosure by the Government is subject to restrictions

as set forth in subparagraph (c)(1)(ii) of DFARS 252.227-7013, Rights in

Technical Data and Computer Software (October 1988).

Oracle Corporation, 500 Oracle Parkway, Redwood City, CA  94065.

If this software/documentation is delivered to a U.S. Government Agency not within the Department of Defense, then it is delivered with "Restricted Rights," as defined in FAR 52.227-14, Rights in Data - General, including Alternate III (June 1987).

The information in this document is subject to change without notice.   If you find any problems in the documentation, please report them to us in writing.   Oracle Corporation does not warrant that this document is error-free.

Oracle, SQL*DBA, SQL*Forms, SQL*Menu, SQL*Net, SQL*Plus, and SQL*ReportWriter are registered trademarks of Oracle Corporrtion.

Oracle7, PL/SQL, PRO*C, SQL*Module, and  Trusted Oracle7 are registered trademarks of Oracle Corporation.

IBM, DB2, and SQL/DS are registerd trademrks of International Business Machines Corporation.


Preface


PREFACE

PL/SQL is Oracle's procedural language extension to SQL, the relational database language. PL/SQL fully integrates modern software engineering features such as data encapsulation, information hiding, overloading, and exception handling, and so brings state-of-the-art programming to the ORACLE Server and a variety of ORACLE tools.

Designed to meet the practical needs of software developers, this guide explains all the concepts behind PL/SQL and uses simple examples to illustrate every facet of the language. All the information you need to write, run, and debug PL/SQL-based applications is provided.

________________________________________

Audience

This guide was written for programmers developing applications for the ORACLE Server. To use this guide effectively, you need a working knowledge of the following subjects:

•	a procedural programming language such as Ada, C, COBOL, FORTRAN, Pascal, or PL/I

•	the SQL database language

•	ORACLE concepts and terminology

•	ORACLE application development tools

Note:You will not find installation instructions or system-specific information in this guide. For that kind of information about PL/SQL, see the ORACLE installation or user's guide for your system.

________________________________________

What's New in Version 2?

Version 2 of PL/SQL offers an array of improvements and new features. For example, now you can benefit from

•	procedures and functions

•	packages

•	new predefined datatypes

•	PL/SQL tables

•	user-defined records

•	new built-in functions

•	full support for SQL operators

•	remote access

•	national language support (NLS)

•	the new keyword DEFAULT

For more information, see Appendix A.

________________________________________

How this Guide Is Organized

This guide is divided into three parts: a user's guide, a language reference, and appendixes.

User's Guide

This part introduces you to PL/SQL and shows you how to use its many features.

Chapter 1:  Overview

 This chapter surveys the main features of PL/SQL and points out the advantages they offer. It also acquaints you with the basic concepts behind PL/SQL and the general appearance of PL/SQL programs.

Chapter 2:  Fundamentals

 This chapter focuses on the small-scale aspects of PL/SQL. The following subjects are discussed: lexical units, datatypes and type conversion, expressions, assignments, block structure, declarations, scope rules, built-in functions, PL/SQL tables, and user-defined records.

Chapter 3:  Control Structures

 This chapter shows you how to structure the flow of control through a PL/SQL program. It describes conditional, iterative, and sequential control. You learn how to apply simple but powerful control structures such as IF-THEN-ELSE and WHILE-LOOP.

Chapter 4:  Interaction with ORACLE

 This chapter describes the SQL commands, functions, and operators that allow your program to manipulate ORACLE data. You learn how to access remote databases, process transactions, manage cursors, and safeguard the consistency of your database.

Chapter 5:  Error Handling

 This chapter provides an in-depth discussion of error reporting and recovery. You learn how to detect and handle errors using PL/SQL exceptions. The following subjects are discussed: the advantages

 of exceptions, internal versus user-defined exceptions, handling raised exceptions, how exceptions propagate, unhandled exceptions, and useful techniques.

Chapter 6:  Subprograms

 This chapter shows you how to write and use subprograms, which aid application development by isolating operations. The following topics are covered: the advantages of subprograms, procedures, functions, forward declarations, actual versus formal parameters, positional and named notation, parameter modes, parameter default values, aliasing, overloading, recursion, and stored subprograms.

Chapter 7:  Packages

 This chapter shows you how to bundle related PL/SQL types, objects, and subprograms into a package. Once written, your general-purpose package is compiled, then stored in an ORACLE database, where its contents can be shared by many applications.

Chapter 8:  Execution Environments

 This chapter shows you how to use PL/SQL in the SQL*Plus, ORACLE Precompiler, and ORACLE Call Interface (OCI) environments.

Language Reference

This part serves as a reference guide to PL/SQL commands, syntax and semantics, coding conventions, and error messages.

Chapter 9:  Language Elements

 This chapter uses syntax diagrams to show how commands, parameters, and other language elements are sequenced to form PL/SQL statements. In addition, it provides coding conventions, usage notes, and short examples, all of which help you become fluent in PL/SQL quickly.

Chapter 10:  Error Messages

 This chapter lists error messages issued by PL/SQL. For each error, the probable cause and corrective action are given.

Appendixes

This part provides a survey of new features, sample programs, supplementary technical information, and a list of reserved words.

Appendix A:  New Features in Version 2

 This appendix looks at the array of new features offered by PL/SQL Version 2.

Appendix B:  Sample Programs

 This appendix provides several PL/SQL programs to guide you in writing your own. The sample programs illustrate important PL/SQL concepts and features.

Appendix C:  String Comparison and Assignment Semantics

 This appendix explains the semantic differences between the CHAR and VARCHAR2 base types. With ORACLE7 and PL/SQL Version 2, CHAR semantics have changed slightly to comply with the current ANSI/ISO SQL standard.

Appendix D:  The WITH INTERFACE Clause

 This appendix shows you how to use the WITH INTERFACE clause, which defines an interface between PL/SQL and third-generation languages (3GLs) such as C, FORTRAN, and Pascal. The interface lets your 3GL program use SQL*Module to call PL/SQL procedures stored in an ORACLE database.

Appendix E:  Reserved Words

 This appendix lists those words reserved for use by PL/SQL.

________________________________________

Notation Used in This Guide

This guide uses the following notation in code fragments and program examples:

< >	Angle brackets enclose the name of a syntactic element.

--	A double hyphen begins a single-line comment, which extends to the end of a line.

/*  and  */	These symbols delimit a multiline comment, which can extend from one line to another.

.	A dot separates an object name from a component name and so qualifies a reference. For example, dot notation is used to select fields in a record and to specify declarations within a package.

...	An ellipsis shows that statements or clauses irrelevant to the discussion were left out.

UPPERCASE	Uppercase denotes PL/SQL keywords.

lowercase	Lowercase denotes user-defined items such as variables, parameters, and exceptions.

punctuation	Punctuation must be entered as shown.

indention	Indention helps to show structure but is not required.

Syntax Notation

In the text (but not in syntax diagrams), the syntax of PL/SQL is described using a variant of Backus-Naur Form (BNF), which includes the following symbols:

[ ]	Square brackets enclose optional items.

{ }	Braces enclose items only one of which is required.

|	A vertical bar separates alternatives within brackets or braces.

...	An ellipsis shows that the preceding parameter can be 	repeated.

________________________________________

Related Publications

The following publications are recommended for use with this guide:

•	ORACLE7 Server Application Developer's Guide

•	ORACLE7 Server Messages and Codes Manual

•	ORACLE7 Server SQL Language Reference Manual

•	Programmer's Guide to the ORACLE Call Interfaces

•	Programmer's Guide to the ORACLE Precompilers

•	Any of the following:

•	Programmer's Guide to the Pro*Ada Precompiler,

•	Pro*C Supplement to the ORACLE Precompilers Guide

•	Pro*COBOL Supplement to the ORACLE Precompilers Guide

•	Pro*FORTRAN Supplement to the ORACLE Precompilers Guide

•	Pro*Pascal Supplement to the ORACLE Precompilers Guide

•	Pro*PL/I Supplement to the ORACLE Precompilers Guide

•	SQL*Forms Designer's Reference

•	SQL*Module User's Guide and Reference

•	SQL*Plus User's Guide and Reference Manual

•	Trusted ORACLE7 Server Administrator's Guide

Occasionally, this guide refers you to other Oracle manuals for system-specific information. Typically, these manuals are called installation or user's guides, but their exact names vary by operating system and platform. For a complete list of the publications that support ORACLE, refer to the ORACLE Technical Publications Catalog.

________________________________________

Your Comments Are Welcome

The Oracle Corporation technical staff values your comments. As we write and revise, your opinions are the most important input we receive. Please use the Reader's Comment Form at the back of this manual to tell us what you like and dislike about this Oracle publication. If the form has been used or you want to contact us, please call us at (415) 506-7000 or use the following address or FAX number:

PL/SQL Documentation Manager

 	Oracle Corporation

 	500 Oracle Parkway

 	Redwood Shores, CA  94065

 	FAX: (415) 506-7200


PART  I . USER'S GUIDE


CHAPTER 1. OVERVIEW

The limits of my language mean the limits of my world.

Ludwig Wittgenstein

PL/SQL incorporates many of the advances made in programming language design during the 1970s and 1980s. This chapter surveys the main features of PL/SQL and points out the advantages they offer. It also acquaints you with the basic concepts behind PL/SQL and the general appearance of PL/SQL programs. You see how PL/SQL bridges the gap between database technology and procedural programming languages.

________________________________________

Main Features

A good way to get acquainted with PL/SQL is to look at a sample program. The program below processes an order for tennis rackets. First, it declares a variable of type NUMBER to store the quantity of tennis rackets on hand. Then, it retrieves the quantity on hand from a database table named inventory. If the quantity is greater than zero, the program updates the table and inserts a purchase record into another table named purchase_record. Otherwise, the program inserts an out-of-stock record into the purchase_record table.

-- available online in file EXAMP1

DECLARE

   qty_on_hand  NUMBER(5);

BEGIN

   SELECT quantity INTO qty_on_hand FROM inventory

      WHERE product = 'TENNIS RACKET'

      FOR UPDATE OF quantity;

   IF qty_on_hand > 0 THEN  -- check quantity

      UPDATE inventory SET quantity = quantity - 1

         WHERE product = 'TENNIS RACKET';

      INSERT INTO purchase_record

         VALUES ('Tennis racket purchased', SYSDATE);

   ELSE

      INSERT INTO purchase_record

         VALUES ('Out of tennis rackets', SYSDATE);

   END IF;

   COMMIT;

END;

With PL/SQL, you can use SQL statements to manipulate ORACLE data and flow-of-control statements to process the data. Moreover, you can declare constants and variables, define subprograms (procedures and functions), and trap runtime errors. Thus, PL/SQL combines the data manipulating power of SQL with the data processing power of procedural languages.

Block Structure

PL/SQL is a block-structured language. That is, the basic units (procedures, functions, and anonymous blocks) that make up a PL/SQL program are logical blocks, which can contain any number of nested sub-blocks. Typically, each logical block corresponds to a problem or subproblem to be solved. Thus, PL/SQL supports the divide-and-conquer approach to problem solving called stepwise refinement.

A block (or sub-block) lets you group logically related declarations and statements. That way, you can place declarations close to where they are used. The declarations are local to the block and cease to exist when the block completes.

As Figure 1 - 1 shows, a PL/SQL block has three parts: a declarative part, an executable part, and an exception-handling part. (In PL/SQL, a warning or error condition is called an exception.) Only the executable part is required.

The order of the parts is logical. First comes the declarative part, in which objects can be declared. Once declared, objects can be manipulated in the executable part. Exceptions raised during execution can be dealt with in the exception-handling part.

You can nest sub-blocks in the executable and exception-handling parts of a PL/SQL block or subprogram but not in the declarative part. And, you can define local subprograms in the declarative part of any block. However, you can call local subprograms only from the block in which they are defined.

Variables and Constants

PL/SQL allows you to declare variables and constants, then use them in SQL and procedural statements anywhere an expression can be used. However, forward references are not allowed. So, you must declare a variable or constant before referencing it in other statements, including other declarative statements.

 Declaring Variables

Variables can belong to any SQL datatype such as CHAR, DATE, and NUMBER or to any PL/SQL datatype such as BOOLEAN and BINARY_INTEGER. For example, assume you want to declare a variable named part_no to hold 4-digit numbers and a variable named in_stock to hold the Boolean value TRUE or FALSE. You declare these variables as follows:

part_no   NUMBER(4);

in_stock  BOOLEAN;

You can also declare records and PL/SQL tables using the RECORD and TABLE composite datatypes.

 Assigning Values to a Variable

You can assign values to a variable in two ways. The first way uses the assignment operator (:=), a colon followed by an equal sign. You place the variable to the left of the operator and an expression to the right. Some examples follow:

tax := price * tax_rate;

bonus := current_salary * 0.10;

raise := TO_NUMBER(SUBSTR('750 raise', 1, 3));

valid := FALSE;

The second way to assign values to a variable is to SELECT or FETCH database values into it. In the following example, you have ORACLE compute a 10% bonus when you retrieve the salary of an employee:

SELECT sal * 0.10 INTO bonus FROM emp WHERE empno = emp_id;

Then, you can use the variable bonus in another computation or insert its value into a database table.

 Declaring Constants

Declaring a constant is like declaring a variable except that you must add the keyword CONSTANT and immediately assign a value to the constant. Thereafter, no more assignments to the constant are allowed. In the following example, you declare a constant named minimum_balance:

minimum_balance  CONSTANT REAL := 10.00;

Attributes

PL/SQL variables and constants have attributes, which are properties that let you reference the datatype and structure of an object without repeating its definition. Database tables and columns have similar attributes, which you can use to ease maintenance.

 %TYPE

The %TYPE attribute provides the datatype of a variable, constant, or database column. This is particularly useful when declaring variables that refer to database columns. For example, assume there is a column named title in a table named books. To declare a variable named my_title belonging to the same datatype as the column title, you use dot notation and the %TYPE attribute, as follows:

my_title  books.title%TYPE;

Declaring my_title with %TYPE has two advantages. First, you need not know the exact datatype of title. Second, if you change the database definition of title (make it a longer character string for example), the datatype of my_title changes accordingly at run time.

 %ROWTYPE

In PL/SQL, records are used to group data. A record consists of a number of 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 by a cursor (discussed later).

Columns in a row and corresponding fields in a record have the same names and datatypes. In the example below, you declare a record named dept_rec. Its fields have the same names and datatypes as the columns in the dept table.

DECLARE

   dept_rec  dept%ROWTYPE;

   ...

You use dot notation to access field values as the following example shows:

my_deptno := dept_rec.deptno;

If you declare a cursor that retrieves the last name, salary, hire date, and job title of employees, you can use %ROWTYPE to declare a record that stores the same information, as follows:

DECLARE

   CURSOR c1 IS SELECT ename, sal, hiredate, job FROM emp;

   emp_rec  c1%ROWTYPE;

   ...

When you execute the statement

FETCH c1 INTO emp_rec;

the value in the ename column of the emp table is assigned to the ename field of emp_rec, the value in the sal column is assigned to the sal field, and so on. Figure 1 - 2 shows how the result might appear.

Control Structures

Control structures are the most important PL/SQL extension to SQL. Not only does PL/SQL let you manipulate ORACLE data, it lets you process the data using conditional, iterative, and sequential flow-of-control statements such as IF-THEN-ELSE, FOR-LOOP, WHILE-LOOP, EXIT-WHEN, and GOTO. Collectively, these statements can handle any situation.

 Conditional Control

Often, it is necessary to take alternative actions depending on circumstances. The IF-THEN-ELSE statement lets you execute a sequence of statements conditionally. The IF clause checks a condition; the THEN clause defines what to do if the condition is true; the ELSE clause defines what to do if the condition is false or null.

Consider the program below, which processes a bank transaction. Before allowing you to withdraw $500 from account 3, it makes sure the account has sufficient funds to cover the withdrawal. If the funds are available, the program debits the account; otherwise, the program inserts a record into an audit table.

-- available online in file EXAMP2

DECLARE

   acct_balance  NUMBER(11,2);

   acct          CONSTANT NUMBER(4) := 3;

   debit_amt     CONSTANT NUMBER(5,2) := 500.00;

BEGIN

   SELECT bal INTO acct_balance FROM accounts

      WHERE account_id = acct

      FOR UPDATE OF bal;

   IF acct_balance >= debit_amt THEN

      UPDATE accounts SET bal = bal - debit_amt

         WHERE account_id = acct;

   ELSE

      INSERT INTO temp VALUES

         (acct, acct_balance, 'Insufficient funds');

             -- insert account, current balance, and message

   END IF;

   COMMIT;

END;

A sequence of statements that uses query results to select alternative actions is common in database applications. Another common sequence inserts or deletes a row only if an associated entry is found in another table. You can bundle these common sequences into a PL/SQL block using conditional logic. This can improve performance and simplify the integrity checks built into SQL*Forms applications.

 Iterative Control

LOOP statements let you execute a sequence of statements multiple times. You place the keyword LOOP before the first statement in the sequence and the keywords END LOOP after the last statement in the sequence. The following example shows the simplest form of a 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. For example, suppose that you are a manufacturer of custom-made cars and that each car has a serial number. To keep track of which customer buys each car, you might use the following FOR loop:

FOR i IN 1..order_qty LOOP

   UPDATE sales SET custno = customer_id

      WHERE snum = snum_seq.NEXTVAL;

END LOOP;

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 evaluates to TRUE, the sequence of statements is executed, then control resumes at the top of the loop. If the condition evaluates to FALSE or NULL, the loop is bypassed and control passes to the next statement.

In the following example, you find the first employee who has a salary over $4000 and is higher in the chain of command than employee 7902:

-- available online in file EXAMP3

DECLARE

   salary          emp.sal%TYPE;

   mgr_num         emp.mgr%TYPE;

   last_name       emp.ename%TYPE;

   starting_empno  CONSTANT NUMBER(4) := 7902;

BEGIN

   SELECT sal, mgr INTO salary, mgr_num FROM emp

      WHERE empno = starting_empno;

   WHILE salary < 4000 LOOP

      SELECT sal, mgr, ename INTO salary, mgr_num, last_name

      FROM emp

      WHERE empno = mgr_num;

   END LOOP;

   INSERT INTO temp VALUES (NULL, salary, last_name);

   COMMIT;

END;

The EXIT-WHEN statement lets you complete a loop if further processing is undesirable or impossible. When the EXIT statement is encountered, the condition in the WHEN clause is evaluated. If the condition evaluates to TRUE, the loop completes and control passes to the next statement. In the following example, the loop completes when the value of total exceeds 25000:

LOOP

   ...

   total := total + salary;

   EXIT WHEN total > 25000;  -- exit loop if condition is true

END LOOP;

-- control resumes here

 Sequential Control

The GOTO statement lets you branch to a label unconditionally. The label, an undeclared identifier enclosed by double angle brackets, must precede an executable statement or a PL/SQL block. When executed, the GOTO statement transfers control to the labeled statement or block, as the following example shows:

IF rating > 90 THEN

   GOTO calc_raise;  -- branch to label

END IF;

...

<<calc_raise>>

IF job_title = 'SALESMAN' THEN  -- control resumes here

   raise := commission * 0.25;

ELSE

   raise := salary * 0.10;

END IF;

Cursors

ORACLE uses work areas called private SQL areas to execute SQL statements and store processing information. A PL/SQL construct called a cursor lets you name a private SQL area and access its stored information. There are two kinds of cursors: implicit and explicit. PL/SQL implicitly declares a cursor for all SQL data manipulation statements, including queries that return only one row. For queries that return more than one row, you can explicitly declare a cursor to process the rows individually. An example follows:

DECLARE

   CURSOR c1 IS

      SELECT empno, ename, job FROM emp WHERE deptno = 20;

   ...

The set of rows returned by a multirow query is called the active set. Its size is the number of rows that meet your search criteria. As Figure 1 - 3 shows, an explicit cursor "points" to the current row in the active set. This allows your program to process the rows one at a time.

Multirow query processing is somewhat like file processing. For example, a COBOL program opens a file to process records, then closes the file. Likewise, a PL/SQL program opens a cursor to process rows returned by a query, then closes the cursor. Just as a file pointer marks the current position in an open file, a cursor marks the current position in an active set.

As Figure 1 - 4 shows, you use the OPEN, FETCH, and CLOSE statements to control a cursor.

The OPEN statement executes the query associated with the cursor, identifies the active set, and positions the cursor before the first row. The FETCH statement retrieves the current row and advances the cursor to the next row. When the last row has been processed, the CLOSE statement disables the cursor.

 Cursor FOR Loops

In most situations that require an explicit cursor, you can simplify coding by using a cursor FOR loop instead of the OPEN, FETCH, and CLOSE statements. A cursor FOR loop implicitly declares its loop index as a %ROWTYPE record, opens a cursor, repeatedly fetches rows of values from the active set into fields in the record, and closes the cursor when all rows have been processed. In the following example, the cursor FOR loop implicitly declares emp_rec as belonging to type c1%ROWTYPE:

DECLARE

   CURSOR c1 IS

      SELECT ename, sal, hiredate, deptno FROM emp;

   ...

BEGIN

   ...

   FOR emp_rec IN c1 LOOP

       ...

       salary_total :=  salary_total + emp_rec.sal;

   END LOOP;

END;

As the example shows, you use dot notation to reference individual fields.

Error Handling

PL/SQL makes it easy to detect and process predefined and user-defined error conditions called exceptions. When an error occurs, an exception is raised. That is, normal execution stops and control transfers to the exception-handling part of your PL/SQL block or subprogram. To handle raised exceptions, you write separate routines called exception handlers.

Predefined exceptions are raised implicitly by the runtime system. For example, if you try to divide a number by zero, the predefined exception ZERO_DIVIDE is raised automatically. User-defined exceptions must be raised explicitly by RAISE statements.

You can define exceptions of your own in the declarative part of any PL/SQL block or subprogram. In the executable part, you check for the condition that needs special attention. If you find that the condition exists, you execute a RAISE statement. In the example below, you compute the bonus earned by a salesperson. The bonus is based on salary and commission. So, if the commission is null, you raise the exception comm_missing.

DECLARE

   salary        NUMBER(7,2);

   commission    NUMBER(7,2);

   comm_missing  EXCEPTION;  -- declare exception

BEGIN

   SELECT sal, comm INTO salary, commission FROM emp

      WHERE empno = :emp_id;

   IF commission IS NULL THEN

      RAISE comm_missing;  -- raise exception

   ELSE

       :bonus := (salary * 0.05) + (commission * 0.15);

   END IF;

EXCEPTION  -- begin exception handlers

   WHEN comm_missing THEN

       -- process error

END;

The variables emp_id and bonus are declared and assigned values in a host environment. For more information, see the section "ORACLE Precompiler Environment" in Chapter 8.

Modularity

Modularity lets you break an application down into manageable, well-defined logic modules. Through successive refinement, you can reduce a complex problem to a set of simple problems that have easy-to-implement solutions. PL/SQL meets this need with program unit constructs. Besides blocks and subprograms, PL/SQL provides the package construct, which allows you to group related program objects into larger units.

 Subprograms

PL/SQL has two types of subprograms called procedures and functions, which can take parameters and be invoked (called). As the following example shows, a subprogram is like a miniature program, beginning with a header followed by an optional declarative part, an executable part, and an optional exception-handling part:

PROCEDURE award_bonus (emp_id NUMBER) IS

   bonus         REAL;

   comm_missing  EXCEPTION;

BEGIN

   SELECT comm * 0.25 INTO bonus FROM emp WHERE empno = emp_id;

   IF bonus IS NULL THEN

      RAISE comm_missing;

   ELSE

      UPDATE payroll SET pay = pay + bonus WHERE empno = emp_id;

   END IF;

EXCEPTION

   WHEN comm_missing THEN

      ...

END award_bonus;

When called, this procedure accepts an employee number. It uses the number to select the employee's commission from a database table and, at the same time, compute a 25% bonus. Then, it checks the bonus amount. If the bonus is null, an exception is raised; otherwise, the employee's payroll record is updated.

 Packages

PL/SQL lets you bundle logically related types, program objects, and subprograms into a package. Each package is easy to understand and the interfaces between packages are simple, clear, and well-defined. This aids application development.

Packages usually have two parts: a specification and a body. The specification is the interface to your applications; it declares the types, constants, variables, exceptions, cursors, and subprograms available for use. The body defines cursors and subprograms and so implements the specification. In the following example, you "package" two employment procedures:

PACKAGE emp_actions IS  -- package specification

   PROCEDURE hire_employee (empno NUMBER, ename CHAR, ...);

   PROCEDURE fire_employee (emp_id NUMBER);

END emp_actions;

PACKAGE BODY emp_actions IS  -- package body

   PROCEDURE hire_employee (empno NUMBER, ename CHAR, ...) IS

   BEGIN

      INSERT INTO emp VALUES (empno, ename, ...);

   END hire_employee;

   PROCEDURE fire_employee (emp_id NUMBER) IS

   BEGIN

      DELETE FROM emp WHERE empno = emp_id;

   END fire_employee;

END emp_actions;

Only the declarations in the package specification are visible and accessible to applications. Implementation details in the package body are hidden and inaccessible.

If you have the Procedural Database Extension, packages can be compiled and stored in an ORACLE database, where their contents can be shared by many applications. When you call a packaged subprogram for the first time, the whole package is loaded into memory. Therefore, subsequent calls to related subprograms in the package require no disk I/O. Thus, packages can enhance productivity and improve performance.

Information Hiding

With information hiding, you see only the details that are relevant at a given level of algorithm and data structure design. Information hiding keeps high-level design decisions separate from low-level design details, which are more likely to change.

 Algorithms

You implement information hiding for algorithms through top-down design. Once you define the purpose and interface specifications of a low-level procedure, you can ignore the implementation details. They are hidden at higher levels. For example, the implementation of a procedure named raise_salary is hidden. All you need to know is that the procedure will increase a specific employee salary by a given amount. Any changes to the definition of raise_salary are transparent to calling applications.

 Data Structures

You implement information hiding for data structures though data encapsulation. By developing a set of utility subprograms for a data structure, you insulate it from users and other developers. That way, other developers know how to use the subprograms that operate on the data structure but not how the structure is represented.

With PL/SQL packages, you can specify whether types, program objects, and subprograms are public or private. Thus, packages enforce data encapsulation by letting you put type declarations in a black box. A private type definition is hidden and inaccessible. Only the package (not your application) is affected if the definition changes. This simplifies maintenance and enhancement.

________________________________________

Architecture

The PL/SQL runtime system is a technology, not an independent product. Think of this technology as an engine that executes PL/SQL blocks and subprograms. The engine can be installed in an ORACLE Server or in an application development tool such as SQL*Forms, SQL*Menu, or SQL*ReportWriter. So, PL/SQL can reside in two environments:

•	the ORACLE Server

•	ORACLE tools

These two environments are independent. PL/SQL might be available in the Server but unavailable in tools, or the other way around. In either environment, the PL/SQL engine accepts as input any valid PL/SQL block or subprogram. Figure 1 - 5 shows the PL/SQL engine processing a block.

The PL/SQL engine executes procedural statements but sends SQL statements to the SQL Statement Executor in the ORACLE Server.

In ORACLE Server

Application development tools that lack a local PL/SQL engine must rely on ORACLE to process PL/SQL blocks and subprograms. When it contains the PL/SQL engine, an ORACLE Server can process PL/SQL blocks and subprograms as well as single SQL statements. The Server passes the blocks and subprograms to its local PL/SQL engine.

 Anonymous Blocks

Anonymous PL/SQL blocks can be embedded in an ORACLE Precompiler or OCI program. At runtime, the program, lacking a local PL/SQL engine, sends these blocks to the ORACLE Server, where they are compiled and executed. Likewise, interactive tools such as SQL*Plus and SQL*DBA, lacking a local PL/SQL engine, must send anonymous blocks to ORACLE. Figure 1 - 6 shows the processing of an anonymous PL/SQL block sent to ORACLE from a host program or ORACLE tool.

 Stored Subprograms

If you have the Procedural Database Extension, named PL/SQL blocks (subprograms) can be compiled separately and stored permanently in an ORACLE database, ready to be executed.

A subprogram explicitly CREATEd using an ORACLE tool is called a stored subprogram. Once compiled and stored in the data dictionary, it is a database object, which can be referenced by any number of applications connected to that database.

Stored subprograms defined within a package are called packaged subprograms; those defined independently are called stand-alone subprograms. (Subprograms defined within another subprogram or within a PL/SQL block are called local subprograms. They cannot be referenced by other applications and exist only for the convenience of the enclosing block.)

Stored subprograms offer higher productivity, better performance, memory savings, application integrity, and tighter security. For example, by designing applications around a library of stored procedures and functions, you can avoid redundant coding and increase your productivity.

You can call stored subprograms from a database trigger, another stored subprogram, an ORACLE Precompiler application, an OCI application, or interactively from SQL*Plus or SQL*DBA. For example, you might call the stand-alone procedure create_dept from SQL*Plus, as follows:

SQL> EXECUTE create_dept('FINANCE', 'NEW YORK');

Subprograms are stored in parsed, compiled form. So, when called, they are loaded and passed to the PL/SQL engine immediately. Moreover, stored subprograms take advantage of the ORACLE shared memory capability. Only one copy of a subprogram need be loaded into memory for execution by multiple users. Figure 1 - 7 shows a host program or ORACLE tool issuing remote procedure calls (RPCs) to a stored procedure.

 Database Triggers

A database trigger (not a SQL*Forms trigger) is a stored subprogram associated with a table. You can have ORACLE automatically fire the database trigger before or after an INSERT, UPDATE, or DELETE statement affects the table. One of the many uses for database triggers is to audit data modifications. For example, the following database trigger fires whenever salaries in the emp table are updated:

CREATE TRIGGER audit_sal

   AFTER UPDATE OF sal ON emp

   FOR EACH ROW

BEGIN

   INSERT INTO emp_audit VALUES ...

END;

You can use all the SQL data manipulation statements and any procedural statement in the executable part of a database trigger.

In ORACLE Tools

When it contains the PL/SQL engine, an application development tool can process PL/SQL blocks. The tool passes the blocks to its local PL/SQL engine. The engine executes all procedural statements at the application site and sends only SQL statements to ORACLE. Thus, most of the work is done at the application site, not at the Server site.

Furthermore, if the block contains no SQL statements, the engine executes the entire block at the application site. This is useful if your application can benefit from conditional and iterative control. Figure 1 - 8 shows the processing of a PL/SQL block when the PL/SQL engine resides in SQL*Forms. The same concepts apply to the latest versions of SQL*Menu and SQL*ReportWriter.

Frequently, SQL*Forms applications use SQL statements merely to test the value of field entries or to do simple computations. By using PL/SQL instead, you can avoid calls to the Server, which might be remote. Moreover, you can use PL/SQL functions to manipulate field entries.

________________________________________

Advantages of PL/SQL

PL/SQL is a completely portable, high-performance transaction processing language that offers the following advantages:

•	support for SQL

•	higher productivity

•	better performance

•	portability

•	integration with ORACLE

Support for SQL

SQL has become the database language of choice because it is flexible, powerful, and easy to learn. A few English-like commands such as INSERT, UPDATE, and DELETE make it easy to manipulate the data stored in a relational database.

SQL is non-procedural, meaning that you can state what you want done without stating how to do it. ORACLE determines the best way to carry out your request. Moreover, there is no necessary connection between consecutive statements because ORACLE executes SQL statements one at a time.

PL/SQL lets you use all the SQL data manipulation, cursor control, and transaction control commands, as well as all the SQL functions, operators, and pseudocolumns. So, you can manipulate ORACLE data flexibly and safely.

Higher Productivity

PL/SQL adds functionality to non-procedural tools such as SQL*Forms, SQL*Menu, and SQL*ReportWriter. With PL/SQL in these tools, you can use familiar procedural constructs to build applications. For example, you can use an entire PL/SQL block in a SQL*Forms trigger. You need not use multiple trigger steps, macros, or user exits. Thus, PL/SQL increases productivity by putting better tools in your hands.

Moreover, PL/SQL is the same in all environments. As soon as you master PL/SQL with one ORACLE tool, you can transfer your knowledge to other tools and so multiply the productivity gains.

Better Performance

Without PL/SQL, ORACLE must process SQL statements one at a time. Each SQL statement results in another call to ORACLE and higher performance overhead. In a networked environment, the overhead can become significant. Every time a SQL statement is issued, it must be sent over the network, creating more traffic.

However, with PL/SQL, an entire block of statements can be sent to ORACLE at one time. This can drastically reduce communication between your application and ORACLE. As Figure 1 - 9 shows, if your application is database-intensive, you can use control structures to group SQL statements before sending them to ORACLE for execution. Also, you can use subprograms to reduce calls from your application to ORACLE. For example, to execute ten individual SQL statements, ten calls are required, but to execute a subprogram containing ten SQL statements, only one call is required.

PL/SQL can also cooperate with ORACLE application development tools such as SQL*Forms, SQL*Menu, and SQL*ReportWriter. By adding procedural processing power to these tools, PL/SQL boosts performance. Using PL/SQL, a tool can do any computation quickly and efficiently without calling on ORACLE. This saves time and reduces network traffic.

Portability

Applications written in PL/SQL are portable to any operating system and platform on which ORACLE runs. In other words, PL/SQL programs can run anywhere ORACLE can run; you need not tailor them to each new environment. That means you can write portable program libraries, which can be reused in different environments.

Integration with ORACLE

Both PL/SQL and ORACLE are SQL-based. Moreover, PL/SQL supports all the SQL datatypes. Combined with the direct access that SQL provides, these shared datatypes integrate PL/SQL with the ORACLE data dictionary.

The %TYPE and %ROWTYPE attributes further integrate PL/SQL with the data dictionary. For example, you can use the %TYPE attribute to declare variables, basing the declarations on the definitions of database columns. If a definition changes, the variable declaration changes accordingly at run time. This provides data independence, reduces maintenance costs, and allows programs to adapt as the database changes to meet new business needs.


CHAPTER 2. FUNDAMENTALS

There are six essentials in painting. The first is called spirit; the second, rhythm; the third, thought; the fourth, scenery; the fifth, the brush; and the last is the ink.

Ching Hao

The previous chapter provided an overview of PL/SQL. This chapter focuses on the small-scale aspects of the language. Like every other programming language, PL/SQL has a character set, reserved words, punctuation, datatypes, rigid syntax, and fixed rules of usage and statement formation. You use these basic elements of PL/SQL to represent real-world objects and operations.

________________________________________

Character Set

You write a PL/SQL program as lines of text using a specific set of characters. The PL/SQL character set includes

•	the upper and lowercase letters A .. Z, a .. z

•	the numerals 0 .. 9

•	tabs, spaces, and carriage returns

•	the symbols ( ) + - * / < > = ! ~ ; : . ' @ % , " # $ ^ & _ | { } ? [ ]

PL/SQL is not case sensitive, so lowercase letters are equivalent to corresponding uppercase letters except within string and character literals.

________________________________________

Lexical Units

A line of PL/SQL text contains groups of characters known as lexical units, which can be classified as follows:

•	delimiters (simple and compound symbols)

•	identifiers, which include reserved words

•	literals

•	comments

For example, the line

bonus := salary * 0.10;  -- compute bonus

contains the following lexical units:

•	identifiers bonus and salary

•	compound symbol :=

•	simple symbols * and ;

•	numeric literal 0.10

•	comment -- compute bonus

To improve readability, you can separate lexical units by spaces. In fact, you must separate adjacent identifiers by a space or punctuation. For example, the following line is illegal because the reserved words END and IF are joined:

IF x > y THEN high := x; ENDIF;  -- illegal

However, you cannot embed spaces in lexical units except for string literals and comments. For example, the following line is illegal because the compound symbol for assignment (:=) is split:

count : = count + 1;  -- illegal

To show structure, you can divide lines using carriage returns and indent lines using spaces or tabs. Compare the following IF statements:

IF x>y THEN max:=x;ELSE max:=y;END IF;   |     IF x > y THEN

                                         |         max := x;

                                         |     ELSE

                                         |         max := y;

                                         |     END IF;

Delimiters

A delimiter is a simple or compound symbol that has a special meaning to PL/SQL. For example, you use delimiters to represent arithmetic operations such as addition and subtraction.

 Simple Symbols

Simple symbols consist of one character; a list follows:

+	addition operator

- 	subtraction/negation operator

* 	multiplication operator

/ 	division operator

= 	relational operator

< 	relational operator

> 	relational operator

( 	expression or list delimiter

) 	expression or list delimiter

; 	statement terminator

% 	attribute indicator

, 	item separator

. 	component selector

@	remote access indicator

' 	character string delimiter

" 	quoted identifier delimiter

:	host variable indicator

 Compound Symbols

Compound symbols consist of two characters; a list follows:

**	exponentiation operator

<>	relational operator

!=	relational operator

~=	relational operator

^=	relational operator

<=	relational operator

>=	relational operator

:=	assignment operator

=>	association operator

. .	range operator

||	concatenation operator

<<	(beginning) label delimiter

>>	(ending) label delimiter

--	single-line comment indicator

/* 	(beginning) multiline comment delimiter

*/ 	(ending) multiline comment delimiter

Identifiers

You use identifiers to name PL/SQL program objects and units, which include constants, variables, exceptions, cursors, subprograms, and packages. Some examples of identifiers follow:

X

t2

phone#

credit_limit

LastName

oracle$number

An identifier consists of a letter optionally followed by more letters, numerals, dollar signs, underscores, and number signs. Other characters such as hyphens, slashes, and spaces are illegal, as the following examples show:

mine&yours    -- illegal ampersand

debit-amount  -- illegal hyphen

on/off        -- illegal slash

user id       -- illegal space

The next examples show that adjoining and trailing dollar signs, underscores, and number signs are legal:

money$$$tree  -- legal

SN##          -- legal

try_again_    -- legal

You can use upper, lower, or mixed case to write identifiers. PL/SQL is not case sensitive except within string and character literals. So, if the only difference between identifiers is the case of corresponding letters, PL/SQL considers the identifiers to be the same, as the following example shows:

lastname

LastName  -- same as lastname

LASTNAME  -- same as lastname and LastName

The length of an identifier cannot exceed 30 characters. But, every character, including dollar signs, underscores, and number signs, is significant. For example, PL/SQL considers the following identifiers to be different:

lastname

last_name

Identifiers should be descriptive. So, use meaningful names such as credit_limit and cost_per_thousand. Avoid obscure names such as cr_lim and cpm.

 Reserved Words

Some identifiers, called reserved words, have a special syntactic meaning to PL/SQL and so cannot be redefined. For example, the words BEGIN and END, which bracket the executable part of a block or subprogram, are reserved. As the next example shows, if you try to redefine a reserved word, you get a compilation error:

DECLARE

   end  BOOLEAN;  -- illegal; causes compilation error

   ...

However, you can embed reserved words in an identifier, as the following example shows:

DECLARE

   end_of_game  BOOLEAN;  -- legal

   ...

Typically, reserved words are written in uppercase to promote readability. However, like other PL/SQL identifiers, reserved words can be written in lower or mixed case. For a list of reserved words, see Appendix E.

 Predefined Identifiers

Identifiers globally declared in package STANDARD, such as the exception INVALID_NUMBER, can be redeclared. However, redeclaring predefined identifiers is error-prone because your local declaration overrides the global declaration.

 Quoted Identifiers

For flexibility, PL/SQL lets you enclose identifiers within double quotes. Quoted identifiers are seldom needed, but occasionally they can be useful. They can contain any sequence of printable characters including spaces but excluding double quotes. Hence, the following identifiers are legal:

"X+Y"

"last name"

"on/off switch"

"employee(s)"

"*** header info ***"

The maximum length of a quoted identifier is 30 characters not counting the double quotes.

Using PL/SQL reserved words as quoted identifiers is allowed but not recommended. It is poor programming practice to reuse reserved words. However, some PL/SQL reserved words are not reserved by SQL. For example, the PL/SQL reserved word TYPE can be used in a CREATE TABLE statement to name a database column. But, if a SQL statement in your program refers to that column, you get a compilation error, as the following example shows:

SELECT acct, type, bal INTO ...  -- causes compilation error

To prevent the error, enclose the uppercase column name in double quotes as follows:

SELECT acct, "TYPE", bal INTO ...

The column name cannot appear in lower or mixed case (unless it was defined that way in the CREATE TABLE statement). For example, the following statement is invalid:

SELECT acct, "type", bal INTO ...  -- causes compilation error

Alternatively, you can create a view that renames the troublesome column, then use the view instead of the base table in SQL statements.

Literals

A literal is an explicit numeric, character, string, or Boolean value not represented by an identifier. The numeric literal 147 and the Boolean literal FALSE are examples.

 Numeric literals

Two kinds of numeric literals can be used in arithmetic expressions: integers and reals. An integer literal is an optionally signed whole number without a decimal point. Some examples follow:

030   6   -14   0   +32767

A real literal is an optionally signed whole or fractional number with a decimal point. Several examples follow:

6.6667   0.0   -12.0   3.14159   +8300.00   .5   25.

PL/SQL considers numbers such as  12.0 and 25. to be reals even though they have integral values.

Numeric literals cannot contain dollar signs or commas, but can be written using scientific notation. Simply suffix the number with an E (or e) followed by an optionally signed integer. A few examples follow:

2E5   1.0E-7   3.14159e0   -1E38   -9.5e-3

E stands for "times ten to the power of." As the next example shows, the number after E is the power of ten by which the number before E must be multiplied:

5E3 = 5 X 103 = 5 X 1000 = 5000

The number after E also corresponds to the number of places the decimal point shifts. In the last example, the implicit decimal point shifted three places to the right; in the next example, it shifts three places to the left:

5E-3 = 5 X 10-3 = 5 X 0.001 = 0.005

 Character Literals

A character literal is an individual character enclosed by single quotes (apostrophes). Several examples follow:

'Z'   '%'   '7'   ' '   'z'   '('

Character literals include all the printable characters in the PL/SQL character set: letters, numerals, spaces, and special symbols. PL/SQL is case-sensitive within character literals. For example, PL/SQL considers the literals 'Z' and 'z' to be different.

Do not confuse the character literals '0' .. '9' with integer literals. Character literals cannot be used in arithmetic expressions.

 String literals

A character value can be represented by an identifier or explicitly written as a string literal, which is a sequence of zero or more characters enclosed by single quotes. Several examples follow:

'Hello, world!'

'XYZ Corporation'

'10-NOV-91'

'He said "Life is like licking honey from a thorn."'

'$1,000,000'

All string literals except the null string ('') belong to type CHAR.

Given that apostrophes (single quotes) delimit string literals, how do you represent an apostrophe within a string? As the next example shows, you write two single quotes, which is not the same as writing a double quote:

'Don''t leave without saving your work.'

PL/SQL is casesensitive within string literals. For example, PL/SQL considers the following literals to be different:

'baker'

'Baker'

 Boolean literals

Boolean literals are the predefined values TRUE and FALSE and the non-value NULL, which stands for a missing, unknown, or inapplicable value. Keep in mind, Boolean literals are not strings. For example, TRUE is no less a value than the number 25.

Comments

The PL/SQL compiler ignores comments, but you should not. Adding comments to your program promotes readability and aids understanding. Generally, you use comments to describe the purpose and use of each code segment. PL/SQL supports two comment styles: single-line and multiline.

 Single-line

Single-line comments begin with a double hyphen (--) anywhere on a line and extend to the end of the line. A few examples follow:

-- begin processing

SELECT sal INTO salary FROM emp  -- get current salary

   WHERE empno = emp_id;

bonus := salary * 0.15;  -- compute bonus amount

Notice that comments can appear within a statement at the end of a line.

While testing or debugging a program, you might want to disable a line of code. The following example shows how you can "comment-out" the line:

-- DELETE FROM emp WHERE comm IS NULL;

 Multiline

Multiline comments begin with a slash-asterisk (/*), end with an asterisk-slash (*/), and can span multiple lines. An example follows:

/* compute a 15% bonus for

   top-rated employees */

IF rating > 90 THEN

   bonus := salary * 0.15;

END IF;

You can use multiline comment delimiters to comment-out whole sections of code, as the following example shows:

/* OPEN c1;

   LOOP

      FETCH c1 INTO my_empno, my_ename, my_sal;

      EXIT WHEN c1%NOTFOUND;

      ...

   END LOOP;

   CLOSE c1; */

 Restrictions

You cannot nest comments. Also, you cannot use single-line comments in a PL/SQL block that will be processed dynamically by an ORACLE Precompiler program because end-of-line characters are ignored. As a result, single-line comments extend to the end of the block, not just to the end of a line. So, use multiline comments instead.

________________________________________

Datatypes

Every constant and variable has a datatype, which specifies a storage format, constraints, and valid range of values. PL/SQL provides a variety of predefined scalar and composite datatypes. A scalar type has no internal components. A composite type has internal components that can be manipulated individually.

Figure 2 - 1 shows the predefined types available for your use. An additional scalar type, MLSLABEL is available with Trusted ORACLE, a specially secured version of ORACLE. The scalar types fall into four families, which store number, character, date/time, or Boolean data, respectively.

This section discusses the scalar types; the composite types are discussed later in this chapter.

BINARY_INTEGER

You use the BINARY_INTEGER datatype to store signed integers. The magnitude range of a BINARY_INTEGER value is -231- 1 .. 231- 1 (-2147483647 .. 2147483647). PL/SQL represents BINARY_INTEGER values as signed binary numbers, which, unlike NUMBER values, can be used in calculations without conversion. So, using BINARY_INTEGER variables can boost performance.

 BINARY_INTEGER Subtypes

A subtype associates a base type with a constraint and so defines a subset of values. For convenience, PL/SQL predefines the following BINARY_INTEGER subtypes:

•	NATURAL  (0 .. 2147483647)

•	POSITIVE  (1 .. 2147483647)

You can use the NATURAL or POSITIVE subtype when you want to restrict a variable to non-negative integer values.

NUMBER

You use the NUMBER datatype to store fixed or floating point numbers of virtually any size. You can specify precision, which is the total number of digits, and scale, which determines where rounding occurs. The syntax follows:

NUMBER[(precision, scale)]

You cannot use constants or variables to specify precision and scale; you must use integer literals.

The maximum precision of a NUMBER value is 38; the magnitude range is 1.0E-129 .. 9.99E125. If you do not specify the precision, it defaults to the maximum value supported by your system.

Scale can range from -84 to 127. For instance, a scale of 2 rounds to the nearest hundredth (3.456 becomes 3.46). Scale can be negative, which causes rounding to the left of the decimal point. For example, a scale of -3 rounds to the nearest thousand (3456 becomes 3000). A scale of zero rounds to the nearest whole number. If you do not specify the scale, it defaults to zero.

 NUMBER Subtypes

The NUMBER subtypes below have the same range of values as their base type. For example, FLOAT is just another name for NUMBER.

•	DEC

•	DECIMAL

•	DOUBLE PRECISION

•	FLOAT

•	INTEGER

•	INT

•	NUMERIC

•	REAL

•	SMALLINT

You can use these subtypes for compatibility with ANS/ISO, IBM SQL/DS, and IBM DB2 types or when you want an identifier more descriptive than NUMBER.

CHAR

You use the CHAR datatype to store fixed-length character data. How the data is represented internally depends on the database character set, which might be 7-bit ASCII or EBCDIC Code Page 500 for example.

The CHAR datatype takes an optional parameter that lets you specify a maximum length up to 32767 bytes. The syntax follows:

CHAR[(maximum_length)]

You cannot use a constant or variable to specify the maximum length; you must use an integer literal. If you do not specify the maximum length, it defaults to 1.

Remember, you specify the maximum length of a CHAR(n) variable in bytes, not characters. So, if a CHAR(n) variable stores multibyte characters, its maximum length is less than n characters.

Although the maximum length of a CHAR(n) variable is 32767 bytes, the maximum width of a CHAR database column is 255 bytes. Therefore, you cannot insert values longer than 255 bytes into a CHAR column. You can insert any CHAR(n) value into a LONG database column because the maximum width of a LONG column is 2147483647 (231- 1) bytes or two gigabytes. However, you cannot select a value longer than 32767 bytes from a LONG column into a CHAR(n) variable.

 CHAR Subtypes

The CHAR subtypes below have the same range of values as their base type. For example, STRING is just another name for CHAR.

•	CHARACTER

•	STRING

You can use these subtypes for compatibility with ANS/ISO, IBM SQL/DS, and IBM DB2 types or when you want an identifier more descriptive than CHAR.

VARCHAR2

You use the VARCHAR2 datatype to store variable-length character data. How the data is represented internally depends on the database character set.

The VARCHAR2 datatype takes a required parameter that lets you specify a maximum length up to 32767 bytes. The syntax follows:

VARCHAR2(maximum_length)

You cannot use a constant or variable to specify the maximum length; you must use an integer literal.

Remember, you specify the maximum length of a VARCHAR2(n) variable in bytes, not characters. So, if a VARCHAR2(n) variable stores multibyte characters, its maximum length is less than n characters.

Although the maximum length of a VARCHAR2(n) variable is 32767 bytes, the maximum width of a VARCHAR2 database column is 2000 bytes. Therefore, you cannot insert values longer than 2000 bytes into a VARCHAR2 column. You can insert any VARCHAR2(n) value into a LONG database column because the maximum width of a LONG column is 2147483647 bytes. However, you cannot select a value longer than 32767 bytes from a LONG column into a VARCHAR2(n) variable.

Important semantic differences between the CHAR and VARCHAR2 base types are described in Appendix C.

 VARCHAR Subtype

The VARCHAR subtype has the same range of values as its base type. That is, VARCHAR is just another name for VARCHAR2. You can use this subtype for compatibility with ANS/ISO, IBM SQL/DS, and IBM DB2 types. However, the VARCHAR datatype might change to accommodate emerging SQL standards. So, it is a good idea to use VARCHAR2 rather than VARCHAR.

LONG

You use the LONG datatype to store variable-length character strings. The LONG datatype is like the VARCHAR2 datatype, except that the maximum length of a LONG value is 32760 bytes.

You can insert any LONG value into a LONG database column because the maximum width of a LONG column is 2147483647 bytes. However, you cannot select a value longer than 32760 bytes from a LONG column into a LONG variable.

LONG columns can store text, arrays of characters, or even short documents. You can reference LONG columns in UPDATE, INSERT, and (most) SELECT statements, but not in expressions, function calls, or certain SQL clauses such as WHERE, GROUP BY, and CONNECT BY. For more information, refer to the ORACLE7 Server SQL Language Reference Manual.

RAW

You use the RAW datatype to store binary data or byte strings. For example, a RAW variable might store a sequence of graphics characters or a digitized picture. Raw data is like character data, except that PL/SQL does not interpret raw data. Likewise, ORACLE does no character set conversions (from 7-bit ASCII to EBCDIC Code Page 500 for example) when you transmit raw data from one system to another.

The RAW datatype takes a required parameter that lets you specify a maximum length up to 32767 bytes. The syntax follows:

RAW(maximum_length)

You cannot use a constant or variable to specify the maximum length; you must use an integer literal.

Although the maximum length of a RAW variable is 32767 bytes, the maximum width of a RAW database column is 255 bytes. Therefore, you cannot insert values longer than 255 bytes into a RAW column. You can insert any RAW value into a LONG RAW database column because the maximum width of a LONG RAW column is 2147483647 bytes. However, you cannot select a value longer than 32767 bytes from a LONG RAW column into a RAW variable.

LONG RAW

You use the LONG RAW datatype to store binary data or byte strings. LONG RAW data is like LONG data, except that LONG RAW data is not interpreted by PL/SQL. The maximum length of a LONG RAW value is 32760 bytes.

You can insert any LONG RAW value into a LONG RAW database column because the maximum width of a LONG RAW column is 2147483647 bytes. However, you cannot select a value longer than 32760 bytes from a LONG RAW column into a LONG RAW variable.

BOOLEAN

You use the BOOLEAN datatype to store the values TRUE and FALSE and the non-value NULL. Recall that NULL stands for a missing, unknown, or inapplicable value.

The BOOLEAN datatype takes no parameters. Only the values TRUE and FALSE and the non-value NULL can be assigned to a BOOLEAN variable. You cannot insert the values TRUE and FALSE into a database column. Furthermore, you cannot select or fetch column values into a BOOLEAN variable.

DATE

You use the DATE datatype to store fixed-length date values. The DATE datatype takes no parameters. Valid dates for DATE variables include January 1, 4712 BC to December 31, 4712 AD.

When stored in a database column, date values include the time of day in seconds since midnight. The date portion defaults to the first day of the current month; the time portion defaults to midnight.

ROWID

Internally, every table in an ORACLE database has a ROWID pseudocolumn, which stores 6-byte binary values called rowids. Rowids uniquely identify rows and provide the fastest way to access particular rows. You use the ROWID datatype to store rowids in a readable format.

ROWID is a CHAR subtype. So, when you select or fetch a rowid into a ROWID variable, you can use the function ROWIDTOCHAR, which converts the binary value to an 18-byte character string and returns it in the format

BBBBBBBB.RRRR.FFFF

where BBBBBBBB is the block in the database file, RRRR is the row in the block (the first row is 0), and FFFF is the database file. These numbers are hexadecimal. For example, the rowid

0000000E.000A.0007

points to the 11th row in the 15th block in the 7th database file.

Typically, ROWID variables are compared to the ROWID pseudocolumn in the WHERE clause of an UPDATE or DELETE statement to identify the latest row fetched by a cursor. For an example, see the section "Fetching Across Commits" in Chapter 4.

MLSLABEL

With Trusted ORACLE, you use the MLSLABEL datatype to store variable-length, binary operating system labels. Trusted ORACLE uses labels to control access to data. For more information, see the Trusted ORACLE7 Server Administrator's Guide.

You can use the MLSLABEL datatype to define a database column. And, you can use the %TYPE and %ROWTYPE attributes to reference the column. However, with standard ORACLE, such columns can store only nulls.

With Trusted ORACLE, you can insert any valid operating system label into a column of type MLSLABEL. If the label is in text format, Trusted ORACLE converts it to a binary value automatically. The text string can be up to 255 bytes long. However, the internal length of an MLSLABEL value is between 2 and 5 bytes.

With Trusted ORACLE, you can also select values from a MLSLABEL column into a character variable. Trusted ORACLE converts the internal binary value to a VARCHAR2 value automatically.

________________________________________

Datatype Conversion

Sometimes it is necessary to convert a value from one datatype to another. For example, if you want to examine a rowid, you must convert it to a character string. PL/SQL supports both explicit and implicit (automatic) datatype conversion.

Explicit Conversion

To specify conversions explicitly, you use built-in functions that convert values from one datatype to another. Table 2 - 1 shows you which function to use in a given situation. For example, to convert a CHAR value to a NUMBER value, you use the function TO_NUMBER.

        TO

FROM	CHAR	DATE	NUMBER	RAW	ROWID

CHAR	TO_DATE	TO_NUMBER	HEXTORAW	CHARTOROWID

DATE	TO_CHAR

NUMBER	TO_CHAR	TO_DATE

RAW	RAWTOHEX

ROWID	ROWIDTOCHAR

Table 2 - 1.  Conversion Functions

For more information about these functions, see the section "Conversion Functions" later in this chapter.

Implicit Conversion

When it makes sense, PL/SQL can convert the datatype of a value implicitly. This allows you to use literals, variables, and parameters of one type where another type is expected. In the example below, the CHAR variables start_time and finish_time hold string values representing the number of seconds past midnight. The difference between those values must be assigned to the NUMBER variable elapsed_time. So, PL/SQL converts the CHAR values to NUMBER values implicitly.

DECLARE

   start_time    CHAR(5);

   finish_time   CHAR(5);

   elapsed_time  NUMBER(5);

BEGIN

   /* Get system time as seconds past midnight. */

   SELECT TO_CHAR(SYSDATE, 'SSSSS')

      INTO start_time FROM sys.dual;

   ----------------------------------

   -- do something

   ----------------------------------

   /* Get system time again. */

   SELECT TO_CHAR(SYSDATE, 'SSSSS')

       INTO finish_time FROM sys.dual;

   /* Compute elapsed time in seconds. */

   elapsed_time := finish_time - start_time;

   INSERT INTO results VALUES (..., elapsed_time);

END;

Before assigning a selected column value to a variable, PL/SQL will, if necessary, convert the value from the datatype of the source column to the datatype of the variable. This happens, for example, when you select a DATE column value into a VARCHAR2 variable. Likewise, before assigning or comparing the value of a variable to a database column, PL/SQL will, if necessary, convert the value from the datatype of the variable to the datatype of the target column.

If PL/SQL cannot determine which implicit conversion is needed, you get a compilation error. In such cases, you must use datatype conversion functions. Table 2 - 2 shows which implicit conversions PL/SQL can do.

        TO

FROM	BINARY	CHAR	DATE	LONG	NUMBER	RAW	ROWID	VARCHAR2

INTEGER

BINARY	Yes	Yes	Yes	Yes

INTEGER

CHAR	Yes	Yes	Yes	Yes	Yes	Yes	Yes

DATE	Yes	Yes	Yes

LONG	Yes	Yes	Yes

NUMBER	Yes	Yes	Yes	Yes

RAW	Yes	Yes	Yes

ROWID	Yes	Yes

VARCHAR2	Yes	Yes	Yes	Yes	Yes	Yes	Yes

Table 2 - 2.  Implicit Conversions

It is your responsibility to ensure that values are convertible. For instance, PL/SQL can convert the CHAR value '02-JUN-92' to a DATE value, but PL/SQL cannot convert the CHAR value 'YESTERDAY' to a DATE value. Similarly, PL/SQL cannot convert a CHAR value containing alphabetic characters to a NUMBER value.

Implicit versus Explicit Conversion

Generally, it is poor programming practice to rely on implicit datatype conversions because they can hamper performance and might change from one software release to the next. Also, implicit conversions are context sensitive and therefore not always predictable. Instead, use datatype conversion functions. That way, your applications will be more reliable and easier to maintain.

DATE Values

When you select a DATE column value into a CHAR or VARCHAR2 variable, PL/SQL must convert the internal binary value to a character value. So, PL/SQL calls the function TO_CHAR, which returns a character string in the default date format. To get other information such as the time or Julian date, you must call TO_CHAR with a format mask.

A conversion is also necessary when you insert a CHAR or VARCHAR2 value into a DATE column. So, PL/SQL calls the function TO_DATE, which expects the default date format. To insert dates in other formats, you must call TO_DATE with a format mask.

RAW and LONG RAW Values

When you select a RAW or LONG RAW column value into a CHAR or VARCHAR2 variable, PL/SQL must convert the internal binary value to a character value. In this case, PL/SQL returns each binary byte of RAW or LONG RAW data as a pair of characters. Each character represents the hexadecimal equivalent of a nibble (half a byte). For example, PL/SQL returns the binary byte 11111111 as the pair of characters 'FF'. The function RAWTOHEX does the same conversion.

A conversion is also necessary when you insert a CHAR or VARCHAR2 value into a RAW or LONG RAW column. Each pair of characters in the variable must represent the hexadecimal equivalent of a binary byte. If either character does not represent the hexadecimal equivalent of a nibble, an exception is raised.

________________________________________

Declarations

Your program stores values in variables and constants. As the program executes, the values of variables can change, but the values of constants cannot.

You can declare variables and constants in the declarative part of any PL/SQL block, subprogram, or package. Declarations allocate storage space for a value, specify its datatype, and name the storage location so that the value can be referenced. They can also assign an initial value and specify the NOT NULL constraint. A few examples follow:

birthdate  DATE;

emp_count  SMALLINT := 0;

acct_id    VARCHAR2(5) NOT NULL := 'AP001';

The first declaration names a variable of type DATE. The second declaration names a variable of type SMALLINT and uses the assignment operator (:=) to assign an initial value of zero to the variable. The third declaration names a variable of type VARCHAR2, specifies the NOT NULL constraint, and assigns an initial value of 'AP001' to the variable.

You cannot assign nulls to a variable or constant defined as NOT NULL. If you try, the predefined exception VALUE_ERROR is raised. The NOT NULL constraint must be followed by an initialization clause; otherwise, you get a compilation error. For example, the following declaration is illegal:

acct_id  VARCHAR2(5) NOT NULL;  -- illegal; not initialized

The next examples show that the expression following the assignment operator can be arbitrarily complex and can refer to previously initialized variables and constants:

pi      CONSTANT REAL := 3.14159;

radius  REAL := 1;

area    REAL := pi * radius**2;

In constant declarations, the reserved word CONSTANT must precede the type specifier, as the following example shows:

credit_limit  CONSTANT REAL := 5000.00;

This declaration names a constant of type REAL and assigns an initial (also final) value of 5000 to the constant. A constant must be initialized in its declaration; otherwise, you get a compilation error.

Using DEFAULT

If you prefer, you can use the reserved word DEFAULT instead of the assignment operator to initialize variables and constants. For example, the declarations

tax_year  SMALLINT := 92;

valid     BOOLEAN := FALSE;

can be rewritten as follows:

tax_year  SMALLINT DEFAULT 92;

valid     BOOLEAN DEFAULT FALSE;

You can also use DEFAULT to initialize subprogram parameters, cursor parameters, and fields in a user-defined record.

Using %TYPE

The %TYPE attribute provides the datatype of a variable, constant, or database column. In the following example, %TYPE provides the datatype of a variable:

credit  REAL(7,2);

debit   credit%TYPE;

Variables and constants declared using %TYPE are treated like those declared using a datatype name. For example, given the previous declarations, PL/SQL treats debit like a REAL(7,<|>2) variable.

The next example shows that a %TYPE declaration can include an initialization clause:

balance          NUMBER(7,2);

minimum_balance  balance%TYPE := 10.00;

The %TYPE attribute is particularly useful when declaring variables that refer to database columns. You can reference a table and column, or you can reference an owner, table, and column, as the following example shows:

my_dname  scott.dept.dname%TYPE;

Using %TYPE to declare my_dname has two advantages. First, you need not know the exact datatype of dname. Second, if the database definition of dname changes, the datatype of my_dname changes accordingly at run time.

Note, however, that a NOT NULL column constraint does not apply to variables declared using %TYPE. In the next example, even though the database column empno is defined as NOT NULL, you can assign a null to the variable my_empno:

DECLARE

   my_empno  emp.empno%TYPE;

   ...

BEGIN

   my_empno := NULL;  -- this works

   ...

END;

Using %ROWTYPE

The %ROWTYPE attribute provides a record type that represents a row in a table (or view). The record can store an entire row of data selected from the table or fetched by a cursor. In the example below, you declare two records. The first record stores a row selected from the emp table. The second record stores a row fetched by the c1 cursor.

DECLARE

   emp_rec  emp%ROWTYPE;

   CURSOR c1 IS SELECT deptno, dname, loc FROM dept;

   dept_rec  c1%ROWTYPE;

   ...

Columns in a row and corresponding fields in a record have the same names and datatypes. In the following example, you select column values into a record named emp_rec:

DECLARE

   emp_rec  emp%ROWTYPE;

   ...

BEGIN

   SELECT * INTO emp_rec FROM emp WHERE ...

   ...

END;

The column values returned by the SELECT statement are stored in fields. To reference a field, you use dot notation. For example, you might reference the deptno field as follows:

IF emp_rec.deptno = 20 THEN ...

In addition, you can assign the value of an expression to a specific field, as the following examples show:

emp_rec.ename := 'JOHNSON';

emp_rec.sal := emp_rec.sal * 1.15;

A %ROWTYPE declaration cannot include an initialization clause. However, there are two ways to assign values to all fields in a record at once. First, PL/SQL allows aggregate assignment between entire records if their declarations refer to the same table or cursor. For example, the following assignments are legal:

DECLARE

   dept_rec1  dept%ROWTYPE;

   dept_rec2  dept%ROWTYPE;

   CURSOR c1 IS SELECT deptno, dname, loc FROM dept;

   dept_rec3  c1%ROWTYPE;

   dept_rec4  c1%ROWTYPE;

BEGIN

   ...

   dept_rec1 := dept_rec2;

   dept_rec4 := dept_rec3;

   ...

But, because dept_rec2 is based on a table and dept_rec3 is based on a cursor, the following assignment is illegal:

dept_rec2 := dept_rec3;  -- illegal

Second, you can assign a list of column values to a record by using the SELECT or FETCH statement, as the example below shows. The column names must appear in the order in which they were defined by the CREATE TABLE or CREATE VIEW statement.

DECLARE

   dept_rec  dept%ROWTYPE;

   ...

BEGIN

   SELECT deptno, dname, loc INTO dept_rec FROM dept

      WHERE deptno = 30;

   ...

END;

However, you cannot assign a list of column values to a record by using an assignment statement. So, the following syntax is illegal:

record_name := (value1, value2, value3, ...);  -- illegal

Although you can retrieve entire records, you cannot insert them. For example, the following statement is illegal:

INSERT INTO dept VALUES (dept_rec1);  -- illegal

 Aliases

Select-list items fetched by a cursor associated with %ROWTYPE must have simple names or, if they are expressions, must have aliases. In the following example, you use an alias called wages:

-- available online in file EXAMP4

DECLARE

   CURSOR my_cursor IS SELECT sal + NVL(comm, 0) wages, ename

      FROM emp;

   my_rec  my_cursor%ROWTYPE;

BEGIN

   OPEN my_cursor;

   LOOP

      FETCH my_cursor INTO my_rec;

      EXIT WHEN my_cursor%NOTFOUND;

      IF my_rec.wages > 2000 THEN

         INSERT INTO temp VALUES (NULL, my_rec.wages,

            my_rec.ename);

      END IF;

   END LOOP;

   CLOSE my_cursor;

END;

For more information about column name aliases, see the ORACLE7 Server SQL Language Reference Manual.

Restrictions

PL/SQL does not allow forward references. You must declare a variable or constant before referencing it in other statements, including other declarative statements. For example, the following declaration of maxi is illegal:

maxi  INTEGER := 2 * mini;

mini  INTEGER := 15;

However, PL/SQL does allow the forward declaration of subprograms. For more information, see the section "Forward Declarations" in Chapter 6.

Some languages allow you to declare a list of variables belonging to the same datatype. PL/SQL does not allow this. For example, the following declaration is illegal:

i, j, k  SMALLINT;  -- illegal

The legal version follows:

i  SMALLINT;

j  SMALLINT;

k  SMALLINT;

________________________________________

Naming Conventions

The same naming conventions apply to all PL/SQL program objects and units including constants, variables, cursors, exceptions, procedures, functions, and packages. Names can be simple, qualified, remote, or both qualified and remote. For example, you might use the procedure name raise_salary in any of the following ways:

raise_salary(...);                      -- simple

emp_actions.raise_salary(...);          -- qualified

raise_salary@newyork(...);              -- remote

emp_actions.raise_salary@newyork(...);  -- qualified and remote

In the first case, you simply use the procedure name. In the second case, you must qualify the name using dot notation because the procedure is stored in a package called emp_actions. In the third case, you reference the database link newyork because the (stand-alone) procedure is stored in a remote database. In the fourth case, you qualify the procedure name and reference a database link.

Synonyms

You can create synonyms to provide location transparency for remote database objects such as tables, sequences, views, stand-alone subprograms, and packages. However, you cannot create synonyms for objects declared within subprograms or packages. That includes constants, variables, cursors, exceptions, and packaged procedures. For more information, see the sections "Remote Access" in Chapter 4 and "Stored Subprograms" in Chapter 6.

Scoping

Within the same scope, all declared identifiers must be unique. So, even if their datatypes differ, variables and parameters cannot share the same name. For example, two of the following declarations are illegal:

DECLARE

   valid_id  BOOLEAN;

   valid_id  VARCHAR2(5);  -- illegal duplicate identifier

   valid_id  INTEGER;      -- illegal triplicate identifier

   ...

For the scope rules that apply to variables and parameters, see the next section "Scope and Visibility."

Case-sensitivity

Like other identifiers, the names of variables and parameters are not case sensitive. For instance, PL/SQL considers the following names to be the same:

zip_code  INTEGER;

Zip_Code  INTEGER;

ZIP_CODE  INTEGER;

Database Table Names

In potentially ambiguous SQL statements, the names of local variables and formal parameters take precedence over the names of database tables. For example, the following UPDATE statement fails because PL/SQL assumes that emp refers to the loop counter:

FOR emp IN 1..5 LOOP

   ...

   UPDATE emp SET bonus = 500 WHERE ...

END LOOP;

Likewise, the following SELECT statement fails because PL/SQL assumes that emp refers to the formal parameter:

PROCEDURE calc_bonus (emp NUMBER, bonus OUT REAL) IS

   avg_sal  REAL;

   ...

BEGIN

   SELECT AVG(sal) INTO avg_sal FROM emp WHERE ...

   ...

END;

In such cases, you can prefix the table name with a username, as follows:

PROCEDURE calc_bonus (emp NUMBER, bonus OUT REAL) IS

   avg_sal  REAL;

   ...

BEGIN

   SELECT AVG(sal) INTO avg_sal FROM scott.emp WHERE ...

   ...

END;

However, it is better programming practice to rename the variable or formal parameter.

Database Column Names

The names of database columns take precedence over the names of local variables and formal parameters. For example, the following DELETE statement removes all employees from the emp table, not just KING, because ORACLE assumes that both enames in the WHERE clause refer to the database column:

DECLARE

   ename  CHAR(10) := 'KING';

BEGIN

   DELETE FROM emp WHERE ename = ename;

   ...

END;

In such cases, to avoid ambiguity, prefix the names of local variables and formal parameters with my_ as follows:

DECLARE

   my_ename  CHAR(10);

  ...

Or, use a block label to qualify references, as follows:

<<main>>

DECLARE

   ename  CHAR(10) := 'KING';

BEGIN

   DELETE FROM emp WHERE ename = main.ename;

   ...

END;

The next example shows that you can use a subprogram name to qualify references to local variables and formal parameters:

PROCEDURE calc_bonus (empno NUMBER, bonus OUT REAL) IS

   avg_sal  REAL;

   name     CHAR(10);

   job      CHAR(15) := 'SALESMAN';

BEGIN

   SELECT AVG(sal) INTO avg_sal FROM emp

       WHERE job = calc_bonus.job;  -- refers to local variable

   SELECT ename INTO name FROM emp

       WHERE empno = calc_bonus.empno;  -- refers to parameter

   ...

END;

________________________________________

Scope and Visibility

References to an identifier are resolved according to its scope and visibility. The scope of an identifier is that region of a program unit (block, subprogram, or package) from which you can reference the identifier. An identifier is visible only in the regions from which you can reference the identifier using an unqualified name.

For example, identifiers declared in a PL/SQL block are considered local to that block and global to all its sub-blocks. If a global identifier is redeclared in a sub-block, both identifiers remain in scope. Within the sub-block, however, only the local identifier is visible because you must use a qualified name to reference the global identifier.

Figure 2 - 2 shows the scope and visibility of a variable named x, which is declared in an enclosing block, then redeclared in a sub-block.

Although you cannot declare an identifier twice in the same block, you can declare the same identifier in two different blocks. The two objects represented by the identifier are distinct, and any change in one does not affect the other.

However, a block cannot reference identifiers declared in other blocks nested at the same level because those identifiers are neither local nor global to the block. The following example illustrates the scope rules:

DECLARE

   A  CHAR;

   B  REAL;

BEGIN

   -- identifiers available here: A (CHAR), B

   DECLARE

      A  INTEGER;

      C  REAL;

   BEGIN

      -- identifiers available here: A (INTEGER), B, C

   END;

   DECLARE

      D  REAL;

   BEGIN

      -- identifiers available here: A (CHAR), B, D

   END;

   -- identifiers available here: A (CHAR), B

END;

Recall that global identifiers can be redeclared in a sub-block, in which case the local declaration prevails and the sub-block cannot reference the global identifier unless you use a qualified name. The qualifier can be the label of an enclosing block as the following example shows:

<<outer>>

DECLARE

   birthdate  DATE;

BEGIN

   ...

   DECLARE

      birthdate  DATE;

   BEGIN

      ...

      IF birthdate = outer.birthdate THEN

         ...

      END IF;

   END;

END outer;

Or, as the next example shows, the qualifier can be the name of an enclosing subprogram:

PROCEDURE check_credit (...) IS

   rating  NUMBER;

   ...

   FUNCTION valid (...) RETURN BOOLEAN IS

      rating  NUMBER;

   BEGIN

      ...

      IF check_credit.rating < 3 THEN

         ...

   END valid;

BEGIN

   ...

END check_credit;

________________________________________

Assignments

Variables and constants are initialized every time a block or subprogram is entered. By default, variables are initialized to NULL. So, unless you expressly initialize a variable, its value is undefined, as the following example shows:

DECLARE

   count  INTEGER;

   ...

BEGIN

   count := count + 1;  -- assigns a null to count

      ...

Therefore, never reference a variable before you assign it a value.

You can use assignment statements to assign values to a variable. For example, the following statement assigns a new value to the variable bonus, overwriting its old value:

bonus := salary * 0.15;

The expression following the assignment operator can be arbitrarily complex, but it must yield a datatype that is the same as or convertible to the datatype of the variable.

Boolean Values

Only the values TRUE and FALSE and the non-value NULL can be assigned to a Boolean variable. For example, given the declaration

DECLARE

   done  BOOLEAN;

   ...

the following statements are legal:

BEGIN

   done := FALSE;

   WHILE NOT done LOOP

      ...

   END LOOP;

END;

When applied to PL/SQL expressions, the relational operators return a Boolean value. So, the following assignment is legal:

done := (count > 500);

Database Values

Alternatively, you can use the SELECT or FETCH statement to have ORACLE assign values to a variable. An example follows:

SELECT ename, sal + comm INTO last_name, wages FROM emp

   WHERE empno = emp_id;

For each item in the SELECT list, there must be a corresponding variable in the INTO list. Also, each item must return a value that is implicitly convertible to the datatype of its corresponding variable. For more information about the SELECT and FETCH statements, see Chapter 9.

________________________________________

Expressions and Comparisons

Expressions are constructed using operands and operators. An operand is a variable, constant, literal, or function call that contributes a value to an expression. An example of a simple arithmetic expression follows:

-X / 2

Unary operators such as the negation operator (-) operate on one operand; binary operators such as the division operator (/) operate on two operands. PL/SQL has no ternary operators.

The simplest expressions consist of a single variable, which yields a value directly. PL/SQL evaluates (finds the current value of) an expression by combining the values of the operands in ways specified by the operators. This always yields a single value and datatype. PL/SQL determines the datatype by examining the expression and the context in which it appears.

Operator Precedence

The operations within an expression are done in a particular order depending on their precedence (priority). Table 2 - 3 shows the default order of operations from first to last (top to bottom).

Operator	Operation

**, NOT	exponentiation, logical negation

+,-	identity, negation

*,/	multiplication, division

+,-,||	addition, subtraction, concatenation

=,!=,<,>,<=,>=,	comparison

IS NULL, LIKE, BETWEEN, IN

AND	conjunction

OR	inclusion

Table 2 - 3.  Order of Operations

Operators with higher precedence are applied first. For example, both of the following expressions evaluate to 8 because division has a higher precedence than addition:

5 + 12 / 4

12 / 4 + 5

Operators with the same precedence are applied in no particular order.

You can use parentheses to control the order of evaluation. For example, the following expression evaluates to 7, not 11, because parentheses override the default operator precedence:

(8 + 6) / 2

In the next example, the subtraction is done before the division because the most deeply nested subexpression is always evaluated first:

100 + (20 / 5 + (7 - 3))

The following example shows that you can always use parentheses to improve readability, even when they are not needed:

(salary * 0.05) + (commission * 0.25)

Logical Operators

The logical operators AND, OR, and NOT operate according to the tri-state logic illustrated by the truth tables in Table 2 - 4. AND and OR are binary operators; NOT is a unary operator.

NOT	TRUE	FALSE	NULL

FALSE	TRUE	NULL

AND	TRUE	FALSE	NULL

TRUE	TRUE	FALSE	NULL

FALSE	FALSE	FALSE	FALSE

NULL	NULL	FALSE	NULL

OR	TRUE	FALSE	NULL

TRUE	TRUE	TRUE	TRUE

FALSE	TRUE	FALSE	NULL

NULL	TRUE	NULL	NULL

Table 2 - 4.  Truth Tables

As the truth tables show, AND returns the value TRUE only if both its operands are true. On the other hand, OR returns the value TRUE if either of its operands is true. NOT returns the opposite value (logical negation) of its operand. For example, NOT TRUE returns FALSE.

NOT NULL returns NULL because nulls are indeterminate. It follows that if you apply the NOT operator to a null, the result is also indeterminate. Be careful. Nulls can cause unexpected results; see the section "Handling Nulls" later in this chapter.

When you do not use parentheses to specify the order of evaluation, operator precedence determines the order. Compare the following expressions:

NOT valid AND done     |     NOT (valid AND done)

If the Boolean variables valid and done both have the value FALSE, the first expression returns FALSE because NOT has a higher precedence than AND; therefore, the expression is equivalent to

(NOT valid) AND done

However, the second expression returns TRUE.

Comparison Operators

Comparison operators compare one expression to another. The result is always TRUE, FALSE, or NULL. Typically, you use comparison operators in the WHERE clause of SQL data manipulation statements and in conditional control statements.

 Relational Operators

The relational operators allow you to compare arbitrarily complex expressions. The following table gives the meaning of each operator:

Operator	Meaning

=	is equal to

!=	is not equal to

<	is less than

>	is greater than

<=	is less than or equal to

>=	is greater than or equal to

 IS NULL Operator

The IS NULL operator returns the Boolean value TRUE if its operand is null or FALSE if it is not null. Comparisons involving nulls always yield NULL. So, to test whether a value is NULL, do not use the statement

IF value = NULL THEN ...

Instead, use the following statement:

IF value IS NULL THEN ...

Be careful. Nulls can cause unexpected results; see the section "Handling Nulls" later in this chapter.

 LIKE Operator

You use the LIKE operator to compare a character value to a pattern. Case is significant. LIKE returns the Boolean value TRUE if the character patterns match or FALSE if they do not match.

The patterns matched by LIKE can include two special-purpose characters called wildcards. An underscore (_) matches exactly one character; a percent sign (%) matches zero or more characters. For example, if the value of ename is 'JOHNSON', the following expression evaluates to TRUE:

ename LIKE 'J%SON'

 BETWEEN Operator

The BETWEEN operator tests whether a value lies in a specified range. It means "greater than or equal to <low value> and less than or equal to <high value>." For example, the following expression evaluates to FALSE:

45 BETWEEN 38 AND 44

 IN Operator

The IN operator tests set membership. It means "equal to any member of." The set can contain nulls, but they are ignored. For example, the following statement does not delete rows in which the ename column

is null:

DELETE FROM emp WHERE ename IN (NULL, 'KING', 'FORD');

Furthermore, expressions of the form

value NOT IN set

evaluate to FALSE if the set contains a null. For example, instead of deleting rows in which the ename column is not null and not 'KING', the following statement deletes no rows:

DELETE FROM emp WHERE ename NOT IN (NULL, 'KING');

Concatenation Operator

The concatenation operator (||) appends one string to another. For example, the expression

'suit' || 'case'

returns the value

'suitcase'

If both operands belong to type CHAR, the concatenation operator returns a CHAR value. Otherwise, it returns a VARCHAR2 value.

Boolean Expressions

PL/SQL lets you compare variables and constants in both SQL and procedural statements. These comparisons, called Boolean expressions, consist of simple or complex expressions separated by relational operators. Often, Boolean expressions are connected by the logical operators AND, OR, and NOT. A Boolean expression always evaluates to TRUE, FALSE, or NULL.

In a SQL statement, Boolean expressions let you specify the rows in a table that are affected by the statement. In a procedural statement, Boolean expressions are the basis for conditional control. There are three kinds of Boolean expressions: arithmetic, character, and date.

 Arithmetic

You can use the relational operators to compare numbers for equality or inequality. Comparisons are quantitative; that is, one number is greater than another if it represents a larger quantity. For example, given the assignments

number1 := 75;

number2 := 70;

the following expression evaluates to TRUE:

number1 > number2

 Character

You can also compare character values for equality or inequality. Comparisons are based on the collating sequence used for the database character set. (A collating sequence is an internal ordering of the database character set; a range of numeric codes represents the individual characters.) One character value is greater than another if it follows it in the collating sequence. For example, given the assignments

string1 := 'Kathy';

string2 := 'Kathleen';

the following expression evaluates to TRUE:

string1 > string2

However, there are semantic differences between the CHAR and VARCHAR2 base types that come into play when you compare character values. For more information, refer to Appendix C.

 Date

Furthermore, you can compare dates. Comparisons are chronological; that is, one date is greater than another if it is more recent. For example, given the assignments

date1 := '01-JAN-91';

date2 := '31-DEC-90';

the following expression evaluates to TRUE:

date1 > date2

 Guidelines

In general, do not compare real numbers for exact equality or inequality. Real numbers are stored as approximate values. So, for example, the following IF condition might not evaluate to TRUE:

count := 1;

IF count = 1.0 THEN ...

It is a good idea to use parentheses when doing comparisons. For example, the following expression is illegal because 100 < tax yields a Boolean value of TRUE or FALSE, which cannot be compared with the number 500:

100 < tax < 500  -- illegal

The debugged version follows:

(100 < tax) AND (tax < 500)

A Boolean variable is itself either true or false. So, comparisons with the Boolean values TRUE and FALSE are redundant. For example, assuming the variable done belongs to type BOOLEAN, the IF statement

IF done = TRUE THEN ...

can be simplified as follows:

IF done THEN ...

Handling Nulls

You can avoid some common mistakes by keeping in mind the following rules:

•	comparisons involving nulls always yield NULL

•	applying the logical operator NOT to a null yields NULL

•	in conditional control statements, if the condition evaluates to NULL, its associated sequence of statements is not executed

In the example below, you might expect the sequence of statements to execute because x and y seem unequal. But remember, nulls are indeterminate. Whether x is equal to y or not is unknown. Therefore, the IF condition evaluates to NULL and the sequence of statements is bypassed.

x := 5;

y := NULL;

...

IF x != y THEN  -- evaluates to NULL, not TRUE

   sequence_of_statements;  -- not executed

END IF;

In the next example, you might expect the sequence of statements to execute because a and b seem equal. But, again, that is unknown, so the IF condition evaluates to NULL and the sequence of statements is bypassed.

a := NULL;

b := NULL;

...

IF a = b THEN  -- evaluates to NULL, not TRUE

   sequence_of_statements;  -- not executed

END IF;

 NOT Operator

Recall that applying the logical operator NOT to a null yields NULL. Thus, the following two statements are not always equivalent:

IF x > y THEN	|     IF NOT x > y THEN

   high := x;	|         high := y;

ELSE         	|     ELSE

   high := y;	|         high := x;

END IF;      	|     END IF;

The sequence of statements in the ELSE clause is executed when the IF condition evaluates to FALSE or NULL. So, if either or both x and y are null, the first IF statement assigns the value of y to high, but the second IF statement assigns the value of x to high. If neither x nor y is null, both IF statements assign the same value to high.

 Zero-Length Strings

PL/SQL treats any zero-length string like a null. This includes values returned by character functions and Boolean expressions. For example, the following statements assign nulls to the target variables:

null_string := TO_VARCHAR2('');

zip_code := SUBSTR(address, 25, 0);

valid := (name != '');

So, use the IS NULL operator to test for null strings, as follows:

IF my_string IS NULL THEN ...

 Concatenation Operator

The concatenation operator ignores null operands. For example, the expression

'apple' || NULL || NULL || 'sauce'

returns the value

'applesauce'

 Functions

If a null argument is passed to a function, a null is returned except in the following three cases.

DECODE

The function DECODE compares its first argument to one or more search expressions, which are paired with result expressions. Any search or result expression can be null. If a search is successful, the corresponding result is returned. In the next example, if the value of rating is null, DECODE returns the value 1000:

credit_limit := DECODE(rating, NULL, 1000, 'B', 2000, 'A', 4000);

NVL

If its first argument is null, the function NVL returns the value of its second argument. In the following example, if hire_date is null, NVL returns the value of SYSDATE; otherwise, NVL returns the value of hire_date:

start_date := NVL(hire_date, SYSDATE);

REPLACE

If its second argument is null, the function REPLACE returns the value of its first argument whether the optional third argument is present or not. For instance, after the assignment

new_string := REPLACE(old_string, NULL, my_string);

the values of old_string and new_string are the same.

If its third argument is null, REPLACE returns its first argument with every occurrence of its second argument removed. For example, after the assignments

syllabified_name := 'Gold-i-locks';

name := REPLACE(syllabified_name, '-', NULL);

the value of name is

'Goldilocks'

If its second and third arguments are null, REPLACE simply returns its first argument.

________________________________________

Built-in Functions

PL/SQL provides many powerful functions to help you manipulate data. You can use them wherever expressions of the same type are allowed. Furthermore, you can nest them.

The built-in functions fall into the following categories:

•	error-reporting functions

•	number functions

•	character functions

•	conversion functions

•	date functions

•	miscellaneous functions

You can use all the built-in functions in SQL statements except the error-reporting functions SQLCODE and SQLERRM. In addition, you can use all the functions in procedural statements except the miscellaneous function DECODE.

The SQL group functions AVG, MIN, MAX, COUNT, SUM, STDDEV, and VARIANCE are not built into PL/SQL. Nonetheless, you can use them in SQL statements (but not in procedural statements). For more information about the group functions, see the section "SQL Support" in Chapter 4.

For each built-in function, the arguments, the datatypes of the arguments, and the datatype of the returned value are given. The following example shows that the function LENGTH takes an argument of type VARCHAR2 and returns a value of type NUMBER:

function LENGTH (str VARCHAR2) return NUMBER

Error Reporting Functions

Two functions, SQLCODE and SQLERRM, give you information about PL/SQL execution errors. These functions are not allowed in SQL statements.

 SQLCODE

function SQLCODE return NUMBER

Returns the number associated with the most recently raised exception. This function is meaningful only in an exception handler. Outside a handler, SQLCODE always returns zero.

For internal exceptions, SQLCODE returns the number of the associated ORACLE error. The number that SQLCODE returns is negative unless the ORACLE error is no data found, in which case SQLCODE returns +100. For user-defined exceptions, SQLCODE +returns +1 unless you used the pragma EXCEPTION_INIT to associate the exception with an ORACLE error number, in which case SQLCODE returns that error number. (For more information about EXCEPTION_INIT, see the section "Using EXCEPTION_INIT" in Chapter 5.)

 SQLERRM

function SQLERRM [(error_number NUMBER)] return CHAR

Returns the error message associated with the current value of SQLCODE. Without an argument, SQLERRM is meaningful only in an exception handler. Outside a handler, SQLERRM with no argument always returns the message "ORA-0000: normal, successful completion."

For internal exceptions, SQLERRM returns the message associated with the ORACLE error that occurred. The message begins with the ORACLE error code.

For user-defined exceptions, SQLERRM returns the message "User-Defined Exception" unless you used the pragma EXCEPTION_INIT to associate the exception with an ORACLE error number, in which case SQLERRM returns the corresponding error message.

You can pass the argument error_number to SQLERRM, in which case SQLERRM returns the message associated with error_number.

Number Functions

Number functions take numeric arguments and return numeric values. The transcendental functions include trigonometric, logarithmic, and exponential functions.

The ordinary trigonometric functions (SIN, COS, and TAN) and the hyperbolic trigonometric functions (SINH, COSH, and TANH) are closely related. If n is a real number and i = -1 (the imaginary square root of -1), then

SIN(i*n) = i*SINH(n)

COS(i*n) = COSH(n)

TAN(i*n) = i*TANH(n)

 ABS

function ABS (n NUMBER) return NUMBER

Returns the absolute value of the number n.

 CEIL

function CEIL (n NUMBER) return NUMBER

Returns the smallest integer greater than or equal to the number n.

 COS

function COS (a NUMBER) return NUMBER

Returns the cosine of the angle a, which must be expressed in radians. A radian is 57.29578 (180/p) degrees. If a is in degrees, simply take COS(a/57.29578).

 COSH

function COSH (n NUMBER) return NUMBER

Returns the hyperbolic cosine of the number n.

 EXP

function EXP (n NUMBER) return NUMBER

Returns e raised to the nth power. The number e (<155> 2.71828) is the base of the system of natural logarithms.

 FLOOR

function FLOOR (n NUMBER) return NUMBER

Returns the largest integer equal to or less than the number n.

 LN

function LN (n NUMBER) return NUMBER

Returns the natural logarithm of the number n, where n is greater

 than 0.

 LOG

function LOG (m NUMBER, n NUMBER) return NUMBER

Returns the base-m logarithm of the number n, where m is greater

than 1 and n is greater than 0.

 MOD

function MOD (m NUMBER, n NUMBER) return NUMBER

Returns the remainder of the number m when divided by n. If n is 0, m is returned.

 POWER

function POWER (m NUMBER, n NUMBER) return NUMBER

Returns the number m raised to the nth power. The base m and the exponent n can be any numbers, but if m is negative, n must be an integer.

 ROUND

function ROUND (m NUMBER [, n NUMBER]) return NUMBER

Returns the number m rounded to n decimal places. If you omit n, m is rounded to zero decimal places. The number n can be negative, in which case ROUND rounds digits to the left of the decimal point.

 SIGN

function SIGN (n NUMBER) return NUMBER

Returns -1 if the number n is less than 0, 0 if n equals 0, or 1 if n is greater than 0.

 SIN

function SIN (a NUMBER) return NUMBER

Returns the sine of the angle a, which must be expressed in radians.

 SINH

function SINH (n NUMBER) return NUMBER

Returns the hyperbolic sine of the number n.

 SQRT

function SQRT (n NUMBER) return NUMBER

Returns the square root of the number n, which cannot be negative.

 TAN

function TAN (a NUMBER) return NUMBER

Returns the tangent of the angle a, which must be expressed in radians.

 TANH

function TANH (n NUMBER) return NUMBER

Returns the hyperbolic tangent of the number n.

 TRUNC

function TRUNC (m NUMBER [, n NUMBER]) returns NUMBER

Returns the number m truncated to n decimal places. If you omit n, m is truncated to zero decimal places. The number n can be negative, in which case TRUNC truncates (zeroes) digits to the left of the decimal point.

Character Functions

Character functions take character arguments. Some functions return character values, others return numeric values. Those functions that return a character value always return a VARCHAR2 value, with two exceptions. If passed a CHAR argument, the functions UPPER and LOWER return a CHAR value. Otherwise, they return a VARCHAR2 value.

 ASCII

function ASCII (char VARCHAR2) return NUMBER

Returns the collating code that represents the character char in the database character set. Whether the character set is (for example) 7-bit ASCII or EBCDIC Code Page 500, ASCII returns the appropriate collating code. ASCII is the inverse of the function CHR.

 CHR

function CHR (num NUMBER) return VARCHAR2

Returns the character in the database character set that the collating code num represents. Whether the character set is (for example) 7-bit ASCII or EBCDIC Code Page 500, CHR returns the appropriate character. CHR is the inverse of the function ASCII.

 CONCAT

function CONCAT (str1 VARCHAR2, str2 VARCHAR2) return VARCHAR2

Appends string str2 to string str1, then returns the combined string. If either argument is null, CONCAT returns the other argument. If both arguments are null, CONCAT returns a null.

 INITCAP

function INITCAP (str VARCHAR2) return VARCHAR2

Returns the string str, with the first letter of each word in upper case and all other letters in lower case. Words are delimited by spaces or non-alphanumeric characters.

 INSTR

function INSTR (str1 VARCHAR2, str2 VARCHAR2 [, pos NUMBER

   [,n NUMBER]]) return NUMBER

Searches string str1 starting at character position pos for the nth occurrence of string str2 and returns the position of the first character of that occurrence. If pos is negative, INSTR counts and searches backward from the end of str1. The arguments pos and n default to 1. The return value is relative to the beginning of str1 regardless of the value of pos and is expressed in characters. If the search fails, INSTR returns 0.

 INSTRB

function INSTRB (str1 VARCHAR2, str2 VARCHAR2 [, pos NUMBER

   [,n NUMBER]]) return NUMBER

Searches string str1 starting at byte position pos for the nth occurrence of string str2 and returns the position of the first byte of that occurrence. If pos is negative, INSTRB counts and searches backward from the end of str1. The arguments pos and n default to 1. The return value is relative to the beginning of str1 regardless of the value of pos and is expressed in bytes. If the search fails, INSTRB returns 0. For single-byte character sets, INSTRB is equivalent to INSTR.

 LENGTH

function LENGTH (str CHAR) return NUMBER

function LENGTH (str VARCHAR2) return NUMBER

Returns the number of characters in string str. If str belongs to datatype CHAR, the length includes trailing blanks. If str is null, LENGTH returns a null.

 LENGTHB

function LENGTHB (str CHAR) return NUMBER function LENGTHB (str VARCHAR2) return NUMBER

Returns the number of bytes in string str. If str belongs to datatype CHAR, the length includes trailing blanks. If str is null, LENGTHB returns a null. For single-byte character sets, LENGTHB is equivalent to LENGTH.

 LOWER

function LOWER (str CHAR) return CHAR

function LOWER (str VARCHAR2) return VARCHAR2

Returns the string str with all letters in lowercase.

 LPAD

function LPAD (str VARCHAR2, len NUMBER [, pad VARCHAR2])

   return VARCHAR2

Returns the string str left-padded to length len, with the sequence of characters in pad replicated as many times as necessary. If you do not specify pad, it defaults to a single blank. If str is longer than len characters, LPAD returns the first len characters in str.

 LTRIM

function LTRIM (str VARCHAR2 [, set VARCHAR2])

   return VARCHAR2

Returns the string str, with the initial characters removed up to the first character not in set. If you do not specify set, it defaults to a single blank.

 NLS_INITCAP

function NLS_INITCAP (str VARCHAR2 [, nlsparms VARCHAR2])

   return VARCHAR2

Returns the string str, with the first letter of each word in uppercase and all other letters in lowercase. Words are delimited by spaces or non-alphanumeric characters. The value of nlsparms has the form

'NLS_SORT = <sort>'

where sort is either a linguistic sort sequence or the keyword BINARY. The sort sequence handles special linguistic requirements for case conversion. To meet these requirements, NLS_INITCAP might return a value of different length than str. If you omit nlsparms, NLS_INITCAP uses the default sort sequence for your session. For more information, see the ORACLE7 Server Application Developer's Guide.

 NLS_LOWER

function NLS_LOWER (str VARCHAR2 [, nlsparms VARCHAR2])    return VARCHAR2

Returns the string str, with all letters in lowercase. The value of nlsparms has the form

'NLS_SORT = <sort>'

where sort is either a linguistic sort sequence or the keyword BINARY. The sort sequence handles special linguistic requirements for case conversion. To meet these requirements, NLS_LOWER might return a value of different length than str. If you omit nlsparms, NLS_LOWER uses the default sort sequence for your session. For more information, see the ORACLE7 Server Application Developer's Guide.

 NLS_UPPER

function NLS_UPPER (str VARCHAR2 [, nlsparms VARCHAR2])

   return VARCHAR2

Returns the string str, with all letters in upper case. The value of nlsparms has the form

'NLS_SORT = <sort>'

where sort is either a linguistic sort sequence or the keyword BINARY. The sort sequence handles special linguistic requirements for case conversion. To meet these requirements, NLS_UPPER might return a value of different length than str. If you omit nlsparms, NLS_UPPER uses the default sort sequence for your session. For more information, see the ORACLE7 Server Application Developer's Guide.

 NLSSORT

function NLSSORT (str VARCHAR2 [, nlsparms VARCHAR2]) return RAW

Returns the value of string str in the linguistic sort sequence specified by nlsparms. If you omit nlsparms, NLSSORT uses the default sort sequence for your session. The value of nlsparms has the form

'NLS_SORT = <sort>'

where sort is either a linguistic sort sequence or the keyword BINARY. If you specify BINARY, NLSSORT returns str.

In the WHERE clause, NLSSORT lets you specify comparisons based on linguistic rather than binary ordering. NLSSORT also lets you control the behavior of an ORDER BY clause independent of the NLS_SORT parameter. For more information, see the ORACLE7 Server Application Developer's Guide.

 REPLACE

function REPLACE (str1 VARCHAR2, str2 VARCHAR2

   [, str3 VARCHAR2]) return VARCHAR2

Returns the string str1, with every occurrence of substring str2 replaced by string str3. If you do not specify str3, all occurrences of str2 are removed. If you specify neither str2 nor str3, REPLACE returns a null.

 RPAD

function RPAD (str VARCHAR2, len NUMBER [, pad VARCHAR2])

   return VARCHAR2

Returns the string str right-padded to length len, with the sequence of characters in pad replicated as many times as necessary. If you do not specify pad, it defaults to a single blank. If str is longer than len characters, RPAD returns the first len characters in str.

 RTRIM

function RTRIM (str VARCHAR2 [, set VARCHAR2])

   return VARCHAR2

Returns the string str, with the final characters removed after the last character not in set. If you do not specify set, it defaults to a single blank.

 SOUNDEX

function SOUNDEX (str VARCHAR2) return VARCHAR2

Returns a character string containing the phonetic representation of string str. SOUNDEX allows you to compare English words that are spelled differently but sound alike. The phonetic representation is defined in The Art of Computer Programming, Volume 3, by Donald Knuth.

 SUBSTR

function SUBSTR (str VARCHAR2, pos NUMBER [, len NUMBER])

   return VARCHAR2

Returns a substring of string str, starting at character position pos and including len characters or, if you omit len, all characters to the end of str. The number pos cannot be zero. If pos is negative, SUBSTR counts backward from the end of str. The number len must be positive.

 SUBSTRB

function SUBSTRB (str VARCHAR2, pos NUMBER [, len NUMBER])

   return VARCHAR2

Returns a substring of string str, starting at byte position pos and including len bytes or, if you omit len, all bytes to the end of str. The number pos cannot be zero. If pos is negative, SUBSTR counts backward from the end of str. The number len must be positive. For single-byte character sets, SUBSTRB is equivalent to SUBSTR.

 TRANSLATE

function TRANSLATE (str VARCHAR2, set1 VARCHAR2, set2 CHAR)

   return VARCHAR2

Returns the string str after replacing all occurrences of set1 with the corresponding characters in set2. Characters that appear in str but not in set1 are unaffected. If set1 contains more characters than set2, the extra characters at the end of set1 have no corresponding characters in set2. So, if these extra characters appear in str, TRANSLATE removes them from the result value.

 UPPER

function UPPER (str CHAR) return CHAR

function UPPER (str VARCHAR2) return VARCHAR2

Returns the string str, with all letters in upper case.

Conversion Functions

Conversion functions convert a value from one datatype to another.

 CHARTOROWID

function CHARTOROWID (str CHAR) return ROWID

function CHARTOROWID (str VARCHAR2) return ROWID

Converts the string str from type CHAR or VARCHAR2 to type ROWID.

 CONVERT

function CONVERT (str VARCHAR2, set1 VARCHAR2,

   [, set2 VARCHAR2]) return VARCHAR2

Converts the string str from one character set (set2) to another (set1). Like set1, set2 can be a database column or a literal representing the name of a character set. The following table lists some common character sets:

Character Set	Description

US7ASCII	U.S. 7-bit ASCII character set

WE8DEC	DEC West DUropean 8-bit character set

WE8HP	HP West European Laserjet 8-bit character set

F7DEC	DEC French 7-bit character set

WE8EBCDIC500	IBM West European EBCDIC Code Page 500

WE8PC850	IBM PC Code Page 850

WE8IS08859P1	ISO 8859-1 West European 8-bit character set

For complete conversion, the destination character set (set1) must contain representations of all characters in the source character set (set2). Otherwise, replacement characters, which you can specify when defining a character set, are used.

 HEXTORAW

function HEXTORAW (str CHAR) return RAW

function HEXTORAW (str VARCHAR2) return RAW

Converts the hexadecimal string str from type CHAR or VARCHAR2 to type RAW.

 RAWTOHEX

function RAWTOHEX (bin RAW) return VARCHAR2

Converts the binary value bin from type RAW to a hexadecimal string of type VARCHAR2.

 ROWIDTOCHAR

function ROWIDTOCHAR (bin ROWID) return VARCHAR2

Converts the binary value bin from type ROWID to an 18-byte hexadecimal string of type VARCHAR2.

 TO_CHAR for Dates

function TO_CHAR (dte DATE [, fmt VARCHAR2 [, nlsparms] ])

   return VARCHAR2

Converts the date dte to a character string of type VARCHAR2 in the format specified by format model fmt. (For a list of available format models, see the function TO_DATE.) If you omit fmt, dte is converted to a character string in the default date format.

The argument nlsparms specifies the language in which the names and abbreviations of months and days are returned. It has the following form:

'NLS_DATE_LANGUAGE = <language>'

If you omit nlsparms, TO_CHAR uses the default language for your session.

 TO_CHAR for Numbers

function TO_CHAR (num NUMBER [, fmt VARCHAR2 [, nlsparms]])

   return VARCHAR2

Converts the number num to a character string of type VARCHAR2 in the format specified by format model fmt. (For a list of available format elements, see the function TO_NUMBER.) If you omit fmt, num is converted to a character string exactly long enough to hold the significant digits.

The argument nlsparms specifies the following characters, which are returned by the number format elements:

•	decimal character

•	group separator

•	local currency symbol

•	international currency symbol

This argument has the following form:

'NLS_NUMERIC_CHARACTERS = ''dg'',

NLS_CURRENCY = ''text'',

NLS_ISO_CURRENCY = ''text'' '

The characters d and g represent the decimal character and group separator, respectively. Notice that within the quoted string, you must use two single quotes to represent one. If you omit nlsparms, TO_CHAR uses the default parameter values for your session.

 TO_CHAR for Labels

function TO_CHAR (label [, fmt VARCHAR2]) return VARCHAR2

Converts a label of type MLSLABEL to a value of type VARCHAR2 in the format specified by fmt. If you omit fmt, the label is converted to a VARCHAR2 value in the default label format.

Use TO_CHAR for label conversion only with Trusted ORACLE. For more information, see the Trusted ORACLE7 Server Administrator's Guide.

 TO_DATE

function TO_DATE (str VARCHAR2 [, fmt VARCHAR2 [, nlsparms]])

   return DATE

function TO_DATE (num NUMBER, fmt VARCHAR2 [, nlsparms] ])

   return DATE

Converts the string str or the number num to a value of type DATE in the format specified by format model fmt. The following table lists the available format models:

Format Model	Description

CC,SCC	century (S prefixes BC dates with a minus sign)

YYYY,SYYYY	year (S prefixes BC dates with  minus sign

IYYY	year based on ISO standard

YYY,YY,Y	last three, two, or one digit(s) of year

IYY,IY,I	last three, two, or one digit(s) of ISO year

Y,YYY	year with comma

YEAR,SYEAR	year spelled out (S prefixes BC dates with a mi

nus sign

RR	last two digits of year in another century

BC,AD	BC or AD indicator

B.C.,A.D.	BC or AD indicator with periods

Q	quarter of year (1-4; JAN-MAR = 1)

MM	month (01-12; JAN = 01)

RM	Roman numeral month (I-XII;JAN=I0

MONTH	name of month

MON	abbreviated name of month

WW	week of year (1-53)

IW	week of year (1-52 or 1-53) based on ISO stan

dard

W	week of month (1-5)

DDD	day of year (1-366)

DD	day of month (1-31)

D	day of week (1-7)

DAY	name of day

DY	abbreviated name of day

J	Julian day (number of days since January 1, 4712)

AM, PM	meridian indicator

A.M., P.M.	meridian indicator with periods

HH,HH12	hour of day (1-12)

HH24	hours of day (0-23)

MI	minute (0-59)

SS	second (0-59)

SSSSS	seconds past midnight (0-86399)

If you omit fmt, str must be in the default date format. If fmt is 'J' (for Julian day, the number of days since January 1, 4712 BC), num must be an integer.

The argument nlsparms specifies the language in which the names and abbreviations of months and days are returned. It has the following form:

'NLS_DATE_LANGUAGE = <language>'

If you omit nlsparms, TO_DATE uses the default language for your session.

 TO_LABEL

function TO_LABEL (str CHAR [, fmt VARCHAR2]) return MLSLABEL

function TO_LABEL (str VARCHAR2 [, fmt VARCHAR2]) return MLSLABEL

Converts the string str, which contains a label in the format specified by fmt, to a value of type MLSLABEL. If you omit fmt, str must be in the default label format.

TO_LABEL is available only with Trusted ORACLE. For more information, see the Trusted ORACLE7 Server Administrator's Guide.

 TO_MULTI_BYTE

function TO_MULTI_BYTE (str CHAR) return CHAR

function TO_MULTI_BYTE (str VARCHAR2) return VARCHAR2

Returns the string str, with all its single-byte characters converted to their multibyte equivalents. Single-byte characters in str that have no multibyte equivalents are returned unconverted. TO_MULTI_BYTE is useful only if your database character set contains single-byte and multibyte characters.

 TO_NUMBER

function TO_NUMBER (str CHAR [, fmt VARCHAR2 [, nlsparms]])

   return NUMBER

function TO_NUMBER (str VARCHAR2 [, fmt VARCHAR2 [, nlsparms]])

   return NUMBER

Converts the string str from a value of type CHAR or VARCHAR2 to a value of type NUMBER in the format specified by format model fmt. A number format model consists of format elements, which are listed in the following table:

Element	Example	Description

9	9999	sigficant digit

0	0999	leading zero (instead of a blank)

$	$999	leading dollar sig

B	B999	leading blank (instead of a zero)

MI	999MI	trailing minus sign

S	S999	leading plus or minus sign

PR	999PR	angle brackerts for negative values

D	99D99	decimal character

G	9G99	group seperator

C	C999	ISO currency symbol

L	L999	local currency symbol

,	9,999	comm

.	99.99	peirod

V	999V99	10n multiplier; n is the number of 9s after V

EEEE	9.99EEEE	scientific notation

RN,rn	RN	upper or lowercase Roman numeral

The string str must represent a valid number. The argument nlsparms specifies the following characters, which are returned by the number format model:

•	decimal character

•	group separator

•	local currency symbol

•	international currency symbol

This argument has the following form:

'NLS_NUMERIC_CHARACTERS = ''dg'',

NLS_CURRENCY = ''text'',

NLS_ISO_CURRENCY = ''text'' '

The characters d and g represent the decimal character and group separator, respectively. Notice that within the quoted string, you must use two single quotes to represent one. If you omit nlsparms, TO_NUMBER uses the default parameter values for your session.

 TO_SINGLE_BYTE

function TO_SINGLE_BYTE (str CHAR) return CHAR

function TO_SINGLE_BYTE (str VARCHAR2) return VARCHAR2

Returns the string str, with all its multibyte characters converted to their single-byte equivalents. Multibyte characters in str that have no single-byte equivalents are returned unconverted. TO_SINGLE_BYTE is useful only if your database character set contains single-byte and multibyte characters.

Date Functions

Date functions take date arguments and return date values, except MONTHS_BETWEEN, which returns a numeric value.

 ADD_MONTHS

function ADD_MONTHS (dte DATE, num NUMBER) return DATE

function ADD_MONTHS (num NUMBER, dte DATE) return DATE

Returns the date dte plus or minus num months. The number num must be an integer. If dte is the last day of the month or if the resulting month has fewer days than the day component of dte, ADD_MONTHS returns the last day of the resulting month. Otherwise, ADD_MONTHS returns the day component of dte.

 LAST_DAY

function LAST_DAY (dte DATE) return DATE

Returns the date of the last day of the month containing date dte.

 MONTHS_BETWEEN

function MONTHS_BETWEEN (dte1 DATE, dte2 DATE) return NUMBER

Returns the number of months between date dte1 and date dte2.  If dte1 is later than dte2, the result is positive. If dte1 is earlier than dte2, the result is negative. If dte1 and dte2 fall on the same (or the last) days of their respective months, MONTHS_BETWEEN returns an integer. Otherwise, MONTHS_BETWEEN returns a fractional number, which is based on a 31-day month and reflects any difference in the time components of dte1 and dte2.

 NEW_TIME

function NEW_TIME (dte DATE, zon1 VARCHAR2, zon2 VARCHAR2)

return DATE

Given a date and time dte in time zone zon1, returns the corresponding date and time in zon2. The following table lists the possible values of zon1 and zon2:

Value	Description

AST	Atlantic Standard Time

ADT	Atlantic Daylight Time

BST	Bering Standard Time

BDT	Bering Daylight Time

CST	Central Standard Time

CDT	Central Daylight Time

EST	Eastern Standard Time

EDT	Eastern Daylight Time

GMT	Greenwich Mean Time

HST	Alaska-Hawaii Standard Time

HDT	Alaska-Hawaii Daylight Time

MST	Mountain Standard Time

MDT	Mountain Daylight Time

NST	Newfoundland Standard Time

PST	Pacific Standard Time

PDT	Pacific Daylight Time

YST	Yukon Standard Time

YDT	Yukon Daylight Time

 NEXT_DAY

function NEXT_DAY (dte DATE, day VARCHAR2) return DATE

Returns the date of the first day of the week named by day that is later than date dte. The argument day must be one of the seven days of a week.

 ROUND

function ROUND (dte DATE [, fmt VARCHAR2]) return DATE

Returns dte rounded to the unit specified by format model fmt.  If you omit fmt, dte is rounded to the nearest day. The following table lists the available format models:

Format Model	Description

CC,SCC	century

SYYY,YYYY,YEAR,	year (rounds up on July 1)

SYEAR,YYY,YY,Y

Q	quarter (rounds up on 16th day of 2nd month)

MONTH, MON, 	month (rounds up on 16th day)

MM

WW	first day of the week in year

W	first day of the week in month

DDD,DD,J	day

DAY,DY,D	nearest Sunday

HH,HH12,HH24	hour

MI	minute

 SYSDATE

function SYSDATE return DATE

Returns the current system date and time. SYSDATE takes no arguments.

 TRUNC

function TRUNC (dte DATE [, fmt VARCHAR2]) return DATE

Returns date dte with the time portion of the day truncated as specified by format model fmt. (For a list of available format models, see the function ROUND.) If you omit fmt, dte is truncated to the nearest day.

Miscellaneous Functions

All the miscellaneous functions are allowed in SQL statements and, except for DECODE, in procedural statements.

 DECODE

function DECODE (expr, search1, result1 [,search2, result2] ...

   [default] )

The expression expr is compared to each search value. If expr equals a search value, the corresponding result is returned. If no match is found, DECODE returns the default value, or a null if a default value was not supplied.

The expression expr can be any datatype, but the search value should be the same datatype as expr. The value returned is forced to the same datatype as result1. DECODE is allowed only in SQL statements.

 DUMP

function DUMP (expr DATE [, fmt BINARY_INTEGER

   [, pos BINARY_INTEGER [, len BINARY_INTEGER]]]) return VARCHAR2

function DUMP (expr NUMBER [, fmt BINARY_INTEGER

   [, pos BINARY_INTEGER [, len BINARY_INTEGER]]]) return VARCHAR2

function DUMP (expr VARCHAR2 [, fmt BINARY_INTEGER

   [, pos BINARY_INTEGER [, len BINARY_INTEGER]]]) return VARCHAR2

Returns the internal representation of expression expr.  The argument fmt determines the format of the return value (8=octal, 10=decimal, 16=hexadecimal, and 17=single characters). The arguments pos and len specify which part of the representation is returned. The default is to return the entire representation in decimal.

 GREATEST

function GREATEST (expr1, expr2, expr3, ...)

Returns the greatest value in a list of values. The values of expressions expr2, expr3, and so on, are converted to the datatype of expression expr1. So, all datatypes must be compatible with that of expr1. GREATEST compares the expressions using non-blank-padding semantics (discussed in Appendix C).

 GREATEST_LB

function GREATEST_LB (label [,label] ...) return MLSLABEL

Returns the greatest lower bound of the list of labels. Each label must belong to datatype MLSLABEL or be a quoted literal in the default label format.

GREATEST_LB is available only with Trusted ORACLE. For more information, see the Trusted ORACLE7 Server Administrator's Guide.

 LEAST

function LEAST (expr1, expr2, expr3, ...)

Returns the least value in a list of values. The values of expressions expr2, expr3, and so on, are converted to the datatype of expression expr1. So, all datatypes must be compatible with that of expr1. LEAST compares the expressions using non-blank-padding semantics (discussed in Appendix C).

 LEAST_UB

function LEAST_UB (label [,label] ...) return MLSLABEL

Returns the least upper bound of the list of labels. Each label must belong to datatype MLSLABEL or be a quoted literal in the default label format.

LEAST_LB is available only with Trusted ORACLE. For more information, see the Trusted ORACLE7 Server Administrator's Guide.

 NVL

function NVL (str1 CHAR, str2 CHAR) return CHAR

function NVL (dte1 DATE, dte2 DATE) return DATE

function NVL (bool1 BOOLEAN, bool2 BOOLEAN) return BOOLEAN

function NVL (num1 NUMBER, num2 NUMBER) return NUMBER

function NVL (str1 VARCHAR2, str2 VARCHAR2) return VARCHAR2

function NVL (lbl1 MLSLABEL, lbl2 MLSLABEL) return MLSLABEL

Takes two arguments of the same type and returns a value of that type. If the first argument is not null, its value is returned. If the first argument is null, the value of the second argument is returned.

 UID

function UID return NUMBER

Returns the unique identification number assigned to the current ORACLE user. UID takes no arguments.

 USER

function USER return VARCHAR2

Returns the username of the current ORACLE user. USER takes no arguments.

 USERENV

function USERENV (str VARCHAR2) return VARCHAR2

Returns information about the current session. You can use the information to write an application audit trail table or to determine which language and character set are in use.

The string str can have any of the following values:

'ENTRYID'	Returns an auditing entry identifier.

'LABEL'	Returns the session label. This option is available only with Trusted ORACLE. For more information, see the Trusted ORACLE7 Server Administrator's Guide.

'LANGUAGE'	Returns the language, territory, and database character set in use.

'SESSIONID'	Returns the auditing session identifier.

'TERMINAL'	Returns the operating system identifier for the session terminal.

You cannot specify the 'ENTRYID' or 'SESSIONID' option in SQL statements that access a remote database.

 VSIZE

function VSIZE (expr DATE) return NUMBER

function VSIZE (expr NUMBER) return NUMBER

function VSIZE (expr VARCHAR2) return NUMBER

Returns the number of bytes in the internal representation of expression expr. If expr is null, VSIZE returns a null.

________________________________________

PL/SQL Tables

PL/SQL provides two composite datatypes: TABLE and RECORD. This section discusses the TABLE type; the next section discusses the RECORD type.

Objects of type TABLE are called PL/SQL tables, which are modelled as (but not the same as) database tables. PL/SQL tables use a primary key to give you array-like access to rows.

Like the size of a database table, the size of a PL/SQL table is unconstrained. That is, the number of rows in a PL/SQL table can increase dynamically. So, your PL/SQL table grows as new rows are added.

PL/SQL tables can have one column and a primary key, neither of which can be named. The column can belong to any scalar type, but the primary key must belong to type BINARY_INTEGER. Future versions of PL/SQL will allow PL/SQL tables to have multiple, named columns and composite primary keys of any type.

Declaring PL/SQL Tables

PL/SQL tables must be declared in two steps. First, you define a TABLE type, then declare PL/SQL tables of that type. You can declare TABLE types in the declarative part of any block, subprogram, or package using the syntax

TYPE type_name IS TABLE OF

   { column_type | variable%TYPE | table.column%TYPE } [NOT NULL]

   INDEX BY BINARY_INTEGER;

where type_name is a type specifier used in subsequent declarations of PL/SQL tables and column_type is any scalar (not composite) datatype such as CHAR, DATE, or NUMBER. You can use the %TYPE attribute to specify a column datatype.

In the following example, you declare a TABLE type called EnameTabTyp:

DECLARE

   TYPE EnameTabTyp IS TABLE OF CHAR(10)

      INDEX BY BINARY_INTEGER;

   ...

You could have used %TYPE to provide the column datatype, as follows:

DECLARE

   TYPE EnameTabTyp IS TABLE OF emp.ename%TYPE

      INDEX BY BINARY_INTEGER;

   ...

Once you define type EnameTabTyp, you can declare PL/SQL tables of that type, as follows:

ename_tab  EnameTabTyp;

The identifier ename_tab represents an entire PL/SQL table.

A PL/SQL table is unconstrained because its primary key can assume any value in the range of values defined for BINARY_INTEGER. As a result, you cannot initialize a PL/SQL table in its declaration. For example, the following declaration is illegal:

ename_tab  EnameTabTyp := ('CASEY', 'STUART', 'CHU');  -- illegal

PL/SQL tables follow the usual scoping and instantiation rules. (Instantiation is the creation of a new instance of a program object.) In a package, PL/SQL tables are instantiated when you first reference the package and cease to exist when you exit the application or end the database session. In a block or subprogram, they are instantiated when you enter the block or subprogram and cease to exist when you exit the block or subprogram.

Like scalar variables, PL/SQL tables can be declared as the formal parameters of procedures and functions. The restrictions that apply to scalar parameters also apply to PL/SQL tables. Some packaged examples follow:

PACKAGE emp_actions IS

   TYPE EnameTabTyp IS TABLE OF emp.ename%TYPE

      INDEX BY BINARY_INTEGER;

   TYPE SalTabTyp IS TABLE OF emp.sal%TYPE

      INDEX BY BINARY_INTEGER;

   ename_tab  EnameTabTyp;

   sal_tab    SalTabTyp;

   ...

   PROCEDURE hire_batch(

      ename_tab  EnameTabTyp,

      sal_tab    SalTabTyp,

       ...);

   PROCEDURE log_names(

      ename_tab  EnameTabTyp,

      num        BINARY_INTEGER);

   ...

END emp_actions;

To define the behavior of formal parameters, you use parameter modes, which are discussed in Chapter 6. OUT parameters let you return values to the caller of a subprogram when you exit. If you exit successfully, PL/SQL assigns row values to the actual parameters. However, if you exit with an unhandled exception, PL/SQL does not assign row values to the actual parameters.

Referencing PL/SQL Tables

To reference rows in a PL/SQL table, you specify a primary key value using the array-like syntax

plsql_table_name(primary_key_value)

where primary_key_value belongs to type BINARY_INTEGER. For example, you reference the third row in PL/SQL table ename_tab as follows:

ename_tab(3) ...

The magnitude range of a BINARY_INTEGER value is -231- 1 .. 231- 1, so the primary key value can be negative. For instance, the following reference is legal:

ename_tab(-5) ...

For an exception, see the section "Using Host Arrays with PL/SQL Tables" in Chapter 8.

You can assign the value of a PL/SQL expression to a specific row using the following syntax:

plsql_table_name(primary_key_value) := plsql_expression;

In the next example, you assign the sum of variables salary and increase to the fifth row in PL/SQL table sal_tab:

sal_tab(5) := salary + increase;

In the example below, you use a cursor FOR loop to load two PL/SQL tables. A cursor FOR loop implicitly declares its loop index as a record, opens the cursor associated with a given query, repeatedly fetches rows of values from the cursor into fields in the record, then closes the cursor. For more information about cursor FOR loops, see the section "Cursor Management" in Chapter 4.

DECLARE

   TYPE EnameTabTyp IS TABLE OF emp.ename%TYPE

      INDEX BY BINARY_INTEGER;

   TYPE SalTabTyp IS TABLE OF emp.sal%TYPE

       INDEX BY BINARY_INTEGER;

   ename_tab  EnameTabTyp;

   sal_tab    SalTabTyp;

   i          BINARY_INTEGER := 0;

   ...

BEGIN

   -- load employee names and salaries into PL/SQL tables

   FOR emprec IN (SELECT ename, sal FROM emp) LOOP

      i := i + 1;

      ename_tab(i) := emprec.ename;

      sal_tab(i) := emprec.sal;

   END LOOP;

   -- process the tables

   process_sals(ename_tab, sal_tab);

   ...

END;

In the next example, you use dot notation to reference the package emp_actions seen earlier in this section:

DECLARE

   ...

   i  BINARY_INTEGER := 0;

BEGIN

   -- load employee names into a PL/SQL table

   FOR emprec IN (SELECT ename FROM emp ORDER BY ename) LOOP

      i := i + 1;

      emp_actions.ename_tab(i) := emprec.ename;

   END LOOP;

   -- process the PL/SQL table

   emp_actions.log_names(emp_actions.ename_tab, i);

   ...

END;

Until a row is assigned a value, it does not exist. If you try to reference an uninitialized row, PL/SQL raises the predefined exception NO_DATA_FOUND. Consider the following example:

DECLARE

   TYPE JobTabTyp IS TABLE OF CHAR(14)

      INDEX BY BINARY_INTEGER;

   job_tab  JobTabTyp;

BEGIN

   job_tab(1) := 'CLERK';

   IF job_tab(2) = 'CLERK' THEN  -- raises NO_DATA_FOUND

       ...

   END IF;

   ...

EXCEPTION

   WHEN NO_DATA_FOUND THEN

      -- here because job_tab(2) does not exist

      ...

END;

Row references such as job_tab(1) are allowed as actual parameters in subprogram calls but are subject to the same restrictions as scalar variables.

Maintaining a Row Count

Remember, the size of a PL/SQL table is unconstrained. So, if you want to maintain a row count, you must declare a variable for that purpose. For example, you might declare an INTEGER variable named row_count to store the number of rows currently in your PL/SQL table.

What happens if a PL/SQL table grows too large? Consider the following example:

DECLARE

   TYPE DateTabTyp IS TABLE OF DATE

      INDEX BY BINARY_INTEGER;

   hiredate_tab  DateTabTyp;

   i  BINARY_INTEGER := 0;

   ...

BEGIN

   /* Initialize PL/SQL table. */

   LOOP

      i := i + 1;

      hiredate_tab(i) := SYSDATE;

      -- EXIT WHEN statement omitted

   END LOOP;

   ...

END;

With each iteration of the basic loop, another row is added to the PL/SQL table. The loop cannot complete because it contains no EXIT WHEN statement. Eventually, PL/SQL runs out of memory and raises the predefined exception STORAGE_ERROR.

Inserting and Fetching Rows

You must use a loop to INSERT values from a PL/SQL table into a database column. Likewise, you must use a loop to FETCH values from a database column into a PL/SQL table. (No stream interface like that provided by the ORACLE Precompilers for host arrays is available for PL/SQL tables.) For example, given the declarations

DECLARE

   TYPE EmpnoTabTyp IS TABLE OF NUMBER(4)

      INDEX BY BINARY_INTEGER;

   TYPE EnameTabTyp IS TABLE OF CHAR(10)

      INDEX BY BINARY_INTEGER;

   ...

   empno_tab  EmpnoTabTyp;

   ename_tab  EnameTabTyp;

   ...

you might use the following procedure to INSERT values from the PL/SQL tables into the emp database table:

PROCEDURE insert_emp_data(

   rows       BINARY_INTEGER,

   empno_tab  EmpnoTabTyp,

   ename_tab  EnameTabTyp,

   ...) IS

BEGIN

   FOR i IN 1..rows LOOP

      INSERT INTO emp (empno, ename, ...)

         VALUES (empno_tab(i), ename_tab(i), ...);

   END LOOP;

END;

Similarly, you might use the next procedure to FETCH all rows from the emp database table into PL/SQL tables empno_tab and ename_tab:

PROCEDURE fetch_emp_data(

   rows       OUT BINARY_INTEGER,

   empno_tab  OUT EmpnoTabTyp,

   ename_tab  OUT EnameTabTyp,

   ...) IS

BEGIN

   rows := 0;

   FOR emprec IN (SELECT * FROM emp) LOOP

      rows := rows + 1;

      empno_tab(rows) := emprec.empno;

      ename_tab(rows) := emprec.ename;

      ...

   END LOOP;

END;

However, you cannot reference PL/SQL tables in the INTO clause. For example, the following SELECT statement is illegal:

PROCEDURE fetch_emp_data(

   rows       OUT BINARY_INTEGER,

   empno_tab  OUT EmpnoTabTyp,

   ename_tab  OUT EnameTabTyp,

   ...) IS

BEGIN

   SELECT empno, ename

      INTO empno_tab, ename_tab  -- illegal

      FROM emp;

   ...

END;

Deleting Rows

There is no straightforward way to delete rows from a PL/SQL table because the DELETE statement cannot specify PL/SQL tables. Setting a row to NULL as follows does not work because the row remains:

sal_tab(3) := NUll;

Referencing this row does not raise the exception NO_DATA_FOUND.

Although you cannot delete individual rows from a PL/SQL table, you can use a simple workaround to delete entire PL/SQL tables. First, declare another PL/SQL table of the same type and leave it empty. Later, when you want to delete the original PL/SQL tables, simply assign the empty table to them, as shown in the following example:

DECLARE

   TYPE NumTabTyp IS TABLE of NUMBER

      INDEX BY BINARY_INTEGER;

   sal_tab    NumTabTyp;

   empty_tab  NumTabTyp;

   ...

BEGIN

   /* Load salary table. */

   FOR i IN 1..50 LOOP

      sal_tab(i) := i;

   END LOOP;

   ...

   /* Delete all rows from salary table. */

   sal_tab := empty_tab;

   ...

   IF sal_tab(3) = 3 THEN ...  -- raises NO_DATA_FOUND

   ...

END;

________________________________________

User-defined Records

You can use the %ROWTYPE attribute to declare a record that represents a row in a table or a row fetched by a cursor. However, you cannot specify the datatypes of fields in the record or define fields of your own. The composite datatype RECORD lifts those restrictions.

As you might expect, objects of type RECORD are called records. Unlike PL/SQL tables, records have uniquely named fields, which can belong to different datatypes. For example, suppose you have different kinds of data about an employee such as name, salary, hire date, and so on. This data is dissimilar in type but logically related. A record that contains such fields as the name, salary, and hire date of an employee would let you treat the data as a logical unit.

Declaring Records

Like PL/SQL tables, records must be declared in two steps. First, you define a RECORD type, then declare user-defined records of that type.

You can declare RECORD types in the declarative part of any block, subprogram, or package using the syntax

TYPE type_name IS RECORD

   (field_name1 {field_type | variable%TYPE | table.column%TYPE

      | table%ROWTYPE} [NOT NULL],

    field_name2 {field_type | variable%TYPE | table.column%TYPE

      | table%ROWTYPE} [NOT NULL],

    ...);

where type_name is a type specifier used in subsequent declarations of records and field_type is any datatype including RECORD and TABLE. You can use the %TYPE or %ROWTYPE attribute to specify a field datatype. In the following example, you declare a RECORD type named DeptRecTyp:

DECLARE

   TYPE DeptRecTyp IS RECORD(

      deptno  NUMBER(2) NOT NULL := 20,

      dname   dept.dname%TYPE,

      loc     dept.loc%TYPE);

   ...

Notice that the field declarations are like variable declarations. Each field has a unique name and specific datatype. You can add the NOT NULL constraint to any field declaration and so prevent the assigning of nulls to that field. Remember, fields declared as NOT NULL must be initialized.

Once you define type DeptRecTyp, you can declare records of that type, as follows:

dept_rec  DeptRecTyp;

The identifier dept_rec represents an entire record.

Unlike PL/SQL tables, a record can be initialized in its declaration, as this example shows:

DECLARE

   TYPE TimeTyp IS RECORD(

       second  SMALLINT := 0,

       minute  SMALLINT := 0,

       hour    SMALLINT := 0);

   ...

When you declare a record of type TimeTyp, its three fields assume an initial value of zero.

User-defined records follow the usual scoping and instantiation rules. In a package, they are instantiated when you first reference the package and cease to exist when you exit the application or end the database session. In a block or subprogram, they are instantiated when you enter the block or subprogram and cease to exist when you exit the block or subprogram.

Like scalar variables, user-defined records can be declared as the formal parameters of procedures and functions. An example follows:

PACKAGE emp_actions IS

   TYPE EmpRecTyp IS RECORD(

      empno     NUMBER(4) NOT NULL := 1001,

      ename     CHAR(10),

      job       CHAR(14),

      mgr       NUMBER(4),

      hiredate  DATE

      sal       NUMBER(7,2),

      comm      NUMBER(7,2),

      deptno    NUMBER(4));

   ...

   PROCEDURE hire_employee (emp_rec EmpRecTyp);

   ...

END emp_actions;

Remember, OUT parameters let you return values to the caller of a procedure when you exit. If you exit successfully, PL/SQL assigns field values to the actual parameters. However, if you exit with an unhandled exception, PL/SQL does not assign field values to the actual parameters.

Referencing Records

To reference individual fields in a record, you use dot notation and the following syntax:

record_name.field_name

For example, you reference the ename field in the emp_rec record as follows:

emp_rec.ename ...

You can assign the value of a PL/SQL expression to a specific field by using the following syntax:

record_name.field_name := plsql_expression;

In the next example, you convert an employee name to uppercase:

emp_rec.ename := UPPER(emp_rec.ename);

Instead of assigning values separately to each field in a record, you can assign values to all fields at once. This can be done in two ways. First, you can assign one record to another if they belong to the same datatype. For example, given the declarations

DECLARE

   TYPE  DeptRecTyp IS RECORD(...);

   dept_rec1  DeptRecTyp;

   dept_rec2  DeptRecTyp;

   ...

the following assignment is legal:

BEGIN

   ...

   dept_rec1 := dept_rec2;

Second, you can assign a list of column values to a record by using the SELECT or FETCH statement, as the example below shows. Just make sure the column names appear in the same order as the fields in your record.

DECLARE

   TYPE DeptRecTyp IS RECORD(

      deptno  NUMBER(2),

      dname   CHAR(14),

      loc     CHAR(13));

   dept_rec  DeptRecTyp;

   ...

BEGIN

   SELECT deptno, dname, loc INTO dept_rec FROM dept

      WHERE deptno = 30;

   ...

END;

 Restrictions

Even if their fields match exactly, records of different types cannot be assigned to each other. Furthermore, a user-defined record and a %ROWTYPE record always belong to different types, as the following example shows:

DECLARE

   TYPE DeptRecTyp IS RECORD(

      deptno  NUMBER(2),

      dname   CHAR(14),

      loc     CHAR(13));

   dept_rec1  DeptRecTyp;

   dept_rec2  dept%ROWTYPE;

   ...

BEGIN

   ...

   dept_rec1 := dept_rec2;  -- illegal

You cannot assign a list of values to a record by using an assignment statement. So, the following syntax is illegal:

record_name := (value1, value2, value3, ...);  -- illegal

Also, records cannot be tested for equality or inequality. For instance, the following IF condition is illegal:

IF dept_rec1 = dept_rec2 THEN  -- illegal

   ...

END IF;

Nested Records

PL/SQL lets you declare and reference nested records. That is, a record can be the component of another record, as this example shows:

DECLARE

   TYPE TimeTyp IS RECORD(

      minute  SMALLINT,

      hour    SMALLINT);

   TYPE MeetingTyp IS RECORD(

      day      DATE,

      time     TimeTyp,     -- nested record

      place    CHAR(20),

      purpose  CHAR(50));

   TYPE PartyTyp IS RECORD(

      day   DATE,

      time  TimeTyp,        -- nested record

      loc   CHAR(15));

   meeting  MeetingTyp;

   seminar  MeetingTyp;

   party    PartyTyp;

   ...

BEGIN

   meeting.day := '26-JUN-91';

   meeting.time.minute := 45;

   meeting.time.hour := 10;

   ...

END;

The next example shows that you can assign one nested record to another if they belong to the same datatype:

seminar.time := meeting.time;

Such assignments are allowed even if the containing records belong to different datatypes, as the following example shows:

party.time := meeting.time;

Advantage of Records

The RECORD type lets you collect information about the attributes of an object. It is easy to manipulate the information because you can refer to the object as a whole. In the following example, you collect accounting figures from database tables named assets and liabilities, then use ratio analysis to compare the performance of two subsidiary companies:

DECLARE

   TYPE FiguresTyp IS RECORD(

      cash                   REAL,

      marketable_securities  REAL,

      accounts_receivable    REAL,

      inventories            REAL,

      accounts_payable       REAL,

      notes                  REAL,

      employment_costs       REAL,

      accrued_taxes          REAL,

      dividends_payable      REAL,

      short_term_debt        REAL);

   sub1_figs  FiguresTyp;

   sub2_figs  FiguresTyp;

   ...

   FUNCTION acid_test (figs FiguresTyp) RETURN REAL IS

      current_liabilities  REAL;

   BEGIN

      current_liabilities := figs.accounts_payable + figs.notes

         + figs.employment_costs + figs.accrued_taxes

         + figs.dividends_payable + figs.short_term_debt;

      RETURN (figs.cash + figs.marketable_securities

         + figs.accounts_receivable) / current_liabilities;

   END acid_test;

   ...

BEGIN

   SELECT cash, mkt_sec, accts_rec, ... INTO sub1_figs

      FROM assets, liabilities

      WHERE assets.sub = 1 AND liabilities.sub = 1;

   SELECT cash, mkt_sec, accts_rec, ... INTO sub2_figs

      FROM assets, liabilities

      WHERE assets.sub = 2 AND liabilities.sub = 2;

...

   IF acid_test(sub1_figs) > acid_test(sub2_figs) THEN ...

   ...

END;

Notice how easy it is to pass the collected figures to the function acid_test, which computes a financial ratio.


CHAPTER 3. CONTROL STRUCTURES

One ship drives east and another drives west

With the selfsame winds that blow.

'Tis the set of the sails and not the gales

Which tells us the way to go.

Ella Wheeler Wilcox

This chapter shows you how to structure the flow of control through a PL/SQL program. You learn how statements are connected by simple but powerful control structures that have a single entry and exit point. Collectively, these structures can handle any situation. And their proper use leads naturally to a well-structured program.

________________________________________

Overview

According to the structure theorem, any computer program can be written using the basic control structures shown in Figure 3 - 1. They can be combined in any way necessary to deal with a given problem.

The selection structure tests a condition, then executes one sequence of statements instead of another, depending on whether the condition is true or false. A condition is any expression that returns a Boolean value (TRUE, FALSE, or NULL). The iteration structure executes a sequence of statements repeatedly as long as a condition holds true. The sequence structure simply executes a sequence of statements in the order in which they occur.

Now, let us take a closer look at these structures.

________________________________________

Conditional Control: IF Statements

Often, it is necessary to take alternative actions depending on circumstances. The IF statement lets you execute a sequence of statements conditionally. That is, whether the sequence is executed or not depends on the value of a condition. There are three forms of IF statements: IF-THEN, IF-THEN-ELSE, and IF-THEN-ELSIF.

IF-THEN

The simplest form of IF statement associates a condition with a sequence of statements enclosed by the keywords THEN and END IF (not ENDIF), as follows:

IF condition THEN

   sequence_of_statements;

END IF;

The sequence of statements is executed only if the condition evaluates to TRUE. If the condition evaluates to FALSE or NULL, the IF statement does nothing. In either case, control passes to the next statement. An example follows:

IF sales > quota THEN

   compute_bonus(empid);

   UPDATE payroll SET pay = pay + bonus WHERE empno = emp_id;

END IF;

You might want to place brief IF statements on a single line, as in

IF x > y THEN high := x; END IF;

IF-THEN-ELSE

The second form of IF statement adds the keyword ELSE followed by an alternative sequence of statements, as follows:

IF condition THEN

   sequence_of_statements1;

ELSE

   sequence_of_statements2;

END IF;

The sequence of statements in the ELSE clause is executed only if the condition evaluates to FALSE or NULL. Thus, the ELSE clause ensures that a sequence of statements is executed. In the following example, the first or second UPDATE statement is executed when the condition is true or false, respectively:

IF trans_type = 'CR' THEN

   UPDATE accounts SET balance = balance + credit WHERE ...

ELSE

   UPDATE accounts SET balance = balance - debit WHERE ...

END IF;

The THEN and ELSE clauses can include IF statements. That is, IF statements can be nested, as the following example shows:

IF trans_type = 'CR' THEN

   UPDATE accounts SET balance = balance + credit WHERE ...

ELSE

   IF new_balance >= minimum_balance THEN

      UPDATE accounts SET balance = balance - debit WHERE ...

   ELSE

      RAISE insufficient_funds;

   END IF;

END IF;

IF-THEN-ELSIF

Sometimes you want to select an action from several mutually exclusive alternatives. The third form of IF statement uses the keyword ELSIF (not ELSEIF) to introduce additional conditions, as follows:

IF condition1 THEN

   sequence_of_statements1;

ELSIF condition2 THEN

   sequence_of_statements2;

ELSE

   sequence_of_statements3;

END IF;

If the first condition evaluates to FALSE or NULL, the ELSIF clause tests another condition. An IF statement can have any number of ELSIF clauses; the final ELSE clause is optional. Conditions are evaluated one by one from top to bottom. If any condition evaluates to TRUE, its associated sequence of statements is executed and control passes to the next statement. If all conditions evaluate to FALSE or NULL, the sequence in the ELSE clause is executed. Consider the following example:

IF sales > 50000 THEN

   bonus := 1500;

ELSIF sales > 35000 THEN

   bonus := 500;

ELSE

   bonus := 100;

END IF;

INSERT INTO payroll VALUES (emp_id, bonus, ...);

If the value of sales is more than 50000, the first and second conditions are true. Nevertheless, bonus is assigned the proper value of 1500 because the second condition is never tested. When the first condition evaluates to TRUE, its associated statement is executed and control passes to the INSERT statement.

Guidelines

Avoid clumsy IF statements like those in the following example:

DECLARE

   ...

   overdrawn  BOOLEAN;

BEGIN

   ...

   IF new_balance < minimum_balance THEN

      overdrawn := TRUE;

   ELSE

      overdrawn := FALSE;

   END IF;

   ...

   IF overdrawn = TRUE THEN

      RAISE insufficient_funds;

   END IF;

END;

This code disregards two useful facts. First, the value of a Boolean expression can be assigned directly to a Boolean variable. So, you can replace the first IF statement with a simple assignment, as follows:

overdrawn := new_balance < minimum_balance;

Second, a Boolean variable is itself either true or false.  So, you can simplify the condition in the second IF statement as follows:

IF overdrawn THEN ...

When possible, use the ELSIF clause instead of nested IF statements. That way, your code will be easier to read and understand. Compare the following IF statements:

IF condition1 THEN            |     IF condition1 THEN

   statement1;                |        statement1;

ELSE                          |     ELSIF condition2 THEN

   IF condition2 THEN         |        statement2;

      statement2;             |     ELSIF condition3 THEN

   ELSE                       |        statement3;

      IF condition3 THEN      |     END IF;

         statement3;          |

      END IF;                 |

   END IF;                    |

END IF;                       |

These statements are logically equivalent, but the first statement obscures the flow of logic, whereas the second statement reveals it.

________________________________________

Iterative Control: LOOP and EXIT Statements

LOOP statements let you execute a sequence of statements multiple times. There are three forms of LOOP statements: LOOP, WHILE-LOOP, and FOR-LOOP.

LOOP

The simplest form of LOOP statement is the basic (or infinite) loop, which encloses a sequence of statements between the keywords LOOP and END LOOP, as follows:

LOOP

   sequence_of_statements;

END LOOP;

With each iteration of the loop, the sequence of statements is executed, then control resumes at the top of the loop. If further processing is undesirable or impossible, you can use the EXIT statement to complete the loop. You can place one or more EXIT statements anywhere inside a loop, but nowhere outside a loop. There are two forms of EXIT statements: EXIT and EXIT-WHEN.

 EXIT

The EXIT statement forces a loop to complete unconditionally. When an EXIT statement is encountered, the loop completes immediately and control passes to the next statement. An example follows:

LOOP

   ...

   IF ... THEN

       ...

      EXIT;  -- exit loop immediately

   END IF;

END LOOP;

-- control resumes here

The next example shows that you cannot use the EXIT statement to complete a PL/SQL block:

BEGIN

   ...

   IF ... THEN

      ...

      EXIT;  -- illegal

   END IF;

END;

Remember, the EXIT statement must be placed inside a loop. To complete a PL/SQL block before the normal end of the block is reached, you can use the RETURN statement (see Chapter 9).

 EXIT-WHEN

The EXIT-WHEN statement allows a loop to complete conditionally. When the EXIT statement is encountered, the condition in the WHEN clause is evaluated. If the condition evaluates to TRUE, the loop completes and control passes to the next statement after the loop. An example follows:

LOOP

   FETCH c1 INTO ...

   EXIT WHEN c1%NOTFOUND;  -- exit loop if condition is true

   ...

END LOOP;

CLOSE c1;

Until the condition evaluates to TRUE, the loop cannot complete. So, statements within the loop must change the value of the condition. In the last example, if the FETCH statement returns a row, the condition evaluates to FALSE. When the FETCH statement fails to return a row, the condition evaluates to TRUE, the loop completes, and control passes to the CLOSE statement.

The EXIT-WHEN statement replaces a simple IF statement. For example, compare the following statements:

IF count > 100 THEN     |     EXIT WHEN count > 100;

   EXIT;                |

END IF;                 |

These statements are logically equivalent, but the EXIT-WHEN statement is easier to read and understand.

 Loop Labels

Like PL/SQL blocks, loops can be labeled. The label, an undeclared identifier enclosed by double angle brackets, must appear at the beginning of the LOOP statement, as follows:

<<label_name>>

LOOP

   sequence_of_statements;

END LOOP;

Optionally, the label name can also appear at the end of the LOOP statement, as the following example shows:

<<my_loop>>

LOOP

   ...

END LOOP my_loop;

When you nest labeled loops, you can use ending label names to improve readability.

With either form of EXIT statement, you can complete not only the current loop, but any enclosing loop. Simply label the enclosing loop that you want to complete. Then, use the label in an EXIT statement, as follows:

<<outer>>

LOOP

   ...

   LOOP

      ...

      EXIT outer WHEN ...  -- exit both loops

   END LOOP;

   ...

END LOOP outer;

Every enclosing loop up to and including the labeled loop is exited.

WHILE-LOOP

The WHILE-LOOP statement associates a condition with a sequence of statements enclosed by the keywords LOOP and END LOOP, as follows:

WHILE condition LOOP

   sequence_of_statements;

END LOOP;

Before each iteration of the loop, the condition is evaluated. If the condition evaluates to TRUE, the sequence of statements is executed, then control resumes at the top of the loop. If the condition evaluates to FALSE or NULL, the loop is bypassed and control passes to the next statement. An example follows:

WHILE total <= 25000 LOOP

   ...

   SELECT sal INTO salary FROM emp WHERE ...

   total := total + salary;

END LOOP;

The number of iterations depends on the condition and is unknown until the loop completes. Since the condition is tested at the top of the loop, the sequence might execute zero times. In the last example, if the initial value of total is greater than 25000, the condition evaluates to FALSE and the loop is bypassed.

Some languages have a LOOP UNTIL or REPEAT UNTIL structure, which tests the condition at the bottom of the loop instead of at the top. Therefore, the sequence of statements is executed at least once. PL/SQL has no such structure, but you can easily build one as follows:

LOOP

   sequence_of_statements;

   EXIT WHEN boolean_expression;

END LOOP;

To ensure that a WHILE loop executes at least once, use an initialized Boolean variable in the condition, as follows:

done := FALSE;

WHILE NOT done LOOP

   sequence_of_statements;

   done := boolean_expression;

END LOOP;

A statement inside the loop must assign a new value to the Boolean variable. Otherwise, you have an infinite loop. For example, the following LOOP statements are logically equivalent:

WHILE TRUE LOOP     |     LOOP

   ...              |         ...

END LOOP;           |     END LOOP;

FOR-LOOP

Whereas the number of iterations through a WHILE loop is unknown until the loop completes, the number of iterations through a FOR loop is known before the loop is entered. FOR loops iterate over a specified range of integers. (Cursor FOR loops, which iterate over the active set of a cursor, are discussed in Chapter .) The range is part of an iteration scheme, which is enclosed by the keywords FOR and LOOP. The syntax follows:

FOR counter IN [REVERSE] lower_bound..higher_bound LOOP

   sequence_of_statements;

END LOOP;

The range is evaluated when the FOR loop is first entered and is never reevaluated. As the next example shows, the sequence of statements is executed once for each integer in the range. After each iteration, the loop counter is incremented.

FOR i IN 1..3 LOOP  -- assign the values 1,2,3 to i

   sequence_of_statements;  -- executes three times

END LOOP;

The following example shows that if the lower bound equals the higher bound, the sequence of statements is executed once:

FOR i IN 3..3 LOOP  -- assign the value 3 to i

   sequence_of_statements;  -- executes one time

END LOOP;

By default, iteration proceeds upward from the lower bound to the higher bound. However, if you use the keyword REVERSE, iteration proceeds downward from the higher bound to the lower bound, as the example below shows. After each iteration, the loop counter is decremented.

FOR i IN REVERSE 1..3 LOOP  -- assign the values 3,2,1 to i

   sequence_of_statements;  -- executes three times

END LOOP;

Nevertheless, you write the range bounds in ascending (not descending) order.

Inside a FOR loop, the loop counter can be referenced like a constant. So, the loop counter can appear in expressions but cannot be assigned values, as the following example shows:

FOR ctr IN 1..10 LOOP

   ...

   IF NOT finished THEN

      INSERT INTO ... VALUES (ctr, ...);  -- legal

      factor := ctr * 2;  -- legal

      ...

   ELSE

      ctr := 10;  -- illegal

   END IF;

END LOOP;

 Iteration Schemes

The bounds of a loop range can be literals, variables, or expressions but must evaluate to integers. For example, the following iteration schemes are legal:

j IN -5..5

k IN REVERSE first..last

step IN 0..TRUNC(high/low) * 2

code IN ASCII('A')..ASCII('J')

As you can see, the lower bound need not be 1. However, the loop counter increment (or decrement) must be 1. Some languages provide a STEP clause, which lets you specify a different increment. An example written in BASIC follows:

FOR J = 5 TO 15 STEP 5  :REM assign values 5,10,15 to J

   sequence_of_statements  -- J has values 5,10,15

NEXT J

PL/SQL has no such structure, but you can easily build one. Consider the following example:

FOR j IN 5..15 LOOP  -- assign values 5,6,7,... to j

   IF MOD(j, 5) = 0 THEN  --  pass multiples of 5

      sequence_of_statements;  -- j has values 5,10,15

   END IF;

END LOOP;

This loop is logically equivalent to the previous BASIC loop. Within the sequence of statements, the loop counter has only the values 5, 10, and 15.

You might prefer the less elegant but more efficient method shown in the example below. Within the sequence of statements, each reference to the loop counter is multiplied by the increment.

FOR j IN 1..3 LOOP  -- assign values 1,2,3 to j

   sequence_of_statements;  -- each j becomes j*5

END LOOP;

 Dynamic Ranges

PL/SQL lets you determine the loop range dynamically at run time, as the following example shows:

SELECT COUNT(empno) INTO emp_count FROM emp;

FOR i IN 1..emp_count LOOP

   ...

END LOOP;

The value of emp_count is unknown at compile time; the SELECT statement returns the value at run time.

What happens if the lower bound of a loop range evaluates to a larger integer than the upper bound? As the following example shows, the sequence of statements within the loop is not executed and control passes to the next statement:

-- limit becomes 1

FOR i IN 2..limit LOOP

   sequence_of_statements;  -- executes zero times

END LOOP;

-- control passes here

 Scope Rules

The loop counter is defined only within the loop. You cannot reference it outside the loop. After the loop is exited, the loop counter is undefined, as the following example shows:

FOR ctr IN 1..10 LOOP

   ...

END LOOP;

sum := ctr - 1;  -- illegal

You need not explicitly declare the loop counter because it is implicitly declared as a local variable of type INTEGER. The next example shows that the local declaration hides any global declaration:

DECLARE

   ctr  INTEGER;

BEGIN

   ...

   FOR ctr IN 1..25 LOOP

      ...

      IF ctr > 10 THEN ...  -- refers to loop counter

   END LOOP;

END;

To reference the global variable in this example, you must use a label and dot notation, as follows:

<<main>>

DECLARE

   ctr  INTEGER;

   ...

BEGIN

   ...

   FOR ctr IN 1..25 LOOP

      ...

      IF main.ctr > 10 THEN ...  -- refers to global variable

   END LOOP;

END main;

The same scope rules apply to nested FOR loops. Consider the example below. Both loop counters have the same name. So, to reference the outer loop counter from the inner loop, you must use a label and dot notation, as follows:

<<outer>>

FOR step IN 1..25 LOOP

   FOR step IN 1..10 LOOP

      ...

      IF outer.step > 15 THEN ...

   END LOOP;

END LOOP outer;

 Using the EXIT Statement

The EXIT statement allows a FOR loop to complete prematurely. For example, the following loop normally executes ten times, but as soon as the FETCH fails to return a row, the loop completes no matter how many times it has executed.

FOR j IN 1..10 LOOP

   FETCH c1 INTO emp_rec;

   EXIT WHEN c1%NOTFOUND;

   ...

END LOOP;

Suppose you must exit from a nested FOR loop prematurely. You can complete not only the current loop, but any enclosing loop. Simply label the enclosing loop that you want to complete. Then, use the label in an EXIT statement to specify which FOR loop to exit, as follows:

<<outer>>

FOR i IN 1..5 LOOP

   ...

   FOR j IN 1..10 LOOP

      FETCH c1 INTO emp_rec;

      EXIT outer WHEN c1%NOTFOUND;  -- exit both FOR loops

      ...

   END LOOP;

END LOOP outer;

-- control passes here

________________________________________

Sequential Control: GOTO and NULL Statements

Unlike the IF and LOOP statements, the GOTO and NULL statements are not crucial to PL/SQL programming. The structure of PL/SQL is such that the GOTO statement is seldom needed. Occasionally, it can simplify logic enough to warrant its use. The NULL statement can make the meaning and action of conditional statements clear and so improve readability.

GOTO Statement

The GOTO statement branches to a label unconditionally. The label must be unique within its scope and must precede an executable statement or a PL/SQL block. When executed, the GOTO statement transfers control to the labeled statement or block. In the following example, you go to an executable statement farther down in a sequence of statements:

BEGIN

   ...

   GOTO insert_row;

   ...

   <<insert_row>>

   INSERT INTO emp VALUES ...

END;

In the next example, you go to a PL/SQL block farther up in a sequence of statements:

BEGIN

   ...

   <<update_row>>

   BEGIN

      UPDATE emp SET ...

      ...

   END;

   ...

   GOTO update_row;

   ...

END;

The label <<end_loop>> in the following example is illegal because it does not precede an executable statement:

DECLARE

   done  BOOLEAN;

BEGIN

   ...

   FOR i IN 1..50 LOOP

      IF done THEN

         GOTO end_loop;

      END IF;

      ...

   <<end_loop>>  -- illegal

   END LOOP;  -- not an executable statement

END;

To debug the last example, simply add the NULL statement, as follows:

DECLARE

   done  BOOLEAN;

BEGIN

   ...

   FOR i IN 1..50 LOOP

      IF done THEN

         GOTO end_loop;

      END IF;

      ...

   <<end_loop>>

   NULL;  -- an executable statement

   END LOOP;

END;

As the following example shows, a GOTO statement can branch to an enclosing block from the current block:

DECLARE

   my_ename  CHAR(10);

BEGIN

   ...

   <<get_name>>

   SELECT ename INTO my_ename FROM emp WHERE ...

   ...

   BEGIN

      ...

      GOTO get_name;  -- branch to enclosing block

   END;

END;

The GOTO statement branches to the first enclosing block in which the referenced label appears.

 Restrictions

Some possible destinations of a GOTO statement are illegal. Specifically, a GOTO statement cannot branch into an IF statement, LOOP statement, or sub-block. For example, the following GOTO statement is illegal:

BEGIN

   ...

   GOTO update_row;  -- illegal branch into IF statement

   ...

   IF valid THEN

      ...

      <<update_row>>

      UPDATE emp SET ...

   END IF;

END;

Also, a GOTO statement cannot branch from one IF statement clause to another, as the following example shows:

BEGIN

   ...

   IF valid THEN

      ...

      GOTO update_row;  -- illegal branch into ELSE clause

   ELSE

      ...

      <<update_row>>

      UPDATE emp SET ...

   END IF;

END;

The next example shows that a GOTO statement cannot branch from an enclosing block into a sub-block:

BEGIN

   ...

   IF status = 'OBSOLETE' THEN

      GOTO delete_part;  -- illegal branch into sub-block

   END IF;

   ...

   BEGIN

      ...

      <<delete_part>>

      DELETE FROM parts WHERE ...

   END;

END;

Also, a GOTO statement cannot branch out of a subprogram, as the following example shows:

DECLARE

    ...

    PROCEDURE compute_bonus (emp_id NUMBER) IS

    BEGIN

       ...

       GOTO update_row;  -- illegal branch out of subprogram

    END;

BEGIN

   ...

   <<update_row>>

   UPDATE emp SET ...

END;

Finally, a GOTO statement cannot branch from an exception handler into the current block. For example, the following GOTO statement is illegal:

DECLARE

   ...

   pe_ratio  REAL;

BEGIN

   ...

   SELECT price / NVL(earnings, 0) INTO pe_ratio FROM ...

   <<insert_row>>

   INSERT INTO stats VALUES (pe_ratio, ...);

EXCEPTION

   WHEN ZERO_DIVIDE THEN

      pe_ratio := 0;

      GOTO insert_row;  -- illegal branch into current block

   ...

END;

However, a GOTO statement can branch from an exception handler into an enclosing block.

 Guidelines

Overuse of GOTO statements can result in complex, unstructured code that is hard to understand and maintain. So, use GOTO statements sparingly. For example, to branch from a deeply nested structure to an error-handling routine, raise an exception rather than use a GOTO statement.

NULL Statement

The NULL statement explicitly specifies inaction; it does nothing other than pass control to the next statement. It can, however, improve readability. In a construct allowing alternative actions, the NULL statement serves as a placeholder. It tells readers that the associated alternative has not been overlooked, but that indeed no action is necessary. In the following example, the NULL statement shows that no action is taken for unnamed exceptions:

...

EXCEPTION

   WHEN ZERO_DIVIDE THEN

      ROLLBACK;

   WHEN VALUE_ERROR THEN

      INSERT INTO errors VALUES ...

      COMMIT;

   WHEN OTHERS THEN

      NULL;

END;

Each clause in an IF statement must contain at least one executable statement. The NULL statement meets this requirement. So, you can use the NULL statement in clauses that correspond to circumstances in which no action is taken. In the following example, the NULL statement emphasizes that only top-rated employees receive bonuses:

IF rating > 90 THEN

   compute_bonus(emp_id);

ELSE

   NULL;

END IF;

Also, the NULL statement is a handy way to create stubs when designing applications from the top down. Stubs are dummy subprograms that allow you to defer the definition of procedures and functions until you test and debug the main program. In the following example, the NULL statement meets the requirement that at least one statement must appear in the executable part of a subprogram:

PROCEDURE debit_account (acct_id INTEGER, amount REAL) IS

BEGIN

   NULL;

END debit_account;


CHAPTER 4. INTERACTION WITH ORACLE

Knowledge is of two kinds. We know a subject ourselves, or we know where we can find information upon it.

Samuel Johnson

This chapter helps you harness the power of ORACLE. You learn how PL/SQL supports the SQL commands, functions, and operators that allow your program to manipulate ORACLE data. You also learn how to access remote databases, manage cursors, use optimizer hints, process transactions, and safeguard the consistency of your database.

________________________________________

SQL Support

By extending SQL, PL/SQL offers a unique combination of power and ease of use. You can manipulate ORACLE data flexibly and safely because PL/SQL supports all SQL data manipulation commands (except EXPLAIN PLAN), transaction control commands, functions, pseudocolumns, and operators. However, PL/SQL does not support data definition commands such as CREATE, session control commands such as SET ROLE, or the system control command ALTER SYSTEM.

Data Manipulation

To manipulate ORACLE data, you use the INSERT, UPDATE, DELETE, SELECT, and LOCK TABLE commands. INSERT adds new rows of data to database tables; UPDATE modifies rows; DELETE removes unwanted rows; SELECT retrieves rows that meet your search criteria; and LOCK TABLE temporarily limits access to a table.

Transaction Control

ORACLE is transaction oriented; that is, ORACLE uses transactions to ensure data integrity. A transaction is a series of SQL data manipulation statements that does a logical unit of work. For example, two UPDATE statements might credit one bank account and debit another. Simultaneously, ORACLE makes permanent or undoes all database changes made by a transaction. If your program fails in the middle of a transaction, ORACLE detects the error and rolls back the transaction. Hence, the database is restored to its former state automatically.

You use the COMMIT, ROLLBACK, SAVEPOINT, and SET TRANSACTION commands to control transactions. COMMIT makes permanent any database changes made during the current transaction. Until you commit your changes, other users cannot see them. ROLLBACK ends the current transaction and undoes any changes made since the transaction began. SAVEPOINT marks the current point in the processing of a transaction. Used with ROLLBACK, SAVEPOINT undoes part of a transaction. SET TRANSACTION establishes a read-only transaction. For more information, see the section "Transaction Processing" later in this chapter.

SQL Functions

PL/SQL lets you use all the SQL functions including the following group functions, which summarize entire columns of ORACLE data:

•	AVG

•	COUNT

•	MAX

•	MIN

•	STDDEV

•	SUM

•	VARIANCE

Two additional group functions, GLB and LUB, are available only with Trusted ORACLE. GLB and LUB return the greatest lower bound and least upper bound of an operating system label, respectively. For more information, see the Trusted ORACLE7 Server Administrator's Guide.

You can use the group functions in SQL statements, but not in procedural statements. Group functions operate on entire columns unless you use the SELECT GROUP BY statement to sort returned rows into subgroups. If you omit the GROUP BY clause, the group function treats all returned rows as a single group.

You call a group function using the syntax

function_name([ALL | DISTINCT] expr)

where expr is an expression that refers to one or more database columns. If you specify the ALL option (the default), the group function considers all column values including duplicates. For example, the following statement returns the sample standard deviation (s) of all values in the comm column:

SELECT STDDEV(comm) INTO comm_sigma FROM emp;

If you specify the DISTINCT option, the group function considers only distinct values. For example, the following statement returns the number of different job titles in the emp table:

SELECT COUNT(DISTINCT job) INTO job_count FROM emp;

The COUNT function lets you specify the asterisk (*) option, which returns the number of rows in a table. For example, the following statement returns the number of employees in the emp table:

SELECT COUNT(*) INTO emp_count FROM emp;

Except for COUNT(*), all group functions ignore nulls.

SQL Pseudocolumns

PL/SQL recognizes the following SQL pseudocolumns, which return specific data items:

•	CURRVAL

•	LEVEL

•	NEXTVAL

•	ROWID

•	ROWNUM

For example, NEXTVAL returns the next value in a database sequence. They are called pseudocolumns because they are not actual columns in a table but behave like columns. For instance, you can reference pseudocolumns in SQL statements. Furthermore, you can select values from a pseudocolumn. However, you cannot insert values into, update values in, or delete values from a pseudocolumn.

You can use pseudocolumns in SQL statements, but not in procedural statements. In the following example, you use the database sequence empno_seq and the pseudocolumn NEXTVAL to insert a new employee number into the emp table:

INSERT INTO emp VALUES (empno_seq.NEXTVAL, new_ename, ...);

Sometimes, it is convenient to select pseudocolumn values from a dummy table, as follows:

DECLARE

   new_empno  NUMBER(4);

   new_ename  CHAR(10);

   ...

BEGIN

   ...

   SELECT empno_seq.NEXTVAL INTO new_empno FROM dual;

   INSERT INTO emp VALUES (new_empno, new_ename, ...);

END;

Brief descriptions of the pseudocolumns follow. For more information, see the ORACLE7 Server SQL Language Reference Manual.

 CURRVAL and NEXTVAL

A sequence is a database object that generates sequential numbers. When you create a sequence, you can specify its initial value and an increment.

CURRVAL returns the current value in a specified sequence. Before you can reference CURRVAL in a session, you must use NEXTVAL to generate a number. A reference to NEXTVAL stores the current sequence number in CURRVAL. NEXTVAL increments the sequence and returns the next value. To obtain the current or next value in a sequence, you must use dot notation as follows:

sequence_name.CURRVAL

sequence_name.NEXTVAL

After creating a sequence, you can use it to generate unique sequence numbers for transaction processing. However, you can use CURRVAL and NEXTVAL only in a SELECT list, the VALUES clause, and the SET clause. In the following example, you use a sequence to insert the same employee number into two tables:

INSERT INTO emp VALUES (empno_seq.NEXTVAL, my_ename, ...);

INSERT INTO sals VALUES (empno_seq.CURRVAL, my_sal, ...);

If a transaction generates a sequence number, the sequence is incremented immediately whether you commit or roll back the transaction.

 LEVEL

You use LEVEL with the SELECT CONNECT BY statement to organize rows from a database table into a tree structure. LEVEL returns the level number of a node in a tree structure. The root is level 1, children of the root are level 2, grandchildren are level 3, and so on.

You specify the direction in which the query walks the tree (down from the root or up from the branches) with the PRIOR operator. In the START WITH clause, you specify a condition that identifies the root of the tree.

 ROWID

ROWID returns the rowid (binary address) of a row in a database table. Recall that PL/SQL provides a datatype also named ROWID. You can use variables of type ROWID to store rowids in a readable format. For example, you might declare a variable named row_id for that purpose, as follows:

DECLARE

   row_id  ROWID;

   ...

When you select or fetch a rowid into a ROWID variable, you can use the function ROWIDTOCHAR, which converts the binary value to an 18-byte character string. Then, you can compare the ROWID variable to the ROWID pseudocolumn in the WHERE clause of an UPDATE or DELETE statement to identify the latest row fetched from a cursor. Furthermore, you can use the %ROWTYPE attribute with cursors that reference the ROWID pseudocolumn. For examples, see the section "Fetching Across Commits" later in this chapter.

 ROWNUM

ROWNUM returns a number indicating the order in which a row was selected from a table. The first row selected has a ROWNUM of 1, the second row has a ROWNUM of 2, and so on. If a SELECT statement includes an ORDER BY clause, ROWNUMs are assigned to the retrieved rows before the sort is done.

You can use ROWNUM in an UPDATE statement to assign unique values to each row in a table. Also, you can use ROWNUM in the WHERE clause of a SELECT statement to limit the number of rows retrieved, as follows:

DECLARE

   CURSOR c1 IS SELECT empno, sal FROM emp

      WHERE sal > 2000 AND ROWNUM < 10;  -- returns 10 rows

   ...

The value of ROWNUM increases only when a row is retrieved, so the only meaningful use of ROWNUM in a WHERE clause is

... WHERE ROWNUM < constant;

For example, the following condition cannot be met because the first nine rows are never retrieved:

... WHERE ROWNUM = 10;

ROWLABEL Column

PL/SQL also recognizes the special column ROWLABEL, which Trusted ORACLE creates for every database table. Like other columns, ROWLABEL can be referenced in SQL statements. However, with standard ORACLE, ROWLABEL returns a null. With Trusted ORACLE, ROWLABEL returns the operating system label for a row.

A common use of ROWLABEL is to filter query results. For example, the following statement counts only those rows with a security level higher than "unclassified":

SELECT COUNT(*) INTO head_count FROM emp

   WHERE ROWLABEL > 'UNCLASSIFIED';

SQL Operators

PL/SQL lets you use all the SQL comparison, set, and row operators in SQL statements. This section briefly describes some of these operators. For more information, refer to the ORACLE7 Server SQL Language Reference Manual.

 Comparison Operators

Typically, you use comparison operators in the WHERE clause of a data manipulation statement to form predicates, which compare one expression to another and always evaluate to TRUE, FALSE, or NULL. You can use all the comparison operators listed below to form predicates. Moreover, you can combine predicates using the logical operators AND, OR, and NOT.

ALL	Compares a value to each value in a list or returned by a subquery and evaluates to TRUE if all of the individual comparisons yield a TRUE result.

ANY, SOME	Compares a value to each value in a list or returned by a subquery and evaluates to TRUE if any of the individual comparisons yields a TRUE result.

BETWEEN	Tests whether a value lies in a specified range.

EXISTS	Returns TRUE if a subquery returns at least one row.

IN	Tests for set membership.

IS NULL	Tests for nulls.

LIKE	Tests whether a character string matches a specified pattern, which can include wildcards.

 Set Operators

Set operators combine the results of two queries into one result. You can use all the set operators, including INTERSECT, MINUS, UNION, and UNION ALL.

INTERSECT returns all distinct rows selected by both queries. MINUS returns all distinct rows selected by the first query but not by the second. UNION returns all distinct rows selected by either query. UNION ALL returns all rows selected by either query, including all duplicates.

 Row Operators

Row operators return or reference particular rows. You can use all the row operators, including ALL, DISTINCT, and PRIOR.

ALL retains duplicate rows in the result of a query or in an aggregate expression. DISTINCT eliminates duplicate rows from the result of a query or from an aggregate expression. PRIOR refers to the parent row of the current row returned by a tree-structured query. You must use this operator in the CONNECT BY clause of such a query to define the parent-child relationship.

Optimizer Hints

For every SQL statement, the ORACLE optimizer generates an execution plan, which is a series of steps that ORACLE takes to execute the statement. In some cases, you can suggest to ORACLE the way to optimize a SQL statement. These suggestions, called hints, let you influence decisions made by the optimizer.

Hints are not directives; they merely help the optimizer do its job. Some hints limit the scope of information used to optimize a SQL statement, while others suggest overall strategies.

You can use hints to specify the

•	optimization approach for a SQL statement

•	access path for each referenced table

•	join order for a join

•	method used to join tables

Hence, hints fall into the following four categories:

•	Optimization Approach

•	Access Path

•	Join Order

•	Join Operation

For example, the two Optimization Approach hints, COST and NOCOST, invoke the cost-based optimizer and the rule-based optimizer, respectively.

You give hints to the optimizer by placing them in a comment immediately after the verb in a SELECT, UPDATE, or DELETE statement. For instance, the optimizer uses the cost-based approach for the following statement:

SELECT /*+ COST */ ename, job, sal INTO ...

For more information about optimizer hints, see the ORACLE7 Server Application Developer's Guide.

________________________________________

National Language Support

Although the widely-used 7- or 8-bit ASCII and EBCDIC character sets are adequate to represent the Roman alphabet, some Asian languages, such as Japanese, contain thousands of characters. These languages require 16 bits (two bytes) to represent each character. How does ORACLE deal with such dissimilar languages?

ORACLE provides National Language Support (NLS), which lets you process single-byte and multibyte character data and convert between character sets. It also lets your applications run in different language environments. With NLS, number and date formats adapt automatically to the language conventions specified for a user session. Thus, NLS allows users around the world to interact with ORACLE in their native languages.

You control the operation of language-dependent features by specifying various NLS parameters. Default values for these parameters can be set in the ORACLE initialization file. The following table shows what each NLS parameter specifies.

NLS Parameter	Specifies

NLS_LANGUAGE	language-dependent conven

tions

NLS_TERRITORY	territory-dependent conven

tions

NLS_DATE_FORMAT	date format

NLS_DATE_LANGUAGE	language for day and month

names

NLS_NUMERIC_CHAR	decimal character and group

ACTERS	separator

NLS_CURRENCY	local currency symbol

NLS_ISO_CURRENCY	ISO currency symbol

NLS_SORT	sort sequence

The main parameters are NLS_LANGUAGE and NLS_TERRITORY. NLS_LANGUAGE specifies the default values for language-dependent features, which include

•	language for Server messages

•	language for day and month names

•	sort sequence

NLS_LANGUAGE specifies the default values for territory-dependent features, which include

•	date format

•	decimal character

•	group separator

•	local currency symbol

•	ISO currency symbol

You can control the operation of language-dependent NLS features for a user session by specifying the parameter NLS_LANG as follows:

NLS_LANG = <language>_<territory>.<character set>

where language specifies the value of NLS_LANGUAGE for the user session, territory specifies the value of NLS_TERRITORY, and character set specifies the encoding scheme used for the terminal. An encoding scheme (usually called a character set or code page) is a range of numeric codes that corresponds to the set of characters a terminal can display. It also includes codes that control communication with the terminal.

You define NLS_LANG as an environment variable (or the equivalent on your system). For example, on UNIX using the C shell, you might define NLS_LANG as follows:

setenv NLS_LANG French_France.WE8ISO8859P1

PL/SQL fully supports all the NLS features that allow your applications to process multilingual data stored in an ORACLE database. For example, you can declare foreign-language character variables and pass them to string functions such as INSTRB, LENGTHB, and SUBSTRB. These functions have the same syntax as the INSTR, LENGTH, and SUBSTR functions, respectively, but operate on a per-byte basis rather than a per-character basis.

You can use the functions NLS_INITCAP, NLS_LOWER, and NLS_UPPER to handle special instances of case conversion. And, you can use the function NLSSORT to specify WHERE-clause comparisons based on linguistic rather than binary ordering. You can even pass NLS parameters to the TO_CHAR, TO_DATE, and TO_NUMBER functions. For more information about NLS, see the ORACLE7 Server Application Developer's Guide.

________________________________________

Remote Access

PL/SQL lets you access remote databases. In the example below, you query a remote database table in the newyork database via SQL*Net. The query is submitted to your local ORACLE Server, but is "forwarded" to the remote database for execution.

BEGIN

   SELECT ename, job INTO my_ename, my_job

      FROM emp@newyork

      WHERE empno = my_empno;

   ...

For more information about remote database access, see the ORACLE7 Server Application Developer's Guide.

You can use the %TYPE attribute to provide the datatype of a column in a remote database table. Likewise, you can use the %ROWTYPE attribute to declare a record that represents a row in a remote table. Some examples follow:

DECLARE

   emp_id    emp.empno@newyork%TYPE;

   dept_rec  dept@newyork%ROWTYPE;

   ...

You can even call stand-alone and packaged subprograms stored in a remote ORACLE database. For more information, see the section "Remote Access" in Chapter 6.

Location Transparency

To provide location transparency for remote database objects such as tables and views, you can create synonyms, as the following example shows:

CREATE SYNONYM emp2 FOR emp@newyork;

Then, as the next example shows, you can reference a remote object using its synonym:

BEGIN

   SELECT ename, job INTO my_ename, my_job

      FROM emp2  -- synonym for emp@newyork

      WHERE empno = my_empno;

   ...

Because they are database objects, you can also create synonyms for packages and stand-alone subprograms. However, you cannot create synonyms for objects declared within packages or subprograms. For example, you cannot create synonyms for packaged procedures.

Global Names

A distributed database is a single logical database comprising multiple physical databases at different nodes. In a distributed database system, each database is uniquely identified by a two-part global name. The first part is a 8-character database name such as sales; the second part is a network domain name. Figure 4 - 1 shows a fictional network domain that follows Internet conventions. Internet is a worldwide system of computer networks used by companies and schools to exchange information.

To form network domain names, you use dot notation and follow a path through the tree structure from leaf to root. The domain name tells you the name or location of a network host and the type of organization it is. In the following example, the trailing domain com tells you that Primus is a company or other commercial institution:

sales.mexico.americas.primus.com

Every database object is uniquely identified by its global object name. In the following example, you query a remote emp table:

BEGIN

   SELECT ename, job INTO my_ename, my_job

      FROM emp@sales.france.europe.primus.com

      WHERE empno = my_empno;

   ...

________________________________________

Cursor Management

Recall from Chapter 1 that PL/SQL uses two types of cursors: implicit and explicit. PL/SQL declares a cursor implicitly for all SQL data manipulation statements, including queries that return only one row. However, for queries that return more than one row, you must declare an explicit cursor or use a cursor FOR loop.

Explicit Cursors

The set of rows returned by a query can consist of zero, one, or multiple rows, depending on how many rows meet your search criteria. When a query returns multiple rows, you can explicitly define a cursor to process the rows.

You define a cursor in the declarative part of a PL/SQL block, subprogram, or package by naming it and specifying a query. Then, you use three commands to control the cursor: OPEN, FETCH, and CLOSE.

First, you initialize the cursor with the OPEN statement, which identifies the active set. Then, you use the FETCH statement to retrieve the first row. You can execute FETCH repeatedly until all rows have been retrieved. When the last row has been processed, you release the cursor with the CLOSE statement.

You can process several queries in parallel by declaring and opening multiple cursors. Now, let us take a closer look at these steps.

 Declaring a Cursor

Forward references are not allowed in PL/SQL. So, you must declare a cursor before referencing it in other statements. When you declare a cursor, you name it and associate it with a specific query. In the following example, you declare a cursor named c1:

DECLARE

   CURSOR c1 IS SELECT ename, deptno FROM emp

      WHERE sal > 2000;

   ...

BEGIN

   ...

The cursor name is an undeclared identifier, not a PL/SQL variable; it is used only to reference the query. You cannot assign values to a cursor name or use it in an expression. However, cursors and variables follow the same scope rules.

Parameterized Cursors

 Cursors can take parameters, as the example below shows. A cursor parameter can appear in a query wherever a constant can appear.

CURSOR c1 (median IN NUMBER) IS

   SELECT job, ename FROM emp WHERE sal > median;

To declare formal cursor parameters, you use the syntax

CURSOR name [ (parameter [, parameter, ...]) ] IS

   SELECT ...

where parameter stands for the following syntax:

variable_name [IN] datatype [{:= | DEFAULT} value]

The formal parameters of a cursor must be IN parameters. For a discussion of parameter modes, see the section "Parameter Modes" in Chapter 6.

As the example below shows, you can initialize cursor parameters to default values. That way, you can pass different numbers of actual parameters to a cursor, accepting or overriding the default values as you please. Moreover, you can add new formal parameters without having to change every reference to the cursor.

DECLARE

   CURSOR c1(

      low  INTEGER DEFAULT 0,

      high INTEGER DEFAULT 99) IS SELECT ...

   ...

The scope of cursor parameters is local to the cursor, meaning that they can be referenced only within the query used in the cursor declaration. The values of cursor parameters are used by the associated query when the cursor is OPENed.

 Opening a Cursor

OPENing the cursor executes the query and identifies the active set, which consists of all rows that meet the query search criteria. For cursors declared using the FOR UPDATE clause, the OPEN statement also locks those rows. An example of the OPEN statement follows:

OPEN c1;

Rows in the active set are not retrieved when the OPEN statement is executed. Rather, the FETCH statement retrieves the rows.

Passing Parameters

You can pass parameters to a cursor. For example, given the cursor declaration

CURSOR c1(my_ename CHAR, my_comm NUMBER) IS SELECT ...

any of the following statements opens the cursor:

OPEN c1('ATTLEY', 300);

OPEN c1(employee_name, 150);

OPEN c1('THURSTON', my_comm);

In the last example, the variable referenced in the OPEN statement has the same name as the parameter in the cursor declaration. When my_comm is used in the cursor declaration, it refers to the formal parameter my_comm. When it is used outside the declaration, it refers to the PL/SQL variable my_comm. For clarity, use unique identifiers.

Unless you want to accept default values, each formal parameter in the cursor declaration must have a corresponding actual parameter in the OPEN statement. Formal parameters declared with a default value need not have a corresponding actual parameter. They can simply assume their default values when the OPEN statement is executed. Remember, the formal parameters of a cursor must be IN parameters. Therefore, they cannot return values to actual parameters.

You can associate the actual parameters in an OPEN statement with the formal parameters in a cursor declaration using positional or named notation. (Refer to the section "Positional and Named Notation" in Chapter 6.) Each actual parameter must belong to a datatype compatible with the datatype of its corresponding formal parameter.

 Fetching with a Cursor

The FETCH statement retrieves the rows in the active set one at a time. Each time FETCH is executed, the cursor advances to the next row in the active set. An example of the FETCH statement follows:

FETCH c1 INTO my_empno, my_ename, my_deptno;

For each column value returned by the query associated with the cursor, there must be a corresponding variable in the INTO list. Also, their datatypes must be compatible. Typically, you use FETCH as follows:

...

OPEN c1;

LOOP

   FETCH c1 INTO my_record;

   EXIT WHEN c1%NOTFOUND;

   -- process retrieved data

END LOOP;

Any variables in the WHERE clause of the query associated with the cursor are evaluated only when the cursor is OPENed. As the following example shows, the query can reference PL/SQL variables within its scope:

DECLARE

   my_sal  emp.sal%TYPE;

   my_job  emp.job%TYPE;

   factor  INTEGER := 2;

   CURSOR c1 IS

      SELECT factor*sal FROM emp WHERE job = my_job;

BEGIN

   ...

   OPEN c1;  -- here factor equals 2

   LOOP

      FETCH c1 INTO my_sal;

      EXIT WHEN c1%NOTFOUND;

      ...

      factor := factor + 1;  -- does not affect FETCH

   END LOOP;

END;

In this example, each retrieved salary is multiplied by 2, even though factor is incremented after each FETCH. To change the active set or the values of variables in the query, you must CLOSE and reOPEN the cursor with the input variables set to their new values.

However, you can use a different INTO list on separate FETCHes with the same cursor. Each FETCH retrieves another row and assigns values to the INTO variables, as the following example shows:

DECLARE

   CURSOR c1 IS SELECT ename FROM emp;

   name1  emp.ename%TYPE;

   name2  emp.ename%TYPE;

   name3  emp.ename%TYPE;

BEGIN

   OPEN c1;

   FETCH c1 INTO name1;  -- this fetches first row

   FETCH c1 INTO name2;  -- this fetches second row

   FETCH c1 INTO name3;  -- this fetches third row

   ...

   CLOSE c1;

END;

If you execute a FETCH but there are no more rows left in the active set, the values of the fetch-list variables are indeterminate.

 Closing a Cursor

The CLOSE statement disables the cursor, and the active set becomes undefined. An example of the CLOSE statement follows:

CLOSE c1;

Once a cursor is CLOSEd, you can reOPEN it. Any other operation on a closed cursor raises the predefined exception INVALID_CURSOR, which corresponds to ORACLE error ORA-01001.

Explicit Cursor Attributes

Each cursor that you explicitly define has four attributes: %NOTFOUND, %FOUND, %ROWCOUNT, and %ISOPEN. When appended to the cursor name, these attributes let you access useful information about the execution of a multirow query. You can use explicit cursor attributes in procedural statements but not in SQL statements.

 Using %NOTFOUND

When a cursor is OPENed, the rows that satisfy the associated query are identified and form the active set. Rows are FETCHed from the active set one at a time. If the last fetch returned a row, %NOTFOUND evaluates to FALSE. If the last fetch failed to return a row (because the active set was empty), %NOTFOUND evaluates to TRUE. FETCH is expected to fail eventually, so when that happens, no exception is raised.

In the following example, you use %NOTFOUND to exit a loop when FETCH fails to return a row:

LOOP

   FETCH c1 INTO my_ename, my_deptno;

   EXIT WHEN c1%NOTFOUND;

   ...

END LOOP;

Before the first fetch, %NOTFOUND evaluates to NULL. So, if FETCH never executes successfully, the loop is never exited. That is because the EXIT WHEN statement executes only if its WHEN condition is true. To be safe, you might want to use the following EXIT statement instead:

EXIT WHEN c1%NOTFOUND OR c1%NOTFOUND IS NULL;

You can open multiple cursors, then use %NOTFOUND to tell which cursors have rows left to fetch. If a cursor is not open, referencing it with %NOTFOUND raises the predefined exception INVALID_CURSOR.

 Using %FOUND

%FOUND is the logical opposite of %NOTFOUND. After an explicit cursor is open but before the first fetch, %FOUND evaluates to NULL. Thereafter, it evaluates to TRUE if the last fetch returned a row or to FALSE if no row was returned.

In the following example, you use %FOUND to select an action:

LOOP

   FETCH c1 INTO my_ename, my_deptno;

   IF c1%FOUND THEN  -- fetch succeeded

      INSERT INTO temp VALUES (...);

   ELSE  -- fetch failed, so exit loop

      EXIT;

   END IF;

   ...

END LOOP;

You can open multiple cursors, then use %FOUND to tell which cursors have rows left to fetch. If a cursor is not open, referencing it with %FOUND raises INVALID_CURSOR.

 Using %ROWCOUNT

When you open its cursor, %ROWCOUNT is zeroed. Before the first fetch, %ROWCOUNT returns a zero. Thereafter, it returns the number of rows fetched so far. The number is incremented if the latest fetch returned a row. In the next example, you use %ROWCOUNT to take action if more than ten rows have been fetched:

LOOP

   FETCH c1 INTO my_ename, my_deptno;

   IF c1%ROWCOUNT > 10 THEN

      ...

   END IF;

   ...

END LOOP;

You can open multiple cursors, then use %ROWCOUNT to tell how many rows have been fetched so far. If a cursor is not open, referencing it with %ROWCOUNT raises INVALID_CURSOR.

 Using %ISOPEN

%ISOPEN evaluates to TRUE if its cursor is open; otherwise, %ISOPEN evaluates to FALSE. In the following example, you use %ISOPEN to select an action:

IF c1%ISOPEN THEN  -- cursor is open

   ...

ELSE  -- cursor is closed, so open it

   OPEN c1;

END IF;

Table 4 - 1 shows the value returned when you reference a cursor attribute before and after executing an OPEN, FETCH, or CLOSE statement. Notice that before the first FETCH, %NOTFOUND and %FOUND are null when applied to an open cursor.

%NOTFOUND	%FOUND	%ROWCOUNT	%ISOPEN

Before	*	*	*	FALSE

OPEN	After	NULL	NULL	0	TRUE

Before	NULL	NULL	0	TRUE

first

FETCH	After	FALSE	TRUE	1	TRUE

middle	Before	FALSE	TRUE	1	TRUE

FETCHes	After	FALSE	TRUE	data-dependent	TRUE

last	Before	FALSE	TRUE	data-dependent	TRUE

FETCH	After	TRUE	FALSE	data-dependent	TRUE

Before	TRUE	FALSE	data-dependent	TRUE

CLOSE	After	*	*	*	FALSE

Table 4 - 1.  Cursor Values

Some Examples

Suppose you have a table named data_table that holds data collected from laboratory experiments, and you want to analyze the data from experiment 1. In the following example, you compute the results and store them in a database table named temp:

-- available online in file EXAMP5

DECLARE

   num1    data_table.n1%TYPE;  -- Declare variables

   num2    data_table.n2%TYPE;  -- to be of same type as

   num3    data_table.n3%TYPE;  -- database columns

   result  temp.col1%TYPE;

   CURSOR c1 IS

      SELECT n1, n2, n3 FROM data_table

         WHERE exper_num = 1;

BEGIN

   OPEN c1;

   LOOP

      FETCH c1 INTO num1, num2, num3;

      EXIT WHEN c1%NOTFOUND;

          -- the c1%NOTFOUND condition evaluates

          -- to TRUE when FETCH finds no more rows

      /* calculate and store the results */

      result := num2/(num1 + num3);

      INSERT INTO temp VALUES (result, NULL, NULL);

   END LOOP;

   CLOSE c1;

   COMMIT;

END;

In the next example, you check all storage bins that contain part number 5469, withdrawing their contents until you accumulate 1000 units:

-- available online in file EXAMP6

DECLARE

   CURSOR bin_cur(part_number NUMBER) IS SELECT amt_in_bin

      FROM bins

      WHERE part_num = part_number AND

         amt_in_bin > 0

         ORDER BY bin_num

         FOR UPDATE OF amt_in_bin;

   bin_amt         bins.amt_in_bin%TYPE;

   total_so_far    NUMBER(5) := 0;

   amount_needed   CONSTANT NUMBER(5) := 1000;

   bins_looked_at  NUMBER(3) := 0;

BEGIN

   OPEN bin_cur(5469);

   WHILE total_so_far < amount_needed LOOP

      FETCH bin_cur INTO bin_amt;

      EXIT WHEN bin_cur%NOTFOUND;

         /* If we exit, there's not enough to *

          * satisfy the order.                */

      bins_looked_at := bins_looked_at + 1;

      IF total_so_far + bin_amt < amount_needed THEN

         UPDATE bins SET amt_in_bin = 0

             WHERE CURRENT OF bin_cur;

                 -- take everything in the bin

         total_so_far := total_so_far + bin_amt;

      ELSE        -- we finally have enough

         UPDATE bins SET amt_in_bin = amt_in_bin

             - (amount_needed - total_so_far)

             WHERE CURRENT OF bin_cur;

         total_so_far := amount_needed;

      END IF;

   END LOOP;

   CLOSE bin_cur;

   INSERT INTO temp VALUES (NULL, bins_looked_at, '<- bins

      looked at');

   COMMIT;

END;

Implicit Cursors

ORACLE implicitly opens a cursor to process each SQL statement not associated with an explicitly declared cursor. PL/SQL lets you refer to the most recent implicit cursor as the "SQL" cursor. So, although you cannot use the OPEN, FETCH, and CLOSE statements to control an implicit cursor, you can still use cursor attributes to access information about the most recently executed SQL statement.

Implicit Cursor Attributes

The SQL cursor has four attributes: %NOTFOUND, %FOUND, %ROWCOUNT, and %ISOPEN. When appended to the cursor name (SQL), these attributes let you access information about the execution of INSERT, UPDATE, DELETE, and SELECT INTO statements. You can use implicit cursor attributes in procedural statements but not in SQL statements.

The values of cursor attributes always refer to the most recently executed SQL statement, wherever that statement appears. It might be in a different scope (for example, in a sub-block). So, if you want to save an attribute value for later use, assign it to a Boolean variable immediately. The following example shows how failing to save an attribute value can result in a logic bug:

UPDATE parts SET qty = qty - 1 WHERE partno = part_id;

check_parts;  -- procedure call

IF SQL%NOTFOUND THEN  -- dangerous!

   ...

END IF;

In this example, it is dangerous to rely on the IF condition because the procedure check_parts might have changed the value of %NOTFOUND. You can debug the code as follows:

UPDATE parts SET qty = qty - 1 WHERE partno = part_id;

sql_notfound := SQL%NOTFOUND;

check_parts;

IF sql_notfound THEN

   ...

END IF;

Before ORACLE opens the SQL cursor automatically, the implicit cursor attributes evaluate to NULL.

 Using %NOTFOUND

%NOTFOUND evaluates to TRUE if an INSERT, UPDATE, or DELETE affected no rows or a SELECT INTO returned no rows. Otherwise, %NOTFOUND evaluates to FALSE. In the next example, you use %NOTFOUND to insert a new row if an update fails:

UPDATE emp SET sal = sal * 1.05 WHERE empno = my_empno;

IF SQL%NOTFOUND THEN  -- update failed

   INSERT INTO temp VALUES (...);

END IF;

If a SELECT INTO fails to return a row, the predefined exception NO_DATA_FOUND is raised whether you check %NOTFOUND on the next line or not. Consider the following example:

DECLARE

   my_sal  NUMBER(7,2);

   my_empno  NUMBER(4);

BEGIN

   ...

   SELECT sal INTO my_sal FROM emp WHERE empno = my_empno;

   -- might raise NO_DATA_FOUND

   IF SQL%NOTFOUND THEN  -- condition tested only when false

      ...  -- this action is never taken

   END IF;

EXCEPTION

   ...

END;

The check is useless because the IF condition is tested only when %NOTFOUND is false. When NO_DATA_FOUND is raised, normal execution stops and control transfers to the exception-handling part of the block. In this situation, %NOTFOUND is useful in the OTHERS exception handler, as the example below shows. Instead of coding a NO_DATA_FOUND handler, you find out if that exception was raised by checking %NOTFOUND.

DECLARE

   my_sal    NUMBER(7,2);

   my_empno  NUMBER(4);

BEGIN

   ...

   SELECT sal INTO my_sal FROM emp WHERE empno =my_empno;

   -- might raise NO_DATA_FOUND

EXCEPTION

   WHEN OTHERS THEN

      IF SQL%NOTFOUND THEN  -- check for 'no data found'

         ...

      END IF;

      ...

END;

However, a SELECT INTO that calls a SQL group function never raises the exception NO_DATA_FOUND. That is because group functions such as AVG and SUM always return a value or a null. In such cases, %NOTFOUND always evaluates to FALSE. Consider the following example:

DECLARE

   my_sal     NUMBER(7,2);

   my_deptno  NUMBER(2);

BEGIN

   ...

   SELECT MAX(sal) INTO my_sal FROM emp WHERE deptno = my_deptno;

   -- never raises NO_DATA_FOUND

   IF SQL%NOTFOUND THEN  -- always tested but never true

      ...  -- this action is never taken

   END IF;

EXCEPTION

   WHEN NO_DATA_FOUND THEN  -- never invoked

      ...

END;

 Using %FOUND

%FOUND is the logical opposite of %NOTFOUND. Until a SQL data manipulation statement is executed, %FOUND evaluates to NULL. Thereafter, %FOUND evaluates to TRUE if an INSERT, UPDATE, or DELETE affected one or more rows or a SELECT INTO returned one or more rows. Otherwise, %FOUND evaluates to FALSE. In the following example, you use %FOUND to insert a row if a deletion succeeds:

DELETE FROM temp_emp WHERE empno = my_empno;

IF SQL%FOUND THEN  -- delete succeeded

   INSERT INTO emp VALUES (my_empno, my_ename, ...);

END IF;

 Using %ROWCOUNT

%ROWCOUNT returns the number of rows affected by an INSERT, UPDATE, or DELETE or returned by a SELECT INTO. %ROWCOUNT returns a zero if an INSERT, UPDATE, or DELETE affected no rows or a SELECT INTO returned no rows. In the following example, you use %ROWCOUNT to take action if more than ten rows have been deleted:

DELETE FROM emp WHERE ...

IF SQL%ROWCOUNT > 10 THEN

   ...

END IF;

If a SELECT INTO returns more than one row, the predefined exception TOO_MANY_ROWS is raised and %ROWCOUNT is set to 1, not the actual number of rows that satisfy the query. In this situation, %ROWCOUNT is useful in the OTHERS exception handler, as the example below shows. Instead of coding a TOO_MANY_ROWS handler, you find out if the exception TOO_MANY_ROWS was raised by checking %ROWCOUNT.

DECLARE

   my_sal    NUMBER(7,2);

   my_ename  CHAR(10);

BEGIN

   ...

   SELECT sal INTO my_sal FROM emp WHERE ename = my_ename;

   -- might raise TOO_MANY_ROWS

   ...

EXCEPTION

   WHEN OTHERS THEN

      IF SQL%ROWCOUNT > 0 THEN  -- check for 'too many rows'

         ...

      END IF;

      ...

END;

 Using %ISOPEN

ORACLE closes the SQL cursor automatically after executing its associated SQL statement. As a result, %ISOPEN always evaluates to FALSE.

Packaged Cursors

You can separate a cursor specification from its body for placement in a package by using the RETURN clause, as the following example shows:

CREATE PACKAGE emp_actions AS

   /* Declare cursor specification. */

   CURSOR c1 RETURN emp%ROWTYPE;

   ...

END emp_actions;

CREATE PACKAGE BODY emp_actions AS

   /* Define cursor body. */

   CURSOR c1 RETURN emp%ROWTYPE

      SELECT * FROM emp WHERE sal > 3000;

   ...

END emp_actions;

That way, you can change the cursor body without changing the cursor specification. For instance, you might want to change the WHERE clause in the last example, as follows:

CURSOR c1 RETURN emp%ROWTYPE

   SELECT * FROM emp WHERE deptno = 20;

A cursor specification has no SELECT statement because the RETURN clause defines the datatype of the result value. You can use the %ROWTYPE attribute in a RETURN clause to provide a record type that represents a row in a database table. You can also use the %TYPE attribute in a RETURN clause to provide the datatype of a variable, constant, or database column.

A cursor body must have a SELECT statement and the same RETURN clause as its corresponding cursor specification. Furthermore, the number and datatypes of select-list items in the SELECT statement must match the RETURN clause.

Cursor FOR Loops

Recall from Chapter 1 that in most situations requiring a cursor, you can use a cursor FOR loop to simplify coding. A cursor FOR loop implicitly declares its loop index as a record of type %ROWTYPE, opens a cursor, repeatedly fetches rows of values from the active set into fields in the record, then closes the cursor when all rows have been processed or when you exit the loop.

Consider the PL/SQL block below, which uses data from an experiment to compute results, then stores the results in a temporary table. The FOR loop index c1rec is implicitly declared as a record. Its fields store all the column values fetched from the cursor c1. Individual fields are referenced using dot notation.

-- available online in file EXAMP7

DECLARE

   result  temp.col1%TYPE;

   CURSOR c1 IS

      SELECT n1, n2, n3 FROM data_table

         WHERE exper_num = 1;

BEGIN

   FOR c1rec IN c1 LOOP

         /* calculate and store the results */

      result := c1rec.n2 / (c1rec.n1 + c1rec.n3);

      INSERT INTO temp VALUES (result, NULL, NULL);

   END LOOP;

   COMMIT;

END;

Before each iteration of the FOR loop, PL/SQL fetches into the implicitly declared record, which is equivalent to a record explicitly declared as follows:

c1rec  c1%ROWTYPE;

The record is defined only inside the loop. You cannot refer to its fields outside the loop. For example, the following reference is illegal:

BEGIN

   ...

   FOR c1rec IN c1 LOOP

      ...

   END LOOP;

   result := c1rec.n2 + 3;  -- illegal

END;

The sequence of statements inside the loop is executed once for each row that satisfies the query associated with the cursor. When you leave the loop, the cursor is closed automatically. This is true even if you use an EXIT or GOTO statement to leave the loop prematurely or if an exception is raised inside the loop.

 Using Aliases

Fields in the implicitly declared record hold column values from the most recently fetched row. The fields have the same names as corresponding columns in the query select list. But, what happens if a select-list item is an expression? Consider the following example:

CURSOR c1 IS

   SELECT empno, sal+NVL(comm,0), job FROM ...

In such cases, you must include an alias for the select-list item. In the next example, wages is an alias for the select-list item sal+NVL(comm,0):

CURSOR c1 IS

   SELECT empno, sal+NVL(comm,0) wages, job FROM ...

To reference the corresponding field, you use the alias instead of a column name, as follows:

IF emp_rec.wages < 1000 THEN ...

 Passing Parameters

You can pass parameters to a cursor used in a cursor FOR loop. In the following example, you pass a department number. Then, you compute the total wages paid to employees in that department. Also, you determine how many employees have salaries higher than $2000 and how many have commissions larger than their salaries.

-- available online in file EXAMP8

DECLARE

   CURSOR emp_cursor(dnum NUMBER) IS

      SELECT sal, comm FROM emp WHERE deptno = dnum;

   total_wages  NUMBER(11,2) := 0;

   high_paid    NUMBER(4) := 0;

   higher_comm  NUMBER(4) := 0;

BEGIN

   /* The number of iterations will equal the number of rows *

    * returned by emp_cursor.                                */

   FOR emp_record IN emp_cursor(20) LOOP

      emp_record.comm := NVL(emp_record.comm, 0);

      total_wages := total_wages + emp_record.sal +

         emp_record.comm;

      IF emp_record.sal > 2000.00 THEN

         high_paid := high_paid + 1;

      END IF;

      IF emp_record.comm > emp_record.sal THEN

         higher_comm := higher_comm + 1;

      END IF;

   END LOOP;

   INSERT INTO temp VALUES (high_paid, higher_comm,

      'Total Wages: ' || TO_CHAR(total_wages));

   COMMIT;

END;

________________________________________

Transaction Processing

The first SQL statement in your program begins a transaction. When one transaction ends, the next SQL statement automatically begins another transaction. Thus, every SQL statement is part of a transaction.

The COMMIT and ROLLBACK statements ensure that all database changes brought about by SQL operations are either made permanent or undone at the same time. All the SQL statements executed since the last COMMIT or ROLLBACK make up the current transaction. The SAVEPOINT statement names and marks the current point in the processing of a transaction.

Distributed Transactions

A distributed transaction includes at least one SQL statement that updates data at multiple nodes in a distributed database. If the update affects only one node, the transaction is remote, not distributed.

If part of a distributed transaction fails, you must roll back the whole transaction or roll back to a savepoint. ORACLE issues an error message in this situation. So, include a check for the error in every application that does distributed transactions. For more information, see the ORACLE7 Server Application Developer's Guide.

Using COMMIT

The COMMIT statement ends the current transaction and makes permanent any changes made during that transaction. Until you commit the changes, other users cannot access the changed data; they see the data as it was before you made the changes.

Consider a simple transaction that transfers money from one bank account to another. The transaction requires two UPDATEs because it debits the first account, then credits the second. In the example below, after crediting the second account, you issue a COMMIT, which makes the changes permanent. Only then do other users see the changes.

BEGIN

   ...

   UPDATE accts SET bal = my_bal - debit

      WHERE acctno = 7715;

   ...

   UPDATE accts SET bal = my_bal + credit

      WHERE acctno = 7720;

   COMMIT WORK;

END;

The optional keyword WORK has no effect other than to improve readability.

The COMMIT statement releases all row and table locks. It also erases any savepoints (discussed later) marked since the last COMMIT or ROLLBACK.

The COMMENT clause lets you specify a comment to be associated with a distributed transaction. When you issue a COMMIT, changes to each database affected by a distributed transaction are made permanent. However, if a network or machine fails during the commit, the state of the distributed transaction might be unknown or in doubt. In that case, ORACLE stores the text specified by COMMENT in the data dictionary along with the transaction ID. The text must be a quoted literal <50 characters in length. An example follows:

COMMIT COMMENT 'In-doubt order transaction; notify Order Entry';

Using ROLLBACK

The ROLLBACK statement is the inverse of COMMIT. It ends the current transaction and undoes any changes made during that transaction. ROLLBACK is useful for two reasons. First, if you make a mistake, such as deleting the wrong row from a table, you can use ROLLBACK to restore the original data. ROLLBACK TO allows you to erase back to an intermediate statement in the current transaction so that you do not have to erase all your changes.

Second, ROLLBACK is useful when you start a transaction that you cannot finish because an exception is raised or a SQL statement fails. In such cases, ROLLBACK lets you return to the starting point to take corrective action and perhaps try again.

Consider the example below, in which you insert information about an employee into three different database tables. All three tables have a column that holds employee numbers and is constrained by a unique index. If an INSERT statement tries to store a duplicate employee number, the predefined exception DUP_VAL_ON_INDEX is raised. In that case, you want to undo all changes. So, you issue a ROLLBACK in the exception handler.

DECLARE

   emp_id  INTEGER;

   ...

BEGIN

   SELECT empno, ... INTO emp_id, ... FROM new_emp WHERE ...

   ...

   INSERT INTO emp VALUES (emp_id, ...);

   INSERT INTO tax VALUES (emp_id, ...);

   INSERT INTO pay VALUES (emp_id, ...);

   ...

EXCEPTION

   WHEN DUP_VAL_ON_INDEX THEN

      ROLLBACK;

   ...

END;

The COMMENT clause lets you specify a comment to be associated with a distributed transaction. When you issue a ROLLBACK, changes to each database affected by a distributed transaction are undone. However, if a network or machine fails during the rollback, the state of the distributed transaction might be in doubt. In that case, ORACLE stores the text specified by COMMENT in the data dictionary along with the transaction ID. The text must be a quoted literal <50 characters in length. An example follows:

ROLLBACK COMMENT 'In-doubt sales transaction; notify Sales Dept';

 Statement-Level Rollbacks

Before executing a SQL statement, ORACLE marks an implicit savepoint. Then, if the statement fails, ORACLE automatically rolls it back. For example, if an INSERT statement raises an exception by trying to insert a duplicate value in a unique index, the statement is rolled back. Only work started by the failed SQL statement is lost; work done before that statement in the current transaction is saved.

ORACLE can also roll back single SQL statements to break deadlocks. ORACLE signals an error to one of the participating transactions and rolls back the current statement in that transaction.

Before executing a SQL statement, ORACLE must parse it, that is, examine it to make sure it follows syntax rules and refers to valid database objects. Errors detected while executing a SQL statement cause a rollback, but errors detected while parsing the statement do not.

Using SAVEPOINT

SAVEPOINT names and marks the current point in the processing of a transaction. Used with the ROLLBACK TO statement, savepoints let you undo parts of a transaction instead of the whole transaction. In the example below, you mark a savepoint before doing an insert. If the INSERT statement tries to store a duplicate value in the empno column, the predefined exception DUP_VAL_ON_INDEX is raised. In that case, you roll back to the savepoint, undoing just the insert.

DECLARE

   emp_id  emp.empno%TYPE;

BEGIN

   ...

   UPDATE emp SET ... WHERE empno = emp_id;

   DELETE FROM emp WHERE ...

   ...

   SAVEPOINT do_insert;

   INSERT INTO emp VALUES (emp_id, ...);

EXCEPTION

   WHEN DUP_VAL_ON_INDEX THEN

      ROLLBACK TO do_insert;

END;

When you roll back to a savepoint, any savepoints marked after that savepoint are erased. However, the savepoint to which you roll back is not erased. For example, if you mark five savepoints, then roll back to the third, only the fourth and fifth are erased. A simple ROLLBACK or COMMIT erases all savepoints.

If you mark a savepoint within a recursive subprogram, new instances of the SAVEPOINT statement are executed at each level in the recursive descent. However, you can only ROLLBACK TO the most recently marked savepoint.

Savepoint names are undeclared identifiers and can be reused within a transaction. This moves the savepoint from its old position to the current point in the transaction. Thus, a rollback to the savepoint affects only the current part of your transaction. Consider the following example:

...

BEGIN

   ...

   SAVEPOINT my_point;

   UPDATE emp SET ... WHERE empno = emp_id;

   ...

   SAVEPOINT my_point;  -- move my_point to current point

   INSERT INTO emp VALUES (emp_id, ...);

   ...

EXCEPTION

   WHEN OTHERS THEN

      ROLLBACK TO my_point;

END;

By default, the number of active savepoints per session is limited to 5. An active savepoint is one marked since the last commit or rollback. You or your DBA can raise the limit (up to 255) by increasing the value of the ORACLE initialization parameter SAVEPOINTS.

Implicit Rollbacks

Before executing an INSERT, UPDATE, or DELETE statement, ORACLE marks an implicit savepoint (unavailable to you). If the statement fails, ORACLE rolls back to the savepoint. Normally, just the failed SQL statement is rolled back, not the whole transaction. However, if the statement raises an unhandled exception, the host environment determines what is rolled back.

If a stored subprogram fails with an unhandled exception, ORACLE implicitly rolls back all database work done by the subprogram. However, if the subprogram issued a COMMIT before the unhandled exception was raised, only the uncommitted work is rolled back.

Ending Transactions

It is good programming practice to commit or roll back every transaction explicitly. Whether you issue the COMMIT or ROLLBACK in your PL/SQL program or in the host environment depends on the flow of application logic. If you neglect to commit or roll back a transaction explicitly, the host environment determines its final state.

For example, in the SQL*Plus environment, if your PL/SQL block does not include a COMMIT or ROLLBACK statement, the final state of your transaction depends on what you do after running the block. If you execute a data definition, data control, or COMMIT statement or if you issue the EXIT, DISCONNECT, or QUIT command, ORACLE commits the transaction. If you execute a ROLLBACK statement or abort the SQL*Plus session, ORACLE rolls back the transaction.

In the ORACLE Precompiler environment, if your program does not terminate normally, ORACLE rolls back your transaction. A program terminates normally when it explicitly commits or rolls back work and disconnects from ORACLE using the RELEASE parameter, as follows:

EXEC SQL COMMIT WORK RELEASE;

In the OCI environment, if you issue the OLOGOF call, ORACLE automatically commits your transaction. Otherwise, ORACLE rolls back the transaction.

Using SET TRANSACTION

The default state for all transactions is statement-level read consistency. This guarantees that a query sees only changes committed before it began executing, plus any changes made by prior statements in the current transaction. If other users commit changes to the relevant database tables, subsequent queries see those changes.

However, you can use the SET TRANSACTION statement to establish a read-only transaction, which provides transaction-level read consistency. This guarantees that a query sees only changes committed before the current transaction began. The SET TRANSACTION READ ONLY statement takes no additional parameters. An example follows:

SET TRANSACTION READ ONLY;

The SET TRANSACTION statement must be the first SQL statement in a read-only transaction and can only appear once in a transaction. Remember, if a transaction is set to READ ONLY, subsequent queries see only changes committed before the transaction began. The use of READ ONLY does not affect other users or transactions.

Only the SELECT, COMMIT, and ROLLBACK statements are allowed in a read-only transaction. For example, including an INSERT or DELETE statement raises an exception.

During a read-only transaction, all queries refer to the same snapshot of the database, providing a multitable, multiquery, read-consistent view. Other users can continue to query or update data as usual. A commit or rollback ends the transaction. In the example below, as a store manager, you use a read-only transaction to gather sales figures for the day, the past week, and the past month. The figures are unaffected by other users updating the database during the transaction.

DECLARE

   daily_sales    REAL;

   weekly_sales   REAL;

   monthly_sales  REAL;

BEGIN

   SET TRANSACTION READ ONLY;

   SELECT SUM(amt) INTO daily_sales FROM sales

      WHERE dte = SYSDATE;

   SELECT SUM(amt) INTO weekly_sales FROM sales

      WHERE dte > SYSDATE - 7;

   SELECT SUM(amt) INTO monthly_sales FROM sales

      WHERE dte > SYSDATE - 30;

   COMMIT;  -- simply ends the transaction since there

            -- are no changes to make permanent

   ...

END;

Overriding Default Locking

By default, ORACLE locks data structures for you automatically. However, you can request specific data locks on rows or tables when it is to your advantage to override default locking. Explicit locking lets you share or deny access to a table for the duration of a transaction.

 Using FOR UPDATE

When declaring a cursor that will be referenced in the WHERE CURRENT OF clause of an UPDATE or DELETE statement, you must use the FOR UPDATE clause to acquire exclusive row locks. If present, the FOR UPDATE clause must appear at the end of the cursor declaration, as the following example shows:

DECLARE

   CURSOR c1 IS SELECT empno, sal FROM emp

      WHERE job = 'SALESMAN' AND comm > sal FOR UPDATE;

The FOR UPDATE clause indicates that rows will be updated or deleted and locks all rows in the active set. This is useful when you want to base an update on the existing values in a row. In that case, you must make sure the row is not changed by another user before the update. All rows in the active set are locked when you OPEN the cursor. The rows are unlocked when you COMMIT the transaction. So, you cannot FETCH from a FOR UPDATE cursor after a COMMIT.

When querying multiple tables, you can use the FOR UPDATE OF clause to confine row locking to particular tables. Rows in a table are locked only if the FOR UPDATE OF clause refers to a column in that table. For example, the following query locks rows in the emp table but not in the dept table:

DECLARE

   CURSOR c1 IS SELECT ename, dname FROM emp, dept

      WHERE emp.deptno = dept.deptno AND job = 'MANAGER'

      FOR UPDATE OF sal;

You use the WHERE CURRENT OF clause in an UPDATE or DELETE statement to refer to the latest row FETCHed from a cursor, as the following example shows:

DECLARE

   CURSOR c1 IS SELECT empno, job, sal FROM emp FOR UPDATE;

   ...

BEGIN

   OPEN c1;

   LOOP

      FETCH c1 INTO ...

      ...

      UPDATE emp SET sal = new_sal WHERE CURRENT OF c1;

   END LOOP;

   ...

 Using LOCK TABLE

The LOCK TABLE statement lets you lock entire database tables in a specified lock mode so that you can share or deny access to tables while maintaining their integrity. For example, the statement below locks the emp table in row share mode. Row share locks allow concurrent access to a table; they prevent other users from locking the entire table for exclusive use. Table locks are released when your transaction issues a COMMIT or ROLLBACK.

LOCK TABLE emp IN ROW SHARE MODE NOWAIT;

The lock mode determines what other locks can be placed on the table. For example, many users can acquire row share locks on a table at the same time, but only one user at a time can acquire an exclusive lock. While one user has an exclusive lock on a table, no other users can INSERT, UPDATE, or DELETE rows in that table.

The optional keyword NOWAIT tells ORACLE not to wait if the table has been locked by another user. Control is immediately returned to your program so that it can do other work before trying again to acquire the lock. If you omit the keyword NOWAIT, ORACLE waits until the table is available; the wait has no set limit.

A table lock never keeps other users from querying a table, and a query never acquires a table lock. Only if two different transactions try to modify the same row will one transaction wait for the other to complete.

 Fetching Across Commits

Remember, the FOR UPDATE clause acquires exclusive row locks. All rows are locked when you OPEN the cursor, not as they are fetched. The rows are unlocked when you COMMIT or ROLLBACK your transaction. Therefore, you cannot FETCH from a FOR UPDATE cursor after a COMMIT. If you do, an exception is raised. Consider the following FOR loop, which fails after the tenth insert:

DECLARE

   CURSOR c1 IS SELECT ename FROM emp FOR UPDATE OF sal;

   ctr  NUMBER := 0;

BEGIN

   FOR emp_rec IN c1 LOOP  -- FETCHes implicitly

      ...

      ctr := ctr + 1;

      INSERT INTO temp VALUES (ctr, 'still going');

      IF ctr >= 10 THEN

         COMMIT;  -- releases locks

      END IF;

   END LOOP;

END;

If you want to fetch across commits, do not use the FOR UPDATE and WHERE CURRENT OF clauses. Instead, use the ROWID pseudocolumn to mimic the WHERE CURRENT OF clause. Simply select the rowid of each row into a ROWID variable. Then, use the rowid to identify the current row during subsequent updates and deletes. An example follows:

DECLARE

   CURSOR c1 IS SELECT ename, job, rowid FROM emp;

   my_ename  emp.ename%TYPE;

   my_job    emp.job%TYPE;

   my_rowid  ROWID;

BEGIN

   OPEN c1;

   LOOP

      FETCH c1 INTO my_ename, my_job, my_rowid;

      EXIT WHEN c1%NOTFOUND;

      UPDATE emp SET sal = sal * 1.05 WHERE rowid = my_rowid;

      -- this mimics WHERE CURRENT OF c1

      COMMIT;

   END LOOP;

   CLOSE c1;

END;

Be careful. In the last example, the fetched rows are not locked because no FOR UPDATE clause is used. So, you might unintentionally overwrite changes made by another user. Also, the cursor must have a read-consistent view of the data, so rollback segments used in the update are not released until the cursor is closed. This can slow down processing when many rows are updated.

The next example shows that you can use the %ROWTYPE attribute with cursors that reference the ROWID pseudocolumn:

DECLARE

   CURSOR c1 IS SELECT ename, sal, rowid FROM emp;

   emp_rec  c1%ROWTYPE;

BEGIN

   OPEN c1;

   LOOP

      FETCH c1 INTO emp_rec;

      EXIT WHEN c1%NOTFOUND;

      ...

      IF ... THEN

         DELETE FROM emp WHERE rowid = emp_rec.rowid;

      END IF;

   END LOOP;

   CLOSE c1;

END;

Dealing with Size Limitations

PL/SQL was designed primarily for transaction processing. One consequence is that the PL/SQL compiler imposes a limit on program size. The limit depends on the mix of statements in your PL/SQL program and the memory available on your platform. Programs that exceed the limit cause a "program too large" compilation error.

The best solution to this problem is to modularize your program by defining subprograms, which can be stored in an ORACLE database. For more information, see Chapter 6.

Another solution is to break your program into two sub-blocks. Before the first block terminates, have it INSERT any data the second block needs into a database table called temp (for example). When the second block starts executing, have it SELECT the data from temp. This approximates the passing of parameters from one procedure to another. The following example shows two "parameter passing" PL/SQL blocks in a SQL*Plus script:

...

DECLARE

   mode    NUMBER;

   median  NUMBER;

   ...

BEGIN

   ...

   INSERT INTO temp (col1, col2, col3)

      VALUES (mode, median, 'blockA');

END;

/

...

DECLARE

   mode    NUMBER;

   median  NUMBER;

   ...

BEGIN

   SELECT col1, col2 INTO mode, median FROM temp

      WHERE col3 = 'blockA';

   ...

END;

/

...

The previous method works unless you must re-execute the first block while the second block is still executing or unless two or more users must run the script concurrently. To avoid these restrictions, embed your PL/SQL program in a third-generation host language such as C, COBOL, or FORTRAN. That way, you can re-execute the first block using flow-of-control statements. Also, you can store data in global host variables instead of using a temporary database table, as the following Pro*C example shows:

EXEC SQL BEGIN DECLARE SECTION;

   int    my_empno;

   float  my_sal, my_comm;

   short  comm_ind;

   ...

EXEC SQL END DECLARE SECTION;

...

EXEC SQL EXECUTE

   BEGIN

      ...

      SELECT sal, comm INTO :my_sal, :my_comm:comm_ind FROM emp

         WHERE empno = :my_empno;

      IF :my_comm:comm_ind IS NULL THEN

         ...

      END IF;

   END;

END-EXEC;

...

EXEC SQL EXECUTE

   BEGIN

      ...

      IF :my_comm:comm_ind > 1000 THEN

         :my_sal := :my_sal * 1.10;

         UPDATE emp SET sal = :my_sal WHERE empno = :my_empno;

      END IF;

   END;

END-EXEC;

...

________________________________________

Database Triggers

A database trigger is a stored PL/SQL program unit associated with a specific database table. ORACLE executes (fires) the database trigger automatically whenever a given SQL operation affects the table. So, unlike subprograms, which must be invoked explicitly, database triggers are invoked implicitly. Among other things, you can use database triggers to

•	audit data modifications

•	log events transparently

•	enforce complex business rules

•	derive column values automatically

•	implement complex security authorizations

•	maintain replicate tables

You can associate up to 12 database triggers with a given table. To create a database trigger, you must have CREATE TRIGGER privileges and either own the associated table, have ALTER privileges for the associated table, or have ALTER ANY TABLE privileges.

A database trigger has three parts: a triggering event, an optional trigger constraint, and a trigger action. When the event occurs, the database trigger fires and an anonymous PL/SQL block performs the action. Database triggers fire with the privileges of the owner, not the current user. So, the owner must have appropriate access to all objects referenced by the trigger action.

The example below illustrates transparent event logging. The database trigger named reorder ensures that a part is reordered when its quantity on hand drops below the reorder point.

CREATE TRIGGER reorder

   /* triggering event */

   AFTER UPDATE OF qty_on_hand ON inventory  -- table

   FOR EACH ROW

   /* trigger constraint */

   WHEN (new.reorderable = 'T')

BEGIN

   /* trigger action */

   IF :new.qty_on_hand < :new.reorder_point THEN

      INSERT INTO pending_orders

         VALUES (:new.part_no, :new.reorder_qty, SYSDATE);

   END IF;

END;

The name in the ON clause identifies the database table associated with the database trigger. The triggering event specifies the SQL data manipulation statement that affects the table. In this case, the statement is UPDATE. If the trigger statement fails, it is rolled back. The keyword AFTER specifies that the database trigger fires after the update is done.

By default, a database trigger fires once per table. The FOR EACH ROW option specifies that the trigger fires once per row. For the trigger to fire, however, the Boolean expression in the WHEN clause must evaluate to TRUE.

The prefix :new is a correlation name that refers to the newly updated column value. Within a database trigger, you can reference :new and :old values of changing rows. Notice that the colon is not used in the WHEN clause. You can use the REFERENCING clause (not shown) to replace :new and :old with other correlation names.

Except for transaction control statements such as COMMIT and ROLLBACK, any SQL or procedural statement, including subprogram calls, can appear in the BEGIN ... END block. A database trigger can also have DECLARE and EXCEPTION sections.

The next example shows that the trigger action can include calls to the built-in ORACLE procedure raise_application_error, which lets you issue user-defined error messages:

CREATE TRIGGER check_salary

   BEFORE INSERT OR UPDATE OF sal, job ON emp

   FOR EACH ROW

   WHEN (new.job != 'PRESIDENT')

DECLARE

   minsal  NUMBER;

   maxsal  NUMBER;

BEGIN

   /* Get salary range for a given job from table sals. */

   SELECT losal, hisal INTO minsal, maxsal FROM sals

      WHERE job = :new.job;

   /* If salary is out of range, increase is negative, *

    * or increase exceeds 10%, raise an exception.     */

   IF (:new.sal < minsal OR :new.sal > maxsal) THEN

       raise_application_error(-20225, 'Salary out of range');

   ELSIF (:new.sal < :old.sal) THEN

       raise_application_error(-20230, 'Negative increase');

   ELSIF (:new.sal > 1.1 * :old.sal) THEN

       raise_application_error(-20235, 'Increase exceeds 10%');

   END IF;

END;

For more information about raise_application_error, see the section "Product-specific Packages" in Chapter 7. For a full discussion of database triggers, see the ORACLE7 Server Application Developer's Guide.


CHAPTER 5. ERROR HANDLING

There is nothing more exhilarating than to be shot at without result.

Winston Churchill

Runtime errors arise from design faults, coding mistakes, hardware failures, and many other sources. Although you cannot anticipate all possible errors, you can plan to handle certain kinds of errors meaningful to your PL/SQL program.

With most programming languages, unless you disable error checking, a runtime error such as stack overflow or division by zero stops normal processing and returns control to the operating system. With PL/SQL, a mechanism called exception handling lets you "bulletproof" your program so that it can continue operating in the presence of errors.

________________________________________

Overview

In PL/SQL, a warning or error condition is called an exception. Exceptions can be internally defined (by the runtime system) or user-defined.

Examples of internally defined exceptions include division by zero and out of memory. Some common internal exceptions have predefined names, such as ZERO_DIVIDE and STORAGE_ERROR. The other internal exceptions can be given names.

You can define exceptions of your own in the declarative part of any PL/SQL block, subprogram, or package. For example, you might define an exception named insufficient_funds to flag overdrawn bank accounts. Unlike internal exceptions, user-defined exceptions must be given names.

When an error occurs, an exception is raised. That is, normal execution stops and control transfers to the exception-handling part of your PL/SQL block or subprogram. Internal exceptions are raised implicitly (automatically) by the runtime system. User-defined exceptions must be raised explicitly by RAISE statements, which can also raise predefined exceptions.

To handle raised exceptions, you write separate routines called exception handlers. After an exception handler runs, the current block stops executing and the enclosing block resumes with the next statement. If there is no enclosing block, control returns to the host environment.

In the following example, you calculate and store a price-to-earnings ratio for a company with ticker symbol XYZ. If the company has zero earnings, the predefined exception ZERO_DIVIDE is raised. This stops normal execution of the block and transfers control to the exception handlers.

DECLARE

   pe_ratio  NUMBER(3,1);

BEGIN

   ...

   SELECT price / earnings INTO pe_ratio FROM stocks

      WHERE symbol = 'XYZ';

      -- might cause a division-by-zero error

   INSERT INTO stats (symbol, ratio) VALUES ('XYZ', pe_ratio);

   COMMIT;

EXCEPTION  -- exception handlers begin here

   WHEN ZERO_DIVIDE THEN  -- handles 'division by zero' error

      INSERT INTO stats (symbol, ratio) VALUES ('XYZ', NULL);

      COMMIT;

   ...

   WHEN OTHERS THEN  -- handles all other errors

      ROLLBACK;

END;   -- exception handlers and block end here

The optional OTHERS handler catches all exceptions that the block does not name specifically.

The last example illustrates exception handling, not the effective use of INSERT statements. For example, a better way to do the insert follows:

INSERT INTO stats (symbol, ratio)

   SELECT symbol, DECODE(earnings, 0, NULL, price / earnings)

   FROM stocks

   WHERE symbol = 'XYZ';

In this example, a subquery supplies values to the INSERT statement. If earnings are zero, the function DECODE returns a null. Otherwise, DECODE returns the price-to-earnings ratio.

________________________________________

Advantages of Exceptions

Using exceptions for error handling has several advantages. Without exception handling, every time you issue a command, you must check for execution errors, as the following example shows:

BEGIN

   SELECT ...

      -- check for 'no data found' error

   SELECT ...

      -- check for 'no data found' error

   SELECT ...

      -- check for 'no data found' error

END;

Error processing is not clearly separated from normal processing; nor is it robust. If you neglect to code a check, the error goes undetected and is likely to cause other, seemingly unrelated errors.

With exceptions, you can handle errors conveniently without the need to code multiple checks, as the next example shows:

BEGIN

   SELECT ...

   SELECT ...

   SELECT ...

EXCEPTION

   WHEN NO_DATA_FOUND THEN  -- catches all 'no data found' errors

END;

Notice how exceptions improve readability by letting you isolate error- handling routines. The primary algorithm is not obscured by error recovery algorithms.

Exceptions also improve reliability. You need not worry about checking for an error at every point it might occur. Just add an exception handler to your PL/SQL block. If the exception is ever raised in that block (or any sub-block), you can be sure it will be handled.

________________________________________

Predefined Exceptions

An internal exception is raised implicitly whenever your PL/SQL program violates an ORACLE rule or exceeds a system-dependent limit. Every ORACLE error has a number, but exceptions must be handled by name. So, PL/SQL predefines some common ORACLE errors as exceptions. For example, the predefined exception NO_DATA_FOUND is raised if a SELECT INTO statement returns no rows.

To handle other ORACLE errors, you can use the OTHERS handler. The error-reporting functions SQLCODE and SQLERRM are especially useful in the OTHERS handler because they return the ORACLE error code and message text. Alternatively, you can use the pragma EXCEPTION_INIT to associate exception names with ORACLE error numbers. See the section "Using EXCEPTION_INIT" later in this chapter.

PL/SQL declares predefined exceptions globally in package STANDARD, which defines the PL/SQL environment. So, you need not declare them yourself. You can write handlers for predefined exceptions using the names shown in the table below. Also shown are the corresponding ORACLE error codes and SQLCODE return values.

Exception Name	ORACLE Error	SQLCODE Value

CURSOR_ALREADY_OPEN	ORA-06511	-6511

DUP_VAL_ON_INDEX	ORA-00001	-1

INVALID_CURSOR	ORA-01001	-1001

INVALID_NUMBER	ORA-01722	-1722

LOGIN_DENIED	ORA-01017	-1017

NO_DATA-FOUND	ORA-01403	+100

NOT_LOGGED_ON	ORA-01012	-1012

PROGRAM_ERROR	ORA-06501	-6501

STORAGE_ERROR	ORA-06500	-6500

TIMEOUT_ON_RESOURCE	ORA-00051	-51

TOO_MANY_ROWS	ORA-01422	-1422

TRANSACTION_BACKED_OUT	ORA-00061	-61

VALUE_ERROR	ORA-06502	-6502

ZERO_DIVIDE	OAR-01476	-1476

Brief descriptions of the predefined exceptions follow:

CURSOR_ALREADY_OPEN      is raised if you try to OPEN an already open cursor. You must CLOSE a cursor before you can reOPEN it.

A cursor FOR loop automatically opens the cursor to which it refers. Therefore, you cannot enter the loop if that cursor is already open, nor can you OPEN that cursor inside the loop.

DUP_VAL_ON_INDEX      is raised if you try to store duplicate values in a database column that is constrained by a unique index.

INVALID_CURSOR      is raised if you try an illegal cursor operation. For example, INVALID_CURSOR is raised if you CLOSE an unopened cursor.

INVALID_NUMBER      is raised in a SQL statement if the conversion of a character string to a number fails because the string does not represent a valid number. For example, the following INSERT statement raises INVALID_NUMBER when ORACLE tries to convert 'HALL' to a number:

INSERT INTO emp (empno, ename, deptno) VALUES ('HALL', 7888, 20);

In procedural statements, VALUE_ERROR is raised instead.

LOGIN_DENIED      is raised if you try logging on to ORACLE with an invalid username/password.

NO_DATA_FOUND      is raised if a SELECT INTO statement returns no rows or if you reference an uninitialized row in a PL/SQL table.

SQL group functions such as AVG and SUM always return a value or a null. So, a SELECT INTO statement that calls a group function will never raise NO_DATA_FOUND.

Because NO_DATA_FOUND is raised if a SELECT INTO statement returns no rows, you can check the value of SQL%NOTFOUND only in an exception handler. However, you can check the value of cursor_name%NOTFOUND after every FETCH. FETCH is expected to return no rows eventually, so when that happens, no exception is raised.

NOT_LOGGED_ON      is raised if your PL/SQL program issues a database call without being logged on to ORACLE.

PROGRAM_ERROR      is raised if PL/SQL has an internal problem.

STORAGE_ERROR      is raised if PL/SQL runs out of memory or if memory is corrupted.

TIMEOUT_ON_RESOURCE      is raised if a timeout occurs while ORACLE is waiting for a resource.

TOO_MANY_ROWS      is raised if a SELECT INTO statement returns more than one row.

TRANSACTION_BACKED_OUT      is typically raised when the remote part of a transaction is rolled back implicitly or explicitly. Your transaction must be rolled back because ORACLE data might be inconsistent at some nodes. In such cases, ROLLBACK the transaction, then retry it. Refer to the section "Retrying a Transaction" later in this chapter.

VALUE_ERROR      is raised if an arithmetic, conversion, truncation, or constraint error occurs. In procedural statements, VALUE_ERROR is raised if the conversion of a character string to a number fails; an example follows:

DECLARE

   my_empno  NUMBER(4);

   my_ename  CHAR(10);

BEGIN

   my_empno := 'HALL';  -- raises VALUE_ERROR

   ...

In SQL statements, INVALID_NUMBER is raised instead.

ZERO_DIVIDE      is raised if you try to divide a number by zero.

________________________________________

User-defined Exceptions

PL/SQL lets you define exceptions of your own. Unlike predefined exceptions, user-defined exceptions must be declared and must be raised explicitly by RAISE statements.

Declaring Exceptions

Exceptions can be declared only in the declarative part of a PL/SQL block, subprogram, or package. You declare an exception by introducing its name, followed by the keyword EXCEPTION. In the following example, you declare an exception named past_due:

DECLARE

   past_due  EXCEPTION;

   acct_num  NUMBER(5);

BEGIN

   ...

Exception and variable declarations are similar. But remember, an exception is an error condition, not an object. Unlike variables, exceptions cannot appear in assignment statements or SQL statements. However, the same scope rules apply to variables and exceptions.

Scope Rules

You cannot declare an exception twice in the same block. You can, however, declare the same exception in two different blocks.

Exceptions declared in a block are considered local to that block and global to all its sub-blocks. Because a block can reference only local or global exceptions, enclosing blocks cannot reference exceptions declared in a sub-block.

If you redeclare a global exception in a sub-block, the local declaration prevails. So, the sub-block cannot reference the global exception unless it was declared in a labeled block, in which case the following syntax is valid:

block_label.exception_name

The next example illustrates the scope rules:

DECLARE

   past_due  EXCEPTION;

   acct_num  NUMBER;

BEGIN

   ...

   ---------------- beginning of sub-block ----------------

   DECLARE

      past_due  EXCEPTION;  -- this declaration prevails

      acct_num  NUMBER;

   BEGIN

      ...

      IF ... THEN

         RAISE past_due;  -- this is not handled

      END IF;

      ...

   END;

   ------------------- end of sub-block -------------------

EXCEPTION

   WHEN past_due THEN  -- does not handle RAISEd exception

       ...

END;

The enclosing block does not handle the RAISEd exception because the declaration of past_due in the sub-block prevails. Though they share the same name, the two past_due exceptions are different, just as the two acct_num variables share the same name but are different variables. Therefore, the RAISE statement and the WHEN clause refer to different exceptions. To have the enclosing block handle the RAISEd exception, you must remove its declaration from the sub-block or define an OTHERS handler.

Using EXCEPTION_INIT

To handle unnamed internal exceptions, you must use the OTHERS handler or the pragma EXCEPTION_INIT. A pragma is a compiler directive, which can be thought of as a parenthetical remark to the compiler. Pragmas (also called pseudoinstructions) are processed at compile time, not at run time. They do not affect the meaning of a program; they simply convey information to the compiler. For example, in the language Ada, the following predefined pragma tells the compiler to optimize the use of storage space:

pragma OPTIMIZE(SPACE);

In PL/SQL, the predefined pragma EXCEPTION_INIT tells the compiler to associate an exception name with an ORACLE error number. That allows you to refer to any internal exception by name and to write a specific handler for it.

You code the pragma EXCEPTION_INIT in the declarative part of a PL/SQL block, subprogram, or package using the syntax

PRAGMA EXCEPTION_INIT(exception_name, ORACLE_error_number);

where exception_name is the name of a previously declared exception. The pragma must appear somewhere after the exception declaration in the same declarative part, as shown in the following example:

DECLARE

   insufficient_privileges  EXCEPTION;

   PRAGMA EXCEPTION_INIT(insufficient_privileges, -1031);

      -----------------------------------------------------

      -- ORACLE returns error number -1031 if, for example,

      -- you try to UPDATE a table for which you have

      -- only SELECT privileges

      -----------------------------------------------------

BEGIN

   ...

EXCEPTION

   WHEN insufficient_privileges THEN

      -- handle the error

   ...

END;

Using raise_application_error

A package named DBMS_STANDARD (part of the Procedural Database Extension) provides language facilities that help your application interact with ORACLE. This package includes a procedure named raise_application_error, which lets you issue user-defined error messages from a stored subprogram or database trigger.

The calling application gets a PL/SQL exception, which it can process using the error-reporting functions SQLCODE and SQLERRM. Moreover, it can use EXCEPTION_INIT to map specific error numbers returned by raise_application_error to exceptions of its own. For more information about raise_application_error, see the section "Product-specific Packages" in Chapter 7.

Redeclaring Predefined Exceptions

Remember, PL/SQL declares predefined exceptions globally in package STANDARD, so you need not declare them yourself. Redeclaring predefined exceptions is error-prone because your local declaration overrides the global declaration. For example, if you declare an exception named invalid_number and then PL/SQL raises the predefined exception INVALID_NUMBER internally, a handler written for INVALID_NUMBER will not catch the internal exception. In such cases, you must use dot notation to specify the predefined exception, as follows:

   ...

EXCEPTION

   WHEN invalid_number OR STANDARD.INVALID_NUMBER THEN

      -- handle the error

   ...

END;

________________________________________

How Exceptions Are Raised

Internal exceptions are raised implicitly by the runtime system, as are user-defined exceptions that you have associated with an ORACLE error number using EXCEPTION_INIT. However, other user-defined exceptions must be raised explicitly by RAISE statements.

Using the RAISE Statement

PL/SQL blocks and subprograms should RAISE an exception only when an error makes it undesirable or impossible to finish processing. You can code a RAISE statement for a given exception anywhere within the scope of that exception. In the following example, you alert your PL/SQL block to a user-defined exception named out_of_stock:

DECLARE

   out_of_stock    EXCEPTION;

   number_on_hand  NUMBER(4);

BEGIN

   ...

   IF number_on_hand < 1 THEN

      RAISE out_of_stock;

   END IF;

   ...

EXCEPTION

   WHEN out_of_stock THEN

      -- handle the error

END;

As the following example shows, you can also raise a predefined exception explicitly:

RAISE INVALID_NUMBER;

That way, you can use an exception handler written for the predefined exception to process other errors, as the next example shows:

DECLARE

   acct_type  INTEGER;

   ...

BEGIN

   ...

   IF acct_type NOT IN (1, 2, 3) THEN

      RAISE INVALID_NUMBER;

   END IF;

   ...

EXCEPTION

   WHEN INVALID_NUMBER THEN

      ROLLBACK;

   ...

END;

________________________________________

How Exceptions Propagate

When an exception is raised, if PL/SQL cannot find a handler for it in the current block or subprogram, the exception propagates. That is, the exception reproduces itself in successive enclosing blocks until a handler is found or there are no more blocks to search. In the latter case, PL/SQL returns an unhandled exception error to the host environment.

Figure 5 - 1, Figure 5 - 2, and Figure 5 - 3 illustrate the propagation rules.

An exception can propagate beyond its scope, that is, beyond the block in which it was declared. Consider the following example:

DECLARE

   ...

BEGIN

   ...

   ---------------- beginning of sub-block ----------------

   DECLARE

      past_due  EXCEPTION;

   BEGIN

      ...

      IF ... THEN

         RAISE past_due;

      END IF;

      ...

   END;

   ------------------- end of sub-block -------------------

   ...

EXCEPTION

   ...

   WHEN OTHERS THEN

      ROLLBACK;

END;

Because the block in which it was declared has no handler for the exception named past_due, it propagates to the enclosing block. But, according to the scope rules, enclosing blocks cannot reference exceptions declared in a sub-block. So, only an OTHERS handler can catch the exception.

________________________________________

Reraising an Exception

Sometimes, you want to reraise an exception, that is, handle it locally, then pass it to an enclosing block. For example, you might want to roll back a transaction in the current block, then log the error in an enclosing block.

To reraise an exception, simply place a RAISE statement in the local handler, as shown in the following example:

DECLARE

   out_of_balance  EXCEPTION;

BEGIN

   ...

   ---------------- beginning of sub-block ----------------

   BEGIN

      ...

      IF ... THEN

         RAISE out_of_balance;  -- raise the exception

      END IF;

      ...

   EXCEPTION

      WHEN out_of_balance THEN

         -- handle the error

         RAISE;  -- reraise the current exception

      ...

   END;

   ------------------- end of sub-block -------------------

EXCEPTION

   WHEN out_of_balance THEN

      -- handle the error differently

   ...

END;

Omitting the exception name in a RAISE statement-allowed only in an exception handler-reraises the current exception.

________________________________________

Handling Raised Exceptions

When an exception is raised, normal execution of your PL/SQL block or subprogram stops and control transfers to its exception-handling part, which is formatted as follows:

...

EXCEPTION

   WHEN exception_name1 THEN  -- handler

      sequence_of_statements1

   WHEN exception_name2 THEN  -- another handler

      sequence_of_statements2

   ...

   WHEN OTHERS THEN          -- optional handler

      sequence_of_statements3

END;

To catch raised exceptions, you must write exception handlers. Each handler consists of a WHEN clause, which specifies an exception, followed by a sequence of statements to be executed when that exception is raised. These statements complete execution of the block or subprogram-control does not return to where the exception was raised. In other words, you cannot resume processing where you left off.

The optional OTHERS exception handler, which is always the last handler in a block or subprogram, acts as the handler for all exceptions not named specifically. Thus, a block or subprogram can have only one OTHERS handler. Consider the following example:

...

EXCEPTION

   WHEN ... THEN

      -- handle the error

   WHEN ... THEN

      -- handle the error

   ...

   WHEN OTHERS THEN

      -- handle all other errors

END;

Use of the OTHERS handler guarantees that no exception will go unhandled.

If you want two or more exceptions to execute the same sequence of statements, list the exception names in the WHEN clause, separating them by the keyword OR, as follows:

EXCEPTION

   WHEN over_limit OR under_limit OR VALUE_ERROR THEN

      -- handle the error

   ...

If any of the exceptions in the list is raised, the associated sequence of statements is executed. The keyword OTHERS cannot appear in the list of exception names; it must appear by itself. You can have any number of exception handlers, and each handler can associate a list of exceptions with a sequence of statements. However, an exception name can appear only once in the exception-handling part of a PL/SQL block or subprogram.

The usual scope rules for PL/SQL variables apply, so only local and global variables can be referenced in an exception handler. However, when an exception is raised inside a cursor FOR loop, the cursor is closed implicitly before the handler is invoked. So, the values of explicit cursor attributes are not available in the handler.

Exceptions Raised in Declarations

Exceptions can be raised in declarations by a faulty initialization expression. For example, the following declaration implicitly raises the predefined exception VALUE_ERROR because limit cannot store numbers larger than 999:

DECLARE

   limit  CONSTANT  NUMBER(3) := 5000;  -- raises VALUE_ERROR

BEGIN

   ...

EXCEPTION

   WHEN VALUE_ERROR THEN  -- cannot catch the exception

      ...

END;

Handlers in the current block cannot catch the raised exception because an exception raised in a declaration propagates immediately to the enclosing block.

Exceptions Raised in Handlers

Only one exception at a time can be active in the exception-handling part of a block or subprogram. So, an exception raised inside a handler immediately propagates to the enclosing block, which is searched to find a handler for the newly raised exception. From there on, the exception propagates normally.

Branching to or from an Exception Handler

A GOTO statement cannot branch to an exception handler; nor can it branch from an exception handler into the current block. For example, the following GOTO is illegal:

DECLARE

   pe_ratio  NUMBER(3,1);

BEGIN

   DELETE FROM stats WHERE symbol = 'XYZ';

   SELECT price / NVL(earnings, 0) INTO pe_ratio FROM stocks

      WHERE symbol = 'XYZ';

   <<my_label>>

   INSERT INTO stats (symbol, ratio) VALUES ('XYZ', pe_ratio);

EXCEPTION

   WHEN ZERO_DIVIDE THEN

      pe_ratio := 0;

      GOTO my_label;  -- illegal branch into current block

END;

However, a GOTO statement can branch from an exception handler into an enclosing block.

Using SQLCODE and SQLERRM

In an exception handler, you can use the functions SQLCODE and SQLERRM to find out which error occurred and to get the error message.

For internal exceptions, SQLCODE returns the number of the associated ORACLE error. The number that SQLCODE returns is negative unless the ORACLE error is no data found, in which case SQLCODE returns +100. SQLERRM returns the message associated with the ORACLE error that occurred. The message begins with the ORACLE error code.

For user-defined exceptions, SQLCODE returns +1 and SQLERRM returns the message

User-Defined Exception

unless you used the pragma EXCEPTION_INIT to associate the exception name with an ORACLE error number, in which case SQLCODE returns that error number and SQLERRM returns the corresponding error message. The maximum length of an ORACLE error message is 512 characters including the error code, nested messages, and message inserts such as table and column names.

If no exception has been raised, SQLCODE returns zero and SQLERRM returns the message

ORA-0000: normal, successful completion

You can pass an error number to SQLERRM, in which case SQLERRM returns the message associated with that error number. The error number passed to SQLERRM should be negative. Passing a zero to SQLERRM always returns the following message:

ORA-0000: normal, successful completion

Passing a positive number to SQLERRM always returns the message

User-Defined Exception

unless you pass +100, in which case SQLERRM returns this message:

ORA-01403: no data found

In the following example, SQLERRM gives unwanted results because it is passed positive rather than negative numbers:

DECLARE

   msg  CHAR(100);

BEGIN

   FOR num IN 1..9999 LOOP

      msg := SQLERRM(num);  -- should be SQLERRM(-num)

      INSERT INTO errors VALUES (msg);

   END LOOP;

END;

You cannot use SQLCODE or SQLERRM directly in a SQL statement. For example, the following statement is illegal:

INSERT INTO errors VALUES (SQLCODE, SQLERRM);

Instead, you must assign their values to local variables, then use the variables in the SQL statement, as the following example shows:

DECLARE

   err_num  NUMBER;

   err_msg  CHAR(100);

BEGIN

   ...

EXCEPTION

   ...

   WHEN OTHERS THEN

      err_num := SQLCODE;

      err_msg := SUBSTR(SQLERRM, 1, 100);

      INSERT INTO errors VALUES (err_num, err_msg);

END;

The string function SUBSTR ensures that a VALUE_ERROR exception (for truncation) is not raised when you assign the value of SQLERRM to err_msg. SQLCODE and SQLERRM are especially useful in the OTHERS exception handler because they tell you which internal exception was raised.

Unhandled Exceptions

Remember, if it cannot find a handler for a raised exception, PL/SQL returns an unhandled exception error to the host environment, which determines the outcome. For example, in the ORACLE Precompilers environment, any database changes made by a failed SQL statement or PL/SQL block are rolled back.

Unhandled exceptions can affect transactions. Before executing a PL/SQL block or stored subprogram, ORACLE marks an implicit savepoint. If the block or subprogram fails with an unhandled exception, ORACLE rolls back to the savepoint. Thus, any database work done by the block or subprogram is undone.

Unhandled exceptions can also affect subprograms. If you exit a subprogram successfully, PL/SQL assigns values to OUT parameters. However, if you exit with an unhandled exception, PL/SQL does not assign values to OUT parameters. Also, if a stored subprogram fails with an unhandled exception, ORACLE implicitly rolls back all database work done by the subprogram. However, if the subprogram issued a COMMIT before the unhandled exception was raised, only the uncommitted work is rolled back.

You can avoid unhandled exceptions by coding an OTHERS handler at the topmost level of every PL/SQL block and subprogram.

________________________________________

Useful Techniques

In this section, you learn two useful techniques: how to continue after an exception is raised, and how to retry a transaction.

Continuing after an Exception Is Raised

An exception handler lets you recover from an otherwise "fatal" error before exiting a block. But, when the handler completes, the block terminates. You cannot return to the current block from an exception handler. In the following example, if the SELECT INTO statement raises ZERO_DIVIDE, you cannot resume with the INSERT statement:

DECLARE

   pe_ratio  NUMBER(3,1);

BEGIN

   DELETE FROM stats WHERE symbol = 'XYZ';

   SELECT price / NVL(earnings, 0) INTO pe_ratio FROM stocks

      WHERE symbol = 'XYZ';

   INSERT INTO stats (symbol, ratio) VALUES ('XYZ', pe_ratio);

EXCEPTION

   WHEN ZERO_DIVIDE THEN

       ...

END;

Though PL/SQL does not support continuable exceptions, you can still handle an exception for a statement, then continue with the next statement. Just place the statement in its own sub-block with its own exception handlers, as shown in the following example:

DECLARE

   pe_ratio  NUMBER(3,1);

BEGIN

   DELETE FROM stats WHERE symbol = 'XYZ';

   ---------------- beginning of sub-block ----------------

   BEGIN

      SELECT price / NVL(earnings, 0) INTO pe_ratio FROM stocks

         WHERE symbol = 'XYZ';

   EXCEPTION

      WHEN ZERO_DIVIDE THEN

         pe_ratio := 0;

   END;

   ------------------- end of sub-block -------------------

   INSERT INTO stats (symbol, ratio) VALUES ('XYZ', pe_ratio);

EXCEPTION

   ...

END;

If an error occurs in the sub-block, a local handler can catch the exception. When the sub-block terminates, the enclosing block continues to execute at the point where the sub-block ends.

In the last example, if the SELECT INTO statement raises a ZERO_DIVIDE exception, the local handler catches it and sets pe_ratio to zero. Execution of the handler is complete, so the sub-block terminates, and execution continues with the INSERT statement.

Retrying a Transaction

After an exception is raised, rather than abandon your transaction, you might want to retry it. The technique you use is simple. First, encase the transaction in a sub-block. Then, place the sub-block inside a loop that repeats the transaction.

Consider the following example. Before starting the transaction, you mark a savepoint. If the transaction succeeds, you commit, then exit from the loop. If the transaction fails, control transfers to the exception handler, where you roll back to the savepoint undoing any changes, then try to fix the problem.

When the exception handler completes, the sub-block terminates, control transfers to the LOOP statement in the enclosing block, the sub-block starts executing again, and the transaction is retried. You might want to use a FOR or WHILE loop to limit the number of tries.

DECLARE

   name    CHAR(20);

   ans1    CHAR(3);

   ans2    CHAR(3);

   ans3    CHAR(3);

   suffix  NUMBER := 1;

BEGIN

   ...

   LOOP  -- could be "FOR i IN 1..10 LOOP" to allow a

        -- maximum of ten tries

      ---------------- beginning of sub-block ----------------

      BEGIN

         SAVEPOINT start_transaction;  -- mark a savepoint

            /* Remove rows from a table of survey results. */

         DELETE FROM results WHERE answer1 = 'NO';

            /* Add a survey respondent's name and answers. */

         INSERT INTO results VALUES (name, ans1, ans2, ans3);

            -- raises a DUP_VAL_ON_INDEX exception if

            -- two respondents have the same name because

            -- there is a unique index on the name column

         COMMIT;

         EXIT;

      EXCEPTION

         WHEN DUP_VAL_ON_INDEX THEN

            ROLLBACK TO start_transaction;  -- undo changes

            suffix := suffix + 1;             -- try to fix

            name := name || TO_CHAR(suffix);  -- problem

         ...

      END;

      ------------------- end of sub-block -------------------

   END LOOP;

END;


CHAPTER 6. SUBPROGRAMS

Civilization advances by extending the number of important operations that we can perform without thinking about them.

Alfred North Whitehead

This chapter shows you how to use subprograms, which let you name and encapsulate a sequence of statements. Thus, subprograms aid application development by isolating operations. They are like building blocks, which you can use to construct reliable, modular, maintainable applications.

________________________________________

What Are Subprograms?

Subprograms are named PL/SQL blocks that can take parameters and be invoked. PL/SQL has two types of subprograms called procedures and functions. Generally, you use a procedure to perform an action and a function to compute a value.

Like unnamed or anonymous PL/SQL blocks, subprograms have a declarative part, an executable part, and an optional exception-handling part. The declarative part contains declarations of types, cursors, constants, variables, exceptions, and nested subprograms. These objects are local and cease to exist when you exit the subprogram. The executable part contains statements that assign values, control execution, and manipulate ORACLE data. The exception-handling part contains exception handlers, which deal with exceptions raised during execution.

Consider the following procedure named debit_account, which debits a bank account:

PROCEDURE debit_account (acct_id INTEGER, amount REAL) IS

   old_balance  REAL;

   new_balance  REAL;

   overdrawn    EXCEPTION;

BEGIN

   SELECT bal INTO old_balance FROM accts

      WHERE acctno = acct_id;

   new_balance := old_balance - amount;

   IF new_balance < 0 THEN

      RAISE overdrawn;

   ELSE

      UPDATE accts SET bal = new_balance

         WHERE acctno = acct_id;

   END IF;

EXCEPTION

   WHEN overdrawn THEN

      ...

END debit_account;

When invoked or called, this procedure accepts an account number and a debit amount. It uses the account number to select the account balance from the accts database table. Then, it uses the debit amount to compute a new balance. If the new balance is less than zero, an exception is raised; otherwise, the bank account is updated.

Where Are They Allowed?

Subprograms can be defined using any ORACLE tool that supports PL/SQL. They can be declared in PL/SQL blocks, procedures, functions, and packages. However, subprograms must be declared at the end of a declarative section after all other program objects. For example, the following procedure declaration is misplaced:

DECLARE

   PROCEDURE award_bonus (...) IS  -- misplaced; must come last

   BEGIN ... END;

   rating  NUMBER;

   ...

Generally, tools such as SQL*Forms that incorporate the PL/SQL engine can store subprograms locally for later, strictly local execution. However, to become available for general use by all tools, subprograms must be stored in an ORACLE database. For more information, see the section "Stored Subprograms" later in this chapter.

________________________________________

Advantages of Subprograms

Subprograms provide extensibility; that is, they let you tailor the PL/SQL language to suit your needs. For example, if you need a procedure that creates new departments, you can easily write one as follows:

PROCEDURE create_dept (new_dname CHAR, new_loc CHAR) IS

BEGIN

   INSERT INTO dept

      VALUES (deptno_seq.NEXTVAL, new_dname, new_loc);

END create_dept;

Subprograms also provide modularity; that is, they let you break a program down into manageable, well-defined logic modules. This supports top-down design and the stepwise refinement approach to problem solving.

In addition, subprograms promote reusability and maintainability. Once validated, a subprogram can be used with confidence in any number of applications. Furthermore, only the subprogram is affected if its definition changes. This simplifies maintenance and enhancement.

Finally, subprograms aid abstraction, the mental separation from particulars. To use subprograms, you must know what they do, not how they work. Therefore, you can design applications from the top down without worrying about implementation details. Dummy subprograms (stubs) allow you to defer the definition of procedures and functions until you test and debug the main program.

________________________________________

Procedures

A procedure is a subprogram that performs a specific action. You write procedures using the syntax

PROCEDURE name [ (parameter [, parameter, ...]) ] IS

   [local declarations]

BEGIN

   executable statements

[EXCEPTION

   exception handlers]

END [name];

where parameter stands for the following syntax:

var_name [IN | OUT | IN OUT] datatype [{:= | DEFAULT} value]

Unlike the datatype specifier in a variable declaration, the datatype specifier in a parameter declaration must be unconstrained. For example, the following declaration of name is illegal:

PROCEDURE ... (name CHAR(20)) IS  -- illegal; should be CHAR

BEGIN ... END;

A procedure has two parts: the specification and the body. The procedure specification begins with the keyword PROCEDURE and ends with the procedure name or a parameter list. Parameter declarations are optional. Procedures that take no parameters are written without parentheses.

The procedure body begins with the keyword IS and ends with the keyword END followed by an optional procedure name. The procedure body has three parts: a declarative part, an executable part, and an optional exception-handling part.

The declarative part contains local declarations, which are placed between the keywords IS and BEGIN. The keyword DECLARE, which introduces declarations in an anonymous PL/SQL block, is not used. The executable part contains statements, which are placed between the keywords BEGIN and EXCEPTION (or END). At least one statement must appear in the executable part of a procedure. The NULL statement meets this requirement. The exception-handling part contains exception handlers, which are placed between the keywords EXCEPTION and END.

Consider the procedure raise_salary, which increases the salary of an employee:

PROCEDURE raise_salary (emp_id INTEGER, increase REAL) IS

   current_salary  REAL;

   salary_missing  EXCEPTION;

BEGIN

   SELECT sal INTO current_salary FROM emp

      WHERE empno = emp_id;

   IF current_salary IS NULL THEN

      RAISE salary_missing;

   ELSE

      UPDATE emp SET sal = sal + increase

         WHERE empno = emp_id;

   END IF;

EXCEPTION

   WHEN NO_DATA_FOUND THEN

      INSERT INTO emp_audit VALUES (emp_id, 'No such number');

   WHEN salary_missing THEN

      INSERT INTO emp_audit VALUES (emp_id, 'Salary is null');

END raise_salary;

When called, this procedure accepts an employee number and a salary increase amount. It uses the employee number to select the current salary from the emp database table. If the employee number is not found or if the current salary is null, an exception is raised. Otherwise, the salary is updated.

A procedure is called as a PL/SQL statement. For example, the procedure raise_salary might be called as follows:

raise_salary(emp_num, amount);

________________________________________

Functions

A function is a subprogram that computes a value. Functions and procedures are structured alike, except that functions have a RETURN clause. You write functions using the syntax

FUNCTION name [ (argument [, argument, ...]) ] RETURN datatype IS

   [local declarations]

BEGIN

   executable statements

[EXCEPTION

   exception handlers]

END [name];

where argument stands for the following syntax:

var_name [IN | OUT | IN OUT] datatype [{:= | DEFAULT} value]

The datatype specifier in an argument declaration must be unconstrained.

Like a procedure, a function has two parts: the specification and the body. The function specification begins with the keyword FUNCTION and ends with the RETURN clause, which specifies the datatype of the result value. Argument declarations are optional. Functions that take no arguments are written without parentheses.

The function body begins with the keyword IS and ends with the keyword END followed by an optional function name. The function body has three parts: a declarative part, an executable part, and an optional exception-handling part.

The declarative part contains local declarations, which are placed between the keywords IS and BEGIN. The keyword DECLARE is not used. The executable part contains statements, which are placed between the keywords BEGIN and EXCEPTION (or END). One or more RETURN statements must appear in the executable part of a function. The exception-handling part contains exception handlers, which are placed between the keywords EXCEPTION and END.

Consider the function sal_ok, which determines if an employee salary is out of range:

FUNCTION sal_ok (salary REAL, title REAL)

RETURN BOOLEAN IS

   min_sal  REAL;

   max_sal  REAL;

BEGIN

   SELECT losal, hisal INTO min_sal, max_sal FROM sals

      WHERE job = title;

   RETURN (salary >= min_sal) AND (salary <= max_sal);

END sal_ok;

When called, this function accepts an employee salary and job title. It uses the job title to select range limits from the sals database table. The function identifier, sal_ok, is set to a Boolean value by the RETURN statement. If the salary is out of range, sal_ok is set to FALSE; otherwise, sal_ok is set to TRUE.

A function is called as part of an expression. For example, the function sal_ok might be called as follows:

IF sal_ok(new_sal, new_title) THEN

   ...

END IF;

...

promotable := sal_ok(new_sal, new_title) AND (rating > 3);

In both cases, the function identifier is an expression that yields a result.

 Restriction

Calls to user-defined functions can appear in procedural statements, but not in SQL statements. For example, the following INSERT statement is illegal:

DECLARE

   empnum  INTEGER;

   ...

   FUNCTION bonus (emp_id INTEGER) RETURN REAL IS

   BEGIN ... END bonus;

BEGIN

   ...

   INSERT INTO payroll

      VALUES (empnum, ..., bonus(empnum));  -- illegal call

END;

________________________________________

RETURN Statement

The RETURN statement immediately completes the execution of a subprogram and returns control to the caller. Execution then resumes with the statement following the subprogram call. (Do not confuse the RETURN statement with the RETURN clause, which specifies the datatype of the result value in a function specification.)

A subprogram can contain several RETURN statements, none of which need be the last lexical statement. Executing any of them completes the subprogram immediately. However, it is poor programming practice to have multiple exit points in a subprogram.

In procedures, a RETURN statement cannot contain an expression. The statement simply returns control to the caller before the normal end of the procedure is reached.

However, in functions, a RETURN statement must contain an expression, which is evaluated when the RETURN statement is executed. The resulting value is assigned to the function identifier. Observe how the function balance RETURNs the balance of a specified bank account:

FUNCTION balance (acct_id INTEGER) RETURN REAL IS

   acct_bal  REAL;

BEGIN

   SELECT bal INTO acct_bal FROM accts WHERE acctno = acct_id;

   RETURN acct_bal;

END balance;

A function must contain at least one RETURN statement. Otherwise, PL/SQL raises the predefined exception PROGRAM_ERROR at run time.

________________________________________

Forward Declarations

PL/SQL requires that you declare an identifier before using it. Therefore, you must declare a subprogram before calling it. For example, the following declaration of procedure award_bonus is illegal because award_bonus calls procedure calc_rating, which is not yet declared when the call is made:

DECLARE

   PROCEDURE award_bonus (...) IS

   BEGIN

      calc_rating(...);  -- undeclared identifier

      ...

   END;

   PROCEDURE calc_rating (...) IS

   BEGIN

      ...

   END;

   ...

In this case, you can solve the problem easily by placing procedure calc_rating before procedure award_bonus. However, the easy solution does not always work. For example, suppose the procedures are mutually recursive (call each other) or you want to define them in alphabetical order.

PL/SQL solves this problem by providing a special subprogram declaration called a forward declaration. You can use forward declarations to

•	define subprograms in logical or alphabetical order

•	define mutually recursive subprograms (see the section "Recursion" later in this chapter)

•	group subprograms in a package

A forward declaration consists of a subprogram specification terminated by a semicolon. In the next example, the forward declaration advises PL/SQL that the body of procedure calc_rating

can be found later in the block.

DECLARE

   PROCEDURE calc_rating (...);  -- forward declaration

   /* Define subprograms in alphabetical order. */

   PROCEDURE award_bonus (...) IS

   BEGIN

      calc_rating(...);

      ...

   END;

   PROCEDURE calc_rating (...) IS

   BEGIN

      ...

   END;

   ...

Although the formal parameter list appears in the forward declaration, it must also appear in the subprogram body. You can place the subprogram body anywhere after the forward declaration, but they must appear in the same block, subprogram, or package.

Packaged Subprograms

Forward declarations also let you group logically related subprograms in a package. The subprogram specifications go in the package specification, and the subprogram bodies go in the package body, where they are invisible to applications. Thus, packages allow you to hide implementation details. An example follows:

PACKAGE emp_actions IS  -- package specification

   PROCEDURE hire_employee (empno NUMBER, ename CHAR, ...);

   PROCEDURE fire_employee (emp_id NUMBER);

END emp_actions;

PACKAGE BODY emp_actions IS  -- package body

   PROCEDURE hire_employee (empno NUMBER, ename CHAR, ...) IS

   BEGIN

      INSERT INTO emp VALUES (empno, ename, ...);

   END hire_employee;

   PROCEDURE fire_employee (emp_id NUMBER) IS

   BEGIN

      DELETE FROM emp WHERE empno = emp_id;

   END fire_employee;

END emp_actions;

You can define subprograms in a package body without declaring their specifications in the package specification. However, such subprograms can be called only from inside the package. For more information, see Chapter 7.

________________________________________

Actual versus Formal Parameters

Subprograms pass information using parameters. The variables or expressions referenced in the parameter list of a subprogram call are actual parameters. For example, the following procedure call lists two actual parameters named emp_num and amount:

raise_salary(emp_num, amount);

The next procedure call shows that in some cases, expressions can be used as actual parameters:

raise_salary(emp_num, merit + cola);

The variables declared in a subprogram specification and referenced in the subprogram body are formal parameters. For example, the following procedure declares two formal parameters named emp_id and increase:

PROCEDURE raise_salary (emp_id INTEGER, increase REAL) IS

   current_salary  REAL;

   ...

BEGIN

   SELECT sal INTO current_salary FROM emp WHERE empno = emp_id;

   ...

   UPDATE emp SET sal = sal + increase WHERE empno = emp_id;

END raise_salary;

Though not necessary, it is good programming practice to use different names for actual and formal parameters.

When you call procedure raise_salary, the actual parameters are evaluated and the result values are assigned to the corresponding formal parameters. Before assigning the value of an actual parameter to a formal parameter, PL/SQL converts the datatype of the value if necessary. For example, the following call to raise_salary is legal:

raise_salary(emp_num, '2500');

The actual parameter and its corresponding formal parameter must belong to compatible datatypes. For instance, PL/SQL cannot convert between the DATE and REAL datatypes. Also, the result value must be convertible to the new datatype. The following procedure call raises the predefined exception VALUE_ERROR because PL/SQL cannot convert the second actual parameter to a number:

raise_salary(emp_num, '$2500');  -- note the dollar sign

For more information, see the section "Datatype Conversion" in Chapter 2.

________________________________________

Positional and Named Notation

When calling a subprogram, you can write the actual parameters using either positional or named notation. That is, you can indicate the association between an actual and formal parameter by position or name. For example, given the declarations

DECLARE

   acct  INTEGER;

   amt   REAL;

   PROCEDURE credit (acctno INTEGER, amount REAL) IS ...

   ...

you can call the procedure credit in four logically equivalent ways:

BEGIN

   credit(acct, amt);                      -- positional notation

   credit(amount => amt, acctno => acct);  -- named notation

   credit(acctno => acct, amount => amt);  -- named notation

   credit(acct, amount => amt);            -- mixed notation

   ...

END;

Positional Notation

The first procedure call uses positional notation. The PL/SQL compiler associates the first actual parameter, acct, with the first formal parameter, acctno. And, the compiler associates the second actual parameter, amt, with the second formal parameter, amount.

Named Notation

The second procedure call uses named notation. The arrow associates the formal parameter to the left of the arrow with the actual parameter to the right of the arrow.

The third procedure call also uses named notation and shows that you can list the parameter pairs in any order. So, you need not know the order in which the formal parameters are listed.

Mixed Notation

The fourth procedure call shows that you can mix positional and named notation. In this case, the first parameter uses positional notation, and the second parameter uses named notation. Positional notation must precede named notation. The reverse is not allowed. For example, the following procedure call is illegal:

credit(acctno => acct, amt);  -- illegal

________________________________________

Parameter Modes

You use parameter modes to define the behavior of formal parameters. The three parameter modes, IN (the default), OUT, and IN OUT, can be used with any subprogram. However, avoid using the OUT and IN OUT modes with functions. The purpose of a function is to take zero or more arguments and return a single value. It is poor programming practice to have a function return multiple values. Also, functions should be free from side effects, which change the values of variables not local to the subprogram.

IN

An IN parameter lets you pass values to the subprogram being called. Inside the subprogram, an IN parameter acts like a constant. Therefore, it cannot be assigned a value. For example, the following assignment statement causes a compilation error:

PROCEDURE debit_account (acct_id INTEGER, amount REAL) IS

   minimum_purchase  CONSTANT REAL := 10.0;

   service_charge    CONSTANT REAL := 0.50;

BEGIN

   IF amount < minimum_purchase THEN

      amount := amount + service_charge;  -- illegal

   END IF;

...

The actual parameter that corresponds to an IN formal parameter can be a constant, literal, initialized variable, or expression.

Unlike OUT and IN OUT parameters, IN parameters can be initialized to default values. For more information, see the next section, "Parameter Default Values."

OUT

An OUT parameter lets you return values to the caller of a subprogram. Inside the subprogram, an OUT parameter acts like an uninitialized variable. Therefore, its value cannot be assigned to another variable or reassigned to itself. For instance, the following assignment statement causes a compilation error:

PROCEDURE calc_bonus (emp_id INTEGER, bonus OUT REAL) IS

   hire_date  DATE;

BEGIN

   SELECT sal * 0.10, hiredate INTO bonus, hire_date FROM emp

      WHERE empno = emp_id;

   IF MONTHS_BETWEEN(SYSDATE, hire_date) > 60 THEN

      bonus := bonus + 500;  -- syntax error

   END IF;

   ...

The actual parameter that corresponds to an OUT formal parameter must be a variable; it cannot be a constant or expression. For example, the following procedure call is illegal:

calc_bonus(7499, salary + commission);  -- syntax error

PL/SQL checks for this syntax error at compile time to prevent the overwriting of constants and expressions.

An OUT actual parameter can (but need not) have a value before the subprogram is called. However, the value is lost when you call the subprogram. Inside the subprogram, an OUT formal parameter cannot be used in an expression; the only operation allowed on the parameter is to assign it a value.

Before exiting a subprogram, explicitly assign values to all OUT formal parameters. Otherwise, the values of corresponding actual parameters are indeterminate. If you exit successfully, PL/SQL assigns values to the actual parameters. However, if you exit with an unhandled exception, PL/SQL does not assign values to the actual parameters.

IN OUT

An IN OUT parameter lets you pass initial values to the subprogram being called and return updated values to the caller. Inside the subprogram, an IN OUT parameter acts like an initialized variable. Therefore, it can be assigned a value and its value can be assigned to another variable. That means you can use an IN OUT formal parameter as if it were a normal variable. You can change its value or reference the value in any way, as the following example shows:

PROCEDURE calc_bonus (emp_id INTEGER, bonus IN OUT REAL) IS

   hire_date      DATE;

   bonus_missing  EXCEPTION;

BEGIN

   SELECT sal * 0.10, hiredate INTO bonus, hire_date FROM emp

      WHERE empno = emp_id;

   IF bonus IS NULL THEN

      RAISE bonus_missing;

   END IF;

   IF MONTHS_BETWEEN(SYSDATE, hire_date) > 60 THEN

      bonus := bonus + 500;

   END IF;

   ...

EXCEPTION

   WHEN bonus_missing THEN

      ...

END calc_bonus;

The actual parameter that corresponds to an IN OUT formal parameter must be a variable; it cannot be a constant or expression.

Table 6 - 1 summarizes all you need to know about the parameter modes.

IN	OUT	IN OUT

the default	must be specified	must be specified

passes initial

passes values to a 	returns values to 	values to a

subprogram	the caller	subprogram;

returns updated

values to the caller

formal parameter 	formal parameter

formal parameter 	acts like an 	acts like an

acts like a constant	uninitialized 	initialized variable

variable

formal parameter

formal parameter 	cannot be used in 	formal parameter

cannot be assigned a 	an expression; 	should be assigned

value	must be assigned a 	a value

value

actual parameter

can be a constant, 	actual parameter 	actual parameter

initialized variable, 	must be a variable	must be a variable

literal, or expression

Table 6 - 1.  Parameter Modes

________________________________________

Parameter Default Values

As the example below shows, you can initialize IN parameters to default values. That way, you can pass different numbers of actual parameters to a subprogram, accepting or overriding the default values as you please. Moreover, you can add new formal parameters without having to change every call to the subprogram.

PROCEDURE create_dept

   (new_dname CHAR DEFAULT 'TEMP',

    new_loc   CHAR DEFAULT 'TEMP') IS

BEGIN

   INSERT INTO dept

      VALUES (deptno_seq.NEXTVAL, new_dname, new_loc);

END create_dept;

If an actual parameter is not passed, the default value of its corresponding formal parameter is used. Consider the following calls to create_dept:

BEGIN

   ...

   create_dept;

   create_dept('MARKETING');

   create_dept('MARKETING', 'NEW YORK');

   ...

END;

The first call passes no actual parameters, so both default values are used. The second call passes one actual parameter, so the default value for new_loc is used. The third call passes two actual parameters, so neither default value is used.

Usually, you can use positional notation to override the default values of formal parameters. However, you cannot skip a formal parameter by leaving out its actual parameter. For example, the following call incorrectly associates the actual parameter 'NEW YORK' with the formal parameter new_dname:

create_dept('NEW YORK');  -- incorrect

You cannot solve the problem by leaving a placeholder for the actual parameter. For example, the following call is illegal:

create_dept( , 'NEW YORK');  -- illegal

In such cases, you must use named notation, as follows:

create_dept(new_loc => 'NEW YORK');

Remember, positional notation cannot follow named notation.

________________________________________

Aliasing

To optimize execution, the PL/SQL compiler can choose different methods of parameter passing (copy or reference) for a subprogram call. The easy-to-avoid problem of aliasing occurs when the same actual parameter appears twice in a procedure call. Unless both formal parameters are IN parameters, the result is indeterminate because it depends on the methods of parameter passing chosen by the compiler. An example follows:

DECLARE

   str  CHAR(10);

   PROCEDURE reverse (in_str CHAR, out_str OUT CHAR) IS

      ...

   BEGIN

      -- reverse order of characters in string

      ...

      /* At this point, whether the value of in_str     *

       * is 'ABCD' or 'DCBA' depends on the methods of  *

       * parameter passing used by the PL/SQL compiler. */

   END reverse;

   ...

BEGIN

   str := 'ABCD';

   reverse(str, str);  -- indeterminate

   ...

END;

Aliasing also occurs when a global variable appears in a procedure call and then is referenced within the procedure. Consider the following example:

DECLARE

   rent  REAL;

   PROCEDURE raise_rent (increase IN OUT REAL) IS

      ...

   BEGIN

      rent := rent + increase;

      ...

   END raise_rent;

   ...

BEGIN

   ...

   raise_rent(rent);  -- indeterminate

END;

Again, the result is indeterminate.

________________________________________

Overloading

PL/SQL lets you overload subprogram names. That is, you can use the same name for several different subprograms as long as their formal parameters differ in number, order, or datatype family. (Figure 2-1 in Chapter 2 shows the datatype families.)

Suppose you want to initialize the first n rows in two PL/SQL tables that were declared as follows:

DECLARE

   TYPE DateTabTyp IS TABLE OF DATE

      INDEX BY BINARY_INTEGER;

   TYPE RealTabTyp IS TABLE OF REAL

      INDEX BY BINARY_INTEGER;

   hiredate_tab  DateTabTyp;

   sal_tab       RealTabTyp;

   ...

You might write the following procedure to initialize the PL/SQL table named hiredate_tab:

PROCEDURE initialize (tab OUT DateTabTyp, n INTEGER) IS

BEGIN

   FOR i IN 1..n LOOP

      tab(i) := SYSDATE;

   END LOOP;

END initialize;

And, you might write the next procedure to initialize the PL/SQL table named sal_tab:

PROCEDURE initialize (tab OUT RealTabTyp, n INTEGER) IS

BEGIN

   FOR i IN 1..n LOOP

      tab(i) := 0.0;

   END LOOP;

END initialize;

Because the processing in these two procedures is the same, it is logical to give them the same name.

You can place the two overloaded initialize procedures in the same block, subprogram, or package. PL/SQL determines which of the two procedures is being called by checking their formal parameters. Consider the example below. If you call initialize with a DateTabTyp parameter, PL/SQL uses the first version of initialize. But, if you call initialize with a RealTabTyp parameter, PL/SQL uses the second version.

DECLARE

   TYPE DateTabTyp IS TABLE OF DATE

      INDEX BY BINARY_INTEGER;

   TYPE RealTabTyp IS TABLE OF REAL

      INDEX BY BINARY_INTEGER;

   hiredate_tab  DateTabTyp;

   comm_tab      RealTabTyp;

   indx          BINARY_INTEGER;

   ...

BEGIN

   indx := 50;

   initialize(hiredate_tab, indx);  -- calls first version

   initialize(comm_tab, indx);      -- calls second version

   ...

END;

Restrictions

Overloaded subprogram names can appear only in a block, subprogram, or package. In other words, you cannot overload the names of stand-alone subprograms.

You cannot overload two subprograms if their formal parameters differ only in name or parameter mode. For example, you cannot overload the following procedures:

PROCEDURE reconcile (acctno IN INTEGER) IS

BEGIN

   ...

END reconcile;

PROCEDURE reconcile (acctno OUT INTEGER) IS

BEGIN

   ...

END reconcile;

Furthermore, you cannot overload two subprograms if their formal parameters differ only in datatype and the different datatypes are in the same family. For instance, you cannot overload the following procedures because the datatypes INTEGER and REAL are in the same family:

PROCEDURE charge_back (amount INTEGER) IS

BEGIN

   ...

END charge_back;

PROCEDURE charge_back (amount REAL) IS

BEGIN

   ...

END charge_back;

Finally, you cannot overload two functions that differ only in return type (the datatype of the result value) even if the types are in different families. For example, you cannot overload the following functions:

FUNCTION acct_ok (acctno INTEGER) RETURN BOOLEAN IS

BEGIN

   ...

END acct_ok;

FUNCTION acct_ok (acctno INTEGER) RETURN INTEGER IS

BEGIN

   ...

END acct_ok;

How Calls Are Resolved

Figure 6 - 1 shows how the PL/SQL compiler resolves subprogram calls. When the compiler encounters a subprogram call, it tries to find a declaration that matches the call. The compiler searches first in the current scope and then, if necessary, in successive enclosing scopes. The compiler stops searching if it finds one or more subprogram declarations in which the subprogram name matches the name of the called subprogram.

To resolve a call among possibly like-named subprograms at the same level of scope, the compiler must find an exact match between the actual and formal parameters. That is, they must match in number, order, and datatype (unless some formal parameters were assigned default values). If no match is found or if multiple matches are found, the compiler generates a syntax error.

In the following example, you call the enclosing procedure swap from within the function valid. However, the compiler generates an error because neither declaration of swap within the current scope matches the procedure call:

PROCEDURE swap (d1 DATE, d2 DATE) IS

   date1  DATE;

   date2  DATE;

   FUNCTION valid (d DATE) RETURN BOOLEAN IS

      PROCEDURE swap (n1 INTEGER, n2 INTEGER) IS

      BEGIN ... END swap;

      PROCEDURE swap (n1 REAL, n2 REAL) IS

      BEGIN ... END swap;

   BEGIN

      ...

      swap(date1, date2);

   END;

BEGIN

   ...

 Caution

PL/SQL declares built-in functions globally in package STANDARD. Redeclaring them locally is error-prone because your local declaration overrides the global declaration. Consider the following example, in which you declare a function named SIGN, then, within the scope of that declaration, try to call the built-in function SIGN:

DECLARE

   x  NUMBER;

   ...

BEGIN

   DECLARE

      FUNCTION SIGN (n NUMBER) RETURN NUMBER IS

      BEGIN

         IF n < 0 THEN RETURN -1; ELSE RETURN 1; END IF;

      END;

   BEGIN

      ...

      x := SIGN(0);  -- assigns 1 to x

   END;

   ...

   x := SIGN(0);  -- assigns 0 to x

END;

Inside the sub-block, PL/SQL uses your definition of SIGN, not the built-in definition. To call the built-in function from inside the sub-block, you must use dot notation, as follows:

x := STANDARD.SIGN(0);  -- assigns 0 to x

________________________________________

Recursion

Recursion is a powerful technique for simplifying the design of algorithms. Basically, recursion means self-reference. In a recursive mathematical sequence, each term is derived by applying a formula to preceding terms. The Fibonacci sequence (1, 1, 2, 3, 5, 8, 13, 21, ...), which was first used to model the growth of a rabbit colony, is an example. Each term in the sequence (after the second) is the sum of the two terms that immediately precede it.

In a recursive definition, something is defined in terms of simpler versions of itself. Consider the definition of n factorial (n!) (the product of all integers from 1 to n):

n! = n * (n - 1)!

Recursive Subprograms

A recursive subprogram is one that calls itself. Think of a recursive call as a call to some other subprogram that does the same task as your subprogram. Each recursive call creates a new instance of any objects declared in the subprogram, including parameters, variables, cursors, and exceptions. Likewise, new instances of SQL statements are created at each level in the recursive descent.

There must be at least two paths through a recursive subprogram: one that leads to the recursive call and one that does not. That is, at least one path must lead to a terminating condition. Otherwise, the recursion would (theoretically) go on forever. In practice, if a recursive subprogram strays into infinite regress, PL/SQL eventually runs out of memory and raises the predefined exception STORAGE_ERROR.

 An Example

To solve some programming problems, you must repeat a sequence of statements until a condition is met. You can use iteration or recursion to solve such problems. Recursion is appropriate when the problem can be broken down into simpler versions of itself. For example, you can evaluate 3! as follows:

0! = 1

1! = 1 * 0! = 1 * 1 = 1

2! = 2 * 1! = 2 * 1 = 2

3! = 3 * 2! = 3 * 2 = 6

To implement this algorithm, you might write the following recursive function, which returns the factorial of a positive integer:

FUNCTION fac (n POSITIVE) RETURN INTEGER IS  -- returns n!

BEGIN

   IF n = 1 THEN  -- terminating condition

      RETURN 1;

   ELSE

      RETURN n * fac(n - 1);  -- recursive call

   END IF;

END fac;

At each recursive call, n is decremented. Eventually, n becomes 1 and the recursion stops.

 Another Example

Consider the procedure below, which finds the staff of a given manager. The procedure declares two formal parameters, mgr_no and tier, which represent the manager's employee number and a tier in his or her departmental organization. Staff members reporting directly to the manager occupy the first tier. When called, the procedure accepts a value for mgr_no but uses the default value of tier. For example, you might call the procedure as follows:

find_staff(7839);

The procedure passes mgr_no to a cursor in a cursor FOR loop, which finds staff members at successively lower tiers in the organization. At each recursive call, a new instance of the FOR loop is created and another cursor is opened. But, prior cursors stay positioned on the next row in their active sets. When a fetch fails to return a row, the cursor is closed automatically and the FOR loop is exited. Since the recursive call is inside the FOR loop, the recursion stops.

PROCEDURE find_staff (mgr_no NUMBER, tier NUMBER := 1) IS

   boss_name  CHAR(10);

   CURSOR c1 (boss_no NUMBER) IS

      SELECT empno, ename FROM emp WHERE mgr = boss_no;

BEGIN

   /* Get manager's name. */

   SELECT ename INTO boss_name FROM emp WHERE empno = mgr_no;

   IF tier = 1 THEN

      INSERT INTO staff  -- single-column output table

         VALUES (boss_name || ' manages the staff');

   END IF;

   /* Find staff members who report directly to manager. */

   FOR ee IN c1 (mgr_no) LOOP

      INSERT INTO staff

         VALUES (boss_name || ' manages ' || ee.ename

            || ' on tier ' || to_char(tier));

      /* Drop to next tier in organization. */

      find_staff(ee.empno, tier + 1);  -- recursive call

   END LOOP;

   COMMIT;

END;

Unlike the initial call, each recursive call passes a second actual parameter (the next tier) to the procedure.

The last example illustrates recursion, not the efficient use of set-oriented SQL statements. You might want to compare the performance of the recursive procedure to that of the following SQL statement, which does the same task:

INSERT INTO staff

   SELECT PRIOR ename || ' manages ' || ename

      || ' on tier ' || to_char(LEVEL - 1)

   FROM emp

   START WITH empno = 7839

   CONNECT BY PRIOR empno = mgr;

The SQL statement is appreciably faster. However, the procedure is more flexible. For example, a multitable query cannot contain the CONNECT BY clause. So, unlike the procedure, the SQL statement cannot be modified to do joins. (A join combines rows from two or more database tables.) In addition, a procedure can process data in ways that a single SQL statement cannot.

Caution

Be careful where you place a recursive call. If you place it inside a cursor FOR loop or between OPEN and CLOSE statements, another cursor is opened at each call. As a result, your program might exceed the limit set by the ORACLE initialization parameter OPEN_CURSORS.

Mutual Recursion

Subprograms are mutually recursive if they directly or indirectly call each other. In the example below, the Boolean functions odd and even, which determine whether a number is odd or even, call each other directly. The forward declaration of odd is necessary because even calls odd, which is not yet declared when the call is made. (Refer to the section "Forward Declarations" earlier in this chapter.)

FUNCTION odd (n NATURAL) RETURN BOOLEAN;  -- forward declaration

FUNCTION even (n NATURAL) RETURN BOOLEAN IS

BEGIN

   IF n = 0 THEN

      RETURN TRUE;

   ELSE

      RETURN odd(n - 1);  -- mutually recursive call

   END IF;

END even;

FUNCTION odd (n NATURAL) RETURN BOOLEAN IS

BEGIN

   IF n = 0 THEN

      RETURN FALSE;

   ELSE

      RETURN even(n - 1);  -- mutually recursive call

   END IF;

END odd;

When a positive integer n is passed to odd or even, the functions call each other by turns. At each call, n is decremented. Ultimately, n becomes zero and the final call returns TRUE or FALSE. For instance, passing the number 4 to odd results in this sequence of calls:

odd(4)

even(3)

odd(2)

even(1)

odd(0)  -- returns FALSE

On the other hand, passing the number 4 to even results in the following sequence of calls:

even(4)

odd(3)

even(2)

odd(1)

even(0)  -- returns TRUE

Recursion versus Iteration

Unlike iteration, recursion is not essential to PL/SQL programming. Any problem that can be solved using recursion can be solved using iteration. Also, the iterative version of a subprogram is usually easier to design than the recursive version. However, the recursive version is usually simpler, smaller, and therefore easier to debug. Compare the following functions, which compute the nth Fibonacci number:

-- recursive version

FUNCTION fib (n POSITIVE) RETURN INTEGER IS

BEGIN

   IF (n = 1) OR (n = 2) THEN

      RETURN 1;

   ELSE

      RETURN fib(n - 1) + fib(n - 2);

   END IF;

END fib;

-- iterative version

FUNCTION fib (n POSITIVE) RETURN INTEGER IS

   pos1  INTEGER := 1;

   pos2  INTEGER := 0;

   cum   INTEGER;

BEGIN

   IF (n = 1) OR (n = 2) THEN

      RETURN 1;

   ELSE

      cum := pos1 + pos2;

      FOR i IN 3..n LOOP

         pos2 := pos1;

         pos1 := cum;

         cum := pos1 + pos2;

      END LOOP;

      RETURN cum;

   END IF;

END fib;

The recursive version of fib is more elegant than the iterative version. However, the iterative version is more efficient; it runs faster and uses less storage. That is because each recursive call requires additional time and memory. As the number of recursive calls gets larger, so does the difference in efficiency. Still, if you expect the number of recursive calls to be small, you might choose the recursive version for its readability.

________________________________________

Stored Subprograms

The ORACLE Server is an important PL/SQL client. If you have the Procedural Database Extension, subprograms can be compiled separately and stored permanently in an ORACLE database, ready to be executed. This section gives an overview of stored database subprograms. You learn about the environment in which they operate and find out what they allow your applications to do. For details, see the ORACLE7 Server Application Developer's Guide.

Advantages of Stored Subprograms

Stored subprograms offer higher productivity, better performance, memory savings, application integrity, and tighter security.

 Higher Productivity

By designing applications around a library of stored subprograms, you can avoid redundant coding and increase your productivity. For example, suppose various applications call a stored procedure that manages the emp database table. If the management method changes, only the procedure must be revised, not the applications.

 Better Performance

Using subprograms can reduce calls from your application to ORACLE. For example, to execute ten individual SQL statements, ten calls are required, but to execute a subprogram containing ten SQL statements, only one call is required. Reducing calls can boost performance, especially if your application communicates with ORACLE over a network.

 Memory Savings

Stored subprograms take advantage of the ORACLE shared memory capability. So, only one copy of a subprogram need be loaded into memory for execution by multiple users. As a result, your applications require less memory.

 Application Integrity

Stored subprograms improve the integrity and consistency of your applications. By developing all your applications around a library of stored subprograms, you reduce the likelihood of coding errors. For example, a subprogram must be validated only once. Then, it can be used with confidence in any number of applications.

 Tighter Security

Stored subprograms can help enforce data security. Your DBA can restrict users to specific database operations by granting access only through subprograms. For example, your DBA might grant users EXECUTE access to a stored procedure that updates the emp table, but not grant them access to the table itself. That way, users can call the procedure, but cannot arbitrarily manipulate table data.

Calling Stored Subprograms

You can call stored subprograms from a database trigger, another stored subprogram, an ORACLE Precompiler application, an OCI application, or an ORACLE tool such as SQL*Plus.

 From Another Subprogram

A stored subprogram can call another stored subprogram. For instance, the following call to the stand-alone procedure create_dept might appear in the body of a packaged subprogram:

create_dept(name, location);

 From an Application Program

An ORACLE Precompiler or OCI application can call stored subprograms using anonymous PL/SQL blocks. In the following example, you call the stand-alone procedure create_dept from an ORACLE Precompiler program:

EXEC SQL EXECUTE

   BEGIN

      create_dept(:name, :location);

   END;

END-EXEC;

The actual parameters name and location are host variables. In the next example, the procedure create_dept is part of a package named emp_actions, so you must use dot notation to qualify the procedure call:

EXEC SQL EXECUTE

   BEGIN

      emp_actions.create_dept(:name, :location);

   END;

END-EXEC;

 From an ORACLE Tool

You can call stored subprograms interactively from ORACLE tools such as SQL*Plus, SQL*Forms, and SQL*DBA. For example, you might call the stand-alone procedure create_dept from SQL*Plus as follows:

SQL> EXECUTE create_dept('MARKETING', 'NEW YORK');

This call is equivalent to the following call issued from an anonymous PL/SQL block:

SQL> BEGIN create_dept('MARKETING', 'NEW YORK'); END;

 Caution

Before executing a stored subprogram, ORACLE marks an implicit savepoint. If the subprogram fails with an unhandled exception, before returning to the host environment, ORACLE rolls back to the savepoint, undoing any database changes made by the subprogram.

 Restrictions

The body of a stand-alone or packaged subprogram can contain any SQL or PL/SQL statement. However, subprograms participating in a distributed transaction, database triggers, and SQL*Forms applications cannot call stored subprograms that contain a COMMIT, ROLLBACK, or SAVEPOINT statement.

References to stored functions can appear in procedural statements, but not in SQL statements.

Remote Access

You can use the following syntax to call stand-alone and packaged subprograms stored in a remote ORACLE database:

subprogram_name@db_link(param1, param2, ...);

package_name.subprogram_name@db_link(param1, param2, ...);

In the next example, you call the stored procedure raise_salary, which is defined in the package emp_actions in the newyork database:

BEGIN

   emp_actions.raise_salary@newyork(emp_num, amount);

You can create synonyms to provide location transparency for remote stand-alone (but not packaged) subprograms, as the following example shows:

CREATE SYNONYM create_dept FOR create_dept@newyork;

 Restrictions

Stored subprograms executing within the ORACLE Server can call a remote subprogram, but PL/SQL blocks executing in an application cannot. Also, ORACLE assumes that all calls to remote subprograms do an update, which requires a two-phase commit of the transaction. As a result, if the local transaction is rolled back, so is the database work done by the remote subprogram. If the remote subprogram fails, an error might be returned that requires your PL/SQL program to roll back the transaction locally.

Subprograms participating in a distributed transaction cannot call remote subprograms that contain a COMMIT, ROLLBACK, or SAVEPOINT statement.

Subprogram State and Dependency

A stored subprogram is always in one of two states: valid or invalid. A subprogram is valid if neither its source code nor any object it references has been DROPped, REPLACEd, or ALTERed since the subprogram was last compiled. When you call a valid subprogram, ORACLE simply loads its compiled PL/SQL code into the shared SQL cache and executes the code.

On the other hand, a stored subprogram is invalid if its source code or any object it references has been DROPped, REPLACEd, or ALTERed since the subprogram was last compiled.

A stored subprogram that references a database object is said to be dependent on that object. ORACLE invalidates a subprogram if any object on which it depends has been DROPped, REPLACEd, or ALTERed since the subprogram was last compiled.

An invalid subprogram must be recompiled before it can be executed. Recompilation occurs in two phases. First, ORACLE determines if any referenced subprograms or packages are themselves invalid. If so, they must be recompiled. This can lead to a cascade of recompilations, all of which must succeed; otherwise, ORACLE returns a runtime error and the subprogram remains invalid. Second, the referencing subprogram is recompiled, after which it can be executed.

For more information about subprogram state and dependency, see the ORACLE7 Server Application Developer's Guide.

Creating Stored Subprograms

The Procedural Database Extension allows you to CREATE subprograms and store them permanently in an ORACLE database for general use. You can issue the CREATE PROCEDURE and CREATE FUNCTION statements interactively from SQL*Plus or SQL*DBA. For example, you might CREATE the procedure fire_employee as follows:

CREATE PROCEDURE fire_employee (emp_id NUMBER) AS

BEGIN

   DELETE FROM emp WHERE empno = emp_id;

END;

Notice that when creating subprograms, you use the keyword AS instead of IS in the specification. For the full syntax of the CREATE statement, see the ORACLE7 Server SQL Language Reference Manual.

When you CREATE a subprogram for storage in the database, ORACLE automatically compiles the source code, caches the object code in a shared SQL area in the System Global Area (SGA), and stores the source and object code in the data dictionary. The object code stays cached in the SGA, where it can be executed quickly. When necessary, ORACLE applies a least-recently-used algorithm that selects shared SQL areas to be flushed from the SGA to make room for others.

When you call a stored subprogram, ORACLE checks to see if an existing shared SQL area holds the object code for that subprogram. If not, ORACLE allocates a shared SQL area and loads the subprogram object code into it. Then, ORACLE allocates a private SQL area, which holds session-specific subprogram values. If multiple users execute a subprogram simultaneously, only one shared SQL area is used, but multiple private SQL areas are maintained-one for each user.

SQL statements within the subprogram are processed in the same way. They use shared SQL areas to hold their parsed representations, and private SQL areas to hold session-specific information. The shared SQL area used by a subprogram is called a parent cursor; the shared SQL areas used by SQL statements within the subprogram are called child cursors.


CHAPTER 7. PACKAGES

Good as it is to inherit a library, it is better to collect one.

Augustine Birrell

This chapter shows you how to bundle related PL/SQL programming constructs into a package. The packaged constructs might include a collection of procedures, or a pool of type definitions and variable declarations. For example, a Human Resources package might include hiring and firing procedures. Once written, your general-purpose package is compiled, then stored in an ORACLE database, where, like a library unit, its contents can be shared by many applications.

Note: Packages can be stored in an ORACLE database only if you have the procedural database extension.

________________________________________

What Is a Package?

A package is a database object that groups logically related PL/SQL types, objects, and subprograms. Packages usually have two parts, a specification and a body, although sometimes the body is unnecessary. The specification is the interface to your applications; it declares the types, variables, constants, exceptions, cursors, and subprograms available for use. The body fully defines cursors and subprograms, and so implements the specification.

Unlike subprograms, packages cannot be called, passed parameters, or nested. Still, the format of a package is similar to that of a subprogram:

PACKAGE name IS  -- specification (visible part)

   -- public type and object declarations

   -- subprogram specifications

END [name];

PACKAGE BODY name IS  -- body (hidden part)

   -- private type and object declarations

   -- subprogram bodies

[BEGIN

   -- initialization statements]

END [name];

The specification holds public declarations, which are visible to your application. The body holds implementation details and private declarations, which are hidden from your application.

Think of the specification as an operational interface and of the body as a "black box" (see Figure 7 - 1).

You can debug, enhance, or replace a package body without changing the interface (package specification) to the package body.

Packages are created interactively with SQL*Plus or SQL*DBA using the CREATE PACKAGE and CREATE PACKAGE BODY commands. In the following example, a record type, a cursor, and two employment procedures are packaged:

CREATE PACKAGE emp_actions AS  -- specification

   TYPE EmpRecTyp IS RECORD (emp_id INTEGER, salary REAL);

   CURSOR desc_salary (emp_id NUMBER) RETURN EmpRecTyp;

   PROCEDURE hire_employee(

      ename   CHAR,

      job     CHAR,

      mgr     NUMBER,

      sal     NUMBER,

      comm    NUMBER,

      deptno  NUMBER);

   PROCEDURE fire_employee (emp_id NUMBER);

END emp_actions;

CREATE PACKAGE BODY emp_actions AS  -- body

   CURSOR desc_salary (emp_id NUMBER) RETURN EmpRecTyp IS

      SELECT empno, sal FROM emp ORDER BY sal DESC;

   PROCEDURE hire_employee(

      ename   CHAR,

      job     CHAR,

      mgr     NUMBER,

      sal     NUMBER,

      comm    NUMBER,

      deptno  NUMBER) IS

   BEGIN

      INSERT INTO emp VALUES (empno_seq.NEXTVAL, ename, job,

         mgr, SYSDATE, sal, comm, deptno);

   END hire_employee;

   PROCEDURE fire_employee (emp_id NUMBER) IS

   BEGIN

      DELETE FROM emp WHERE empno = emp_id;

   END fire_employee;

END emp_actions;

Notice that the procedure hire_employee uses the database sequence empno_seq and the function SYSDATE to INSERT a new employee number and hire date, respectively.

Only the declarations in the package specification are visible and accessible to applications. Implementation details in the package body are hidden and inaccessible. So, you can change the body (implementation) without having to recompile calling programs.

________________________________________

Advantages of Packages

Packages offer several advantages: modularity, easier application design, information hiding, added functionality, and better performance.

 Modularity

Packages let you encapsulate logically related types, objects, and subprograms in a named PL/SQL module. Each package is easy to understand, and the interfaces between packages are simple, clear, and well defined. This aids application development.

 Easier Application Design

When designing an application, all you need initially is the interface information in the package specifications. You can code and compile a specification without its body. Once the specification has been compiled, stored subprograms that reference the package can be compiled as well. You need not define the package bodies fully until you are ready to complete the application.

 Information Hiding

With packages, you can specify which types, objects, and subprograms are public (visible and accessible) or private (hidden and inaccessible). For example, if a package contains four subprograms, three might be public and one private. The package hides the definition of the private subprogram so that only the package (not your application) is affected if the definition changes. This simplifies maintenance and enhancement. Also, by hiding implementation details from users, you protect the integrity of the package.

 Added Functionality

Packaged public variables and cursors persist for the duration of a session. So, they can be shared by all procedures that execute in the environment. Also, they allow you to maintain data across transactions without having to store it in the database.

 Better Performance

When you call a packaged subprogram for the first time, the whole package is loaded into memory. Therefore, subsequent calls to related subprograms in the package require no disk I/O.

In addition, packages stop cascading dependencies and so avoid unnecessary recompiling. For example, if you change the definition of a stand-alone function, ORACLE must recompile all stored subprograms that call the function. However, if you change the definition of a packaged function, ORACLE need not recompile the calling subprograms because they do not depend on the package body.

________________________________________

The Package Specification

The package specification contains public declarations. The scope of these declarations is local to your database schema and global to the package. So, the declared objects are accessible from your application and from anywhere in the package. Figure 7 - 2 illustrates the scoping.

The specification lists the package resources available to applications. All the information your application needs to use the resources is in the specification. For example, the following declaration shows that the function named fac takes one argument of type INTEGER and returns a value of type INTEGER:

FUNCTION fac (n INTEGER) RETURN INTEGER;  -- returns n!

That is all the information you need to call the function. You need not consider the underlying implementation of fac (whether it is iterative or recursive, for example).

Only subprograms and cursors have an underlying implementation or definition. So, if a specification declares only types, constants, variables, and exceptions, the package body is unnecessary. An example of such a package follows:

-- package consisting of a specification only

PACKAGE trans_data IS

   TYPE TimeTyp IS RECORD

      (minute  SMALLINT,

       hour    SMALLINT);

   TYPE TransTyp IS RECORD(

      category  VARCHAR2,

      account   INTEGER,

      amount    REAL,

      time      TimeTyp);

   minimum_balance     CONSTANT REAL := 10.00;

   number_processed    INTEGER;

   insufficient_funds  EXCEPTION;

END trans_data;

The package trans_data needs no body because types, constants, variables, and exceptions do not have an underlying implementation. Such packages let you define global variables-usable by subprograms and triggers-that persist throughout a session.

Referencing Package Contents

To reference the types, objects, and subprograms declared within a package specification, you use dot notation as follows:

package_name.type_name

package_name.object_name

package_name.subprogram_name

You can reference package contents from database triggers, stored subprograms, embedded PL/SQL blocks, and anonymous PL/SQL blocks sent to ORACLE interactively by SQL*Plus or SQL*DBA. In the following example, you reference the packaged variable minimum_balance, which is declared in the package trans_data:

DECLARE

   new_balance  REAL;

   ...

BEGIN

   ...

   IF new_balance < trans_data.minimum_balance THEN

      ...

   END IF;

   ...

________________________________________

The Package Body

The package body implements the package specification. That is, the package body contains the definition of every cursor and subprogram declared in the package specification. Keep in mind that subprograms defined in a package body are accessible outside the package only if their specifications also appear in the package specification.

The package body can also contain private declarations, which define types and objects necessary for the internal workings of the package. The scope of these declarations is local to the package body. Therefore, the declared types and objects are inaccessible except from within the package body. Unlike a package specification, the declarative part of a package body can contain subprogram bodies.

Following the declarative part of a package body is the optional initialization part, which typically holds statements that initialize some of the variables previously declared in the package.

The initialization part of a package plays a minor role because, unlike subprograms, a package cannot be called or passed parameters. As a result, the initialization part of a package is run only once, the first time you reference the package.

________________________________________

Some Examples

Consider the package below named emp_actions. The package specification declares the following types, objects, and subprograms:

•	types EmpRecTyp and DeptRecTyp

•	functions hire_employee, nth_highest_salary, and rank

•	procedures fire_employee and raise_salary

•	cursor desc_salary

•	exception salary_missing

After writing the package, you can develop applications that reference its types, call its subprograms, use its cursor, or raise its exception. When you CREATE the package, it is stored in an ORACLE database for general use.

PACKAGE emp_actions IS

   /* Declare externally visible types, cursor, exception. */

   TYPE EmpRecTyp IS RECORD (emp_id INTEGER, salary REAL);

   TYPE DeptRecTyp IS RECORD (dept_id INTEGER, location CHAR);

   CURSOR desc_salary RETURN EmpRecTyp;

   salary_missing  EXCEPTION;

   /* Declare externally callable subprograms. */

   FUNCTION hire_employee(

      ename   CHAR,

      job     CHAR,

      mgr     INTEGER,

      sal     NUMBER,

      comm    NUMBER,

      deptno  INTEGER) RETURN INTEGER;

   PROCEDURE fire_employee (emp_id INTEGER);

   PROCEDURE raise_salary (emp_id INTEGER, increase NUMBER);

   FUNCTION nth_highest_salary (n INTEGER) RETURN EmpRecTyp;

END emp_actions;

PACKAGE BODY emp_actions IS

   number_hired  INTEGER;  -- visible only in this package

   /* Fully define cursor specified in package. */

   CURSOR desc_salary RETURN EmpRecTyp IS

      SELECT empno, sal FROM emp ORDER BY sal DESC;

   /* Fully define subprograms specified in package. */

   FUNCTION hire_employee(

      ename   CHAR,

      job     CHAR,

      mgr     INTEGER,

      sal     NUMBER,

      comm    NUMBER,

      deptno  INTEGER) RETURN INTEGER IS

      new_empno  INTEGER;

   BEGIN

      SELECT empno_seq.NEXTVAL INTO new_empno FROM DUAL;

      INSERT INTO emp VALUES (new_empno, ename, job,

         mgr, SYSDATE, sal, comm, deptno);

      number_hired := number_hired + 1;

      RETURN new_empno;

   END hire_employee;

   PROCEDURE fire_employee (emp_id INTEGER) IS

   BEGIN

      DELETE FROM emp WHERE empno = emp_id;

   END fire_employee;

   PROCEDURE raise_salary (emp_id INTEGER, increase NUMBER) IS

      current_salary  NUMBER;

   BEGIN

      SELECT sal INTO current_salary FROM emp

         WHERE empno = emp_id;

      IF current_salary IS NULL THEN

         RAISE salary_missing;

      ELSE

         UPDATE emp SET sal = sal + increase

            WHERE empno = emp_id;

      END IF;

   END raise_salary;

   FUNCTION nth_highest_salary (n INTEGER) RETURN EmpRecTyp IS;

      emp_rec  EmpRecTyp;

   BEGIN

      OPEN desc_salary;

      FOR i IN 1..n LOOP

         FETCH desc_salary INTO emp_rec;

         EXIT WHEN desc_salary%NOTFOUND;

      END LOOP;

      CLOSE desc_salary;

      RETURN emp_rec;

   END nth_highest_salary;

   /* Define local function, available only in package. */

   FUNCTION rank (emp_id INTEGER, job_title CHAR)

      RETURN INTEGER IS

   /* Return rank (highest = 1) of employee in a given *

    * job classification based on performance rating.  */

      head_count  INTEGER;

      score       NUMBER;

   BEGIN

      SELECT COUNT(*) INTO head_count FROM emp

         WHERE job = job_title;

      SELECT rating INTO score FROM reviews

         WHERE empno = emp_id;

      score := score / 100;  -- maximum score is 100

      RETURN (head_count + 1) - ROUND(head_count * score);

   END rank;

BEGIN  -- initialization part starts here

   INSERT INTO emp_audit VALUES (SYSDATE, USER, 'EMP_ACTIONS');

   number_hired := 0;

END emp_actions;

Remember, the initialization part of a package is run just once, the first time you reference the package. So, in the last example, only one row is inserted into the database table emp_audit. Likewise, the variable number_hired is initialized only once. Every time the procedure hire_employee is called, the variable number_hired is updated. However, the count kept by number_hired is session-specific. That is, the count reflects the number of new employees processed by one user, not the number processed by all users.

In the next example, some typical bank transactions are packaged. Assume that debit and credit transactions are entered after business hours via automatic teller machines, then applied to accounts the next morning.

PACKAGE bank_transactions IS

   /* Declare externally visible constant. */

   minimum_balance  CONSTANT NUMBER := 100.00;

   /* Declare externally callable procedures. */

   PROCEDURE apply_transactions;

   PROCEDURE enter_transaction(

      acct    NUMBER,

      kind    CHAR,

      amount  NUMBER);

END bank_transactions;

PACKAGE BODY bank_transactions IS

   /* Declare global variable to hold transaction status. */

   new_status  VARCHAR2(70) := 'Unknown';

   /* Use forward declarations because

      apply_transactions calls credit_account

      and debit_account, which are not yet

      declared when the calls are made. */

   PROCEDURE credit_account (acct NUMBER, credit REAL);

   PROCEDURE debit_account (acct NUMBER, debit REAL);

   /* Fully define procedures specified in package. */

   PROCEDURE apply_transactions IS

   /* Apply pending transactions in transactions table *

    * to accounts table.  Use cursor to fetch rows.    */

      CURSOR trans_cursor IS

         SELECT acct_id, kind, amount FROM transactions

            WHERE status = 'Pending'

            ORDER BY time_tag

            FOR UPDATE OF status;  -- to lock rows

   BEGIN

      FOR trans IN trans_cursor LOOP

         IF trans.kind = 'D' THEN

            debit_account(trans.acct_id, trans.amount);

         ELSIF trans.kind = 'C' THEN

            credit_account(trans.acct_id, trans.amount);

         ELSE

            new_status := 'Rejected';

         END IF;

         UPDATE transactions SET status = new_status

            WHERE CURRENT OF trans_cursor;

      END LOOP;

   END apply_transactions;

   PROCEDURE enter_transaction(

   /* Add a transaction to transactions table. */

      acct    NUMBER,

      kind    CHAR,

      amount  NUMBER) IS

   BEGIN

      INSERT INTO transactions

         VALUES (acct, kind, amount, 'Pending', SYSDATE);

   END enter_transaction;

   /* Define local procedures, available only in package. */

   PROCEDURE do_journal_entry(

   /* Record transaction in journal. */

      acct     NUMBER,

      kind     CHAR,

      new_bal  NUMBER) IS

   BEGIN

      INSERT INTO journal

         VALUES (acct, kind, new_bal, sysdate);

      IF kind = 'D' THEN

         new_status := 'Debit applied';

      ELSE

         new_status := 'Credit applied';

      END IF;

   END do_journal_entry;

   PROCEDURE credit_account (acct NUMBER, credit REAL) IS

   /* Credit account unless account number is bad. */

      old_balance  NUMBER;

      new_balance  NUMBER;

   BEGIN

      SELECT balance INTO old_balance FROM accounts

         WHERE acct_id = acct

         FOR UPDATE OF balance;  -- to lock the row

      new_balance := old_balance + credit;

      UPDATE accounts SET balance = new_balance

         WHERE acct_id = acct;

      do_journal_entry(acct, 'C', new_balance);

   EXCEPTION

      WHEN NO_DATA_FOUND THEN

         new_status := 'Bad account number';

      WHEN OTHERS THEN

         new_status := SUBSTR(SQLERRM,1,70);

   END credit_account;

   PROCEDURE debit_account (acct NUMBER, debit REAL) IS

   /* Debit account unless account number is bad or *

    * account has insufficient funds.               */

      old_balance         NUMBER;

      new_balance         NUMBER;

      insufficient_funds  EXCEPTION;

   BEGIN

      SELECT balance INTO old_balance FROM accounts

         WHERE acct_id = acct

         FOR UPDATE OF balance;  -- to lock the row

      new_balance := old_balance - debit;

      IF new_balance >= minimum_balance THEN

         UPDATE accounts SET balance = new_balance

            WHERE acct_id = acct;

         do_journal_entry(acct, 'D', new_balance);

      ELSE

         RAISE insufficient_funds;

      END IF;

   EXCEPTION

      WHEN NO_DATA_FOUND THEN

         new_status := 'Bad account number';

      WHEN insufficient_funds THEN

         new_status := 'Insufficient funds';

      WHEN OTHERS THEN

         new_status := SUBSTR(SQLERRM,1,70);

   END debit_account;

END bank_transactions;  -- no initialization part

In this package, the initialization part is not used.

________________________________________

Private versus Public Objects

Look again at the package emp_actions. The package body declares a variable named number_hired, which is initialized to zero. Unlike items declared in the specification of emp_actions, items declared in the body are restricted to use within the package. Therefore, PL/SQL code outside the package cannot reference the variable number_hired. Such items are termed private.

However, items declared in the specification of emp_actions such as the exception salary_missing are visible outside the package. Therefore, any PL/SQL code can reference the exception salary_missing. Such items are termed public.

When you must maintain items throughout a session or across transactions, place them in the declarative part of the package body. For example, the value of number_hired is retained between calls to hire_employee. Remember, however, that the value of number_hired is session-specific.

If, in addition, you must make the items public, place them in the package specification. For example, the constant minimum_balance declared in the specification of the package bank_transactions is available for general use.

________________________________________

Overloading

Recall from Chapter 6 that PL/SQL allows two or more packaged subprograms to have the same name. This option is useful when you want a subprogram to accept parameters that belong to different types. For example, the following package defines two procedures named journalize:

PACKAGE journal_entries IS

   PROCEDURE journalize (amount NUMBER, trans_date CHAR);

   PROCEDURE journalize (amount NUMBER, trans_date NUMBER );

END journal_entries;

PACKAGE BODY journal_entries IS

   PROCEDURE journalize (amount NUMBER, trans_date CHAR) IS

   BEGIN

      INSERT INTO journal

         VALUES (amount, TO_DATE(trans_date, 'DD-MON-YYYY'));

   END journalize;

   PROCEDURE journalize (amount NUMBER, trans_date NUMBER) IS

   BEGIN

      INSERT INTO journal

         VALUES (amount, TO_DATE(trans_date, 'J'));

   END journalize;

END journal_entries;

The first procedure accepts trans_date as a character string, while the second procedure accepts it as a number (the Julian day). Yet, each procedure handles the data appropriately.

________________________________________

Calling Packaged Subprograms

Packaged subprograms must be referenced using dot notation, as the following example shows:

emp_actions.hire_employee(name, title, ...);

This tells the PL/SQL compiler that hire_employee is found in the package emp_actions.

You can call packaged subprograms from a database trigger, another stored subprogram, an ORACLE Precompiler application, an OCI application, or an ORACLE tool such as SQL*Plus. Some examples follow.

 From Another Stored Subprogram

A stored subprogram can call a packaged subprogram. For instance, the following call to the packaged procedure hire_employee might appear in a stand-alone subprogram:

emp_actions.hire_employee(name, title, ...);

 From an Application Program

An ORACLE Precompiler or OCI application can call packaged subprograms using anonymous PL/SQL blocks. In the following example, you call the packaged procedure hire_employee from an ORACLE Precompiler program:

EXEC SQL EXECUTE

   BEGIN

      emp_actions.hire_employee(:name, :title, ...);

   END;

END-EXEC;

The actual parameters name and title are host variables.

 From an ORACLE Tool

You can call packaged subprograms interactively from ORACLE tools such as SQL*Plus, SQL*Forms, and SQL*DBA. For example, you might call the packaged procedure hire_employee as follows:

SQL> EXECUTE emp.actions.hire_employee('TATE', 'CLERK', ...);

Caution

Before executing a packaged subprogram, ORACLE marks an implicit savepoint. If the subprogram fails with an unhandled exception, before returning to the host environment, ORACLE rolls back to the savepoint, undoing any database changes made by the subprogram.

Restriction

The body of a packaged subprogram can contain any SQL or PL/SQL statement. However, subprograms participating in a distributed transaction, database triggers, and SQL*Forms applications cannot call packaged subprograms that contain a COMMIT, ROLLBACK, or SAVEPOINT statement.

Remote Access

You can use the following syntax to call packaged subprograms stored in a remote ORACLE database:

package_name.subprogram_name@db_link(param1, param2, ...);

In the following example, you call the packaged procedure hire_employee in the newyork database:

emp_actions.hire_employee@newyork(name, title, ...);

________________________________________

Package State and Dependency

A package specification is always in one of two states: valid or invalid. A package specification is valid if neither its source code nor any object it references has been DROPped, REPLACEd, or ALTERed since the package specification was last compiled.

On the other hand, a package specification is invalid if its source code or any object it references has been DROPped, REPLACEd, or ALTERed since the package specification was last compiled. When it invalidates a package specification, ORACLE also invalidates any objects that reference the package.

A package body is subject to the same rules, except that ORACLE can recompile a package body without invalidating its corresponding package specification. This feature limits the extent to which invalidations result in cascading recompilations.

Session Characteristics

Variables, constants, and cursors declared in a package have the following unique characteristics:

•	Every session has its own set of packaged variables, constants, and cursors.

•	In a session, the first time you reference a package, its variables and cursor parameters are null unless you initialize them.

•	During a session, the package user can change the values of packaged variables and cursor parameters. When a session ends, the values are lost and must be reinitialized when the next session begins.

Declare variables and cursors in a package only when you want them to persist throughout a session.

Dependency

When a package specification is recompiled, ORACLE invalidates dependent objects. These include stand-alone or packaged subprograms that call or reference objects declared in the recompiled package specification. If you call or reference a dependent object before it is recompiled, ORACLE automatically recompiles it at run time.

When a package body is recompiled, ORACLE determines if objects on which the package body depends are valid. These include stand-alone subprograms and package specifications called or referenced by a procedure or cursor defined in the recompiled package body. If any of these objects are invalid, ORACLE recompiles them before recompiling the package body. If ORACLE can recompile it successfully, the package body becomes valid. Otherwise, ORACLE returns a runtime error and the package body remains invalid. Compilation errors are stored in the data dictionary with the package.

ORACLE stores the package specification and body separately in the data dictionary. Other objects that call or reference global package objects depend only on the package specification. Therefore, you can redefine objects in the package body (which causes the body to be recompiled) without causing ORACLE to invalidate their dependent objects.

For more information about package dependency, see the ORACLE7 Server Application Developer's Guide.

________________________________________

Package STANDARD

A package named STANDARD defines the PL/SQL environment. The package specification globally declares types, exceptions, and subprograms, which are available automatically to every PL/SQL program. For example, package STANDARD declares the following built-in function named ABS, which returns the absolute value of its argument:

FUNCTION ABS (n NUMBER) RETURN NUMBER;

The contents of package STANDARD are directly visible to applications. So, you can call ABS from a database trigger, a stored subprogram, an ORACLE Precompiler application, an OCI application, and a variety of ORACLE tools including SQL*Forms, SQL*Menu, SQL*Plus, and SQL*ReportWriter.

If you redeclare ABS in a PL/SQL program, your local declaration overrides the global declaration. However, you can still call the built-in function by using dot notation, as follows:

... STANDARD.ABS(x) ...

Most built-in functions are overloaded. For example, package STANDARD contains the following declarations:

FUNCTION TO_CHAR (right DATE) RETURN VARCHAR2;

FUNCTION TO_CHAR (left NUMBER) RETURN VARCHAR2;

FUNCTION TO_CHAR (left DATE, right VARCHAR2) RETURN VARCHAR2;

FUNCTION TO_CHAR (left NUMBER, right VARCHAR2) RETURN VARCHAR2;

PL/SQL resolves a call to TO_CHAR by matching the number and datatypes of the formal and actual parameters.

________________________________________

Product-specific Packages

To help you build PL/SQL-based applications, the ORACLE Server and several ORACLE tools supply packages containing product-specific subprograms. For instance, SQL*Forms supplies a package named SQLFORMS. For information about product-specific packages, see the product reference manual.

ORACLE Environment

The ORACLE Server is an important PL/SQL client. A package named DBMS_STANDARD provides language facilities that help your application interact with ORACLE. For example, this package provides a procedure named raise_application_error, which lets you issue user-defined error messages. That way, you can report errors to an application and avoid returning unhandled exceptions. The calling syntax is

raise_application_error(error_number, error_message);

where error_number is a negative integer in the range -20000 .. -20999 and error_message is a character string up to 2048 bytes in length. Package DBMS_STANDARD is an extension of package STANDARD, so you need not qualify references to it.

An application can call raise_application_error only from an executing stored subprogram. When called, raise_application_error ends the subprogram, rolls back any database changes it made, and returns a user-defined error number and message to the application. The error number and message can be trapped like any ORACLE error. An example follows:

PROCEDURE raise_salary (emp_id NUMBER, increase NUMBER) IS

   current_salary  NUMBER;

BEGIN

   SELECT sal INTO current_salary FROM emp

      WHERE empno = emp_id;

   IF current_salary IS NULL THEN

      raise_application_error(-20101, 'Salary is missing');

   ELSE

      UPDATE emp SET sal = current_salary + increase

         WHERE empno = emp_id;

   END IF;

END raise_salary;

The calling application gets a PL/SQL exception, which it can process using the error-reporting functions SQLCODE and SQLERRM in an OTHERS handler. Furthermore, it can use EXCEPTION_INIT to map specific error numbers returned by raise_application_error to exceptions of its own, as follows:

EXEC SQL EXECUTE

   DECLARE

      ...

      null_salary  EXCEPTION;

      PRAGMA EXCEPTION_INIT(null_salary, -20101);

   BEGIN

      ...

      raise_salary(:emp_number, :amount);

   EXCEPTION

      WHEN null_salary THEN

         INSERT INTO emp_audit VALUES (:emp_number, ...);

      ...

   END;

END-EXEC;

This technique allows the calling application to handle error conditions in specific exception handlers.

Typically, raise_application_error is used in database triggers. For an example, see the section "Database Triggers" in Chapter 4.

________________________________________

Guidelines

When writing packages, keep them as general as possible so they can be reused in future applications. Avoid writing packages that duplicate some feature already provided by ORACLE.

Package specifications reflect the design of your application. So, define them before the package bodies. Place in a specification only the types, objects, and subprograms that must be visible to users of the package. That way, other developers cannot misuse the package by basing their code on irrelevant implementation details.

To reduce the need for recompiling when code is changed, place as few items as possible in a package specification. Changes to a package body do not require ORACLE to recompile dependent procedures. However, changes to a package specification require ORACLE to recompile every stored subprogram that references the package.


CHAPTER 8. EXECUTION ENVIRONMENTS

Every tool carries with it the spirit by which it was created.

Werner Heisenberg

You can use PL/SQL with a variety of application development tools including

•	ORACLE Call Interfaces

•	ORACLE Precompilers

•	SQL*DBA

•	SQL*Forms

•	SQL*Menu

•	SQL*Module

•	SQL*Plus

•	SQL*ReportWriter

This chapter shows you how to use PL/SQL in the SQL*Plus, ORACLE Precompiler, and OCI environments.

Note: PL/SQL does not support I/O, so with interactive tools like SQL*Plus, you must use a database table to hold result values.

________________________________________

SQL*Plus Environment

After entering the SQL*Plus environment, if you have the transaction processing option, you can use PL/SQL in several ways:

•	input and store a PL/SQL block

•	input and run a PL/SQL block

•	create a script containing PL/SQL blocks

•	load and run a script containing PL/SQL blocks

•	call a stored subprogram

Inputting an Anonymous Block

Every PL/SQL block begins with the reserved word DECLARE or, if the block has no declarative part, with the reserved word BEGIN. Inputting either reserved word at the SQL*Plus prompt (SQL>) signals SQL*Plus to

•	clear the SQL buffer

•	enter INPUT mode

•	ignore semicolons (the SQL statement terminator)

SQL*Plus expects you to input an unlabeled PL/SQL block, so you cannot start with a block label.

You input the rest of the PL/SQL block line by line. Ending the block with a period (.) on a line by itself stores the block in the SQL buffer.

You can save your PL/SQL block in a script file as follows:

SQL> SAVE <filename>

If you want to edit the file, you can use the SQL*Plus line editor. For instructions, see the SQL*Plus User's Guide. After editing the file, you can save it again as follows:

SQL> SAVE <filename> REPLACE

Executing an Anonymous Block

After inputting a PL/SQL block, you need not end it with a period. Ending the block with a slash (/) on a line by itself stores the block in the SQL buffer, then runs the block.

Once it is stored in the SQL buffer, you can run the PL/SQL block again as follows:

SQL> RUN

or

SQL> /

When the block is finished running, you are returned to the SQL*Plus prompt. The SQL buffer is not cleared until you start inputting the next SQL statement or PL/SQL block.

Creating a Script

You can use your favorite editor to create text files containing PL/SQL blocks. Although SQL*Plus statements are not allowed in a PL/SQL block, you can intermix them with PL/SQL blocks in a text file. In the example below, a PL/SQL block is intermixed with SQL*Plus statements that set up and display a report. Note that a slash (/) must follow every PL/SQL block.

CLEAR BREAKS;

CLEAR COLUMNS;

COLUMN ENAME HEADING NAME;

TTITLE 'CLERICAL STAFF';

DECLARE

   avg_sal  NUMBER(7,2);

BEGIN

   SELECT AVG(sal) INTO avg_sal FROM emp;

   IF avg_sal < 1500 THEN

      UPDATE emp SET sal = sal * 1.05 WHERE job = 'CLERK';

   END IF;

END;

/

SELECT ENAME, SAL FROM EMP WHERE JOB = 'CLERK';

The two CLEAR statements get rid of any settings left over from a previous report. The COLUMN statement changes the ENAME column heading to NAME. The TTITLE statement specifies a title that appears at the top of each page in the report. The slash following END executes the PL/SQL block.

Loading and Running a Script

After invoking SQL*Plus, you can load a script into the SQL buffer as follows:

SQL> GET <filename>

Once it is stored in the SQL buffer, you can run the script using the RUN command or a slash. If you prefer, you can load and run the script in one step, as follows:

SQL> START <filename>

Your PL/SQL block can take advantage of the SQL*Plus substitution variable feature. Before running a script, SQL*Plus prompts for the value of any variable prefixed with an ampersand (&). In the following example, SQL*Plus prompts for the value of num_rows:

BEGIN

   ...

   FOR i IN 1..&num_rows LOOP

      ...

   END LOOP;

END;

Calling Stored Subprograms

From SQL*Plus, you can call stand-alone and packaged subprograms stored in a local or remote database. For example, you might call the local stand-alone procedure create_dept as follows:

SQL> EXECUTE create_dept('ADVERTISING', 'NEW YORK');

This call is equivalent to the following call issued from an anonymous PL/SQL block:

SQL> BEGIN create_dept('ADVERTISING', 'NEW YORK'); END;

In the next example, you use the database link newyork to call the remote stored procedure raise_salary:

SQL> EXECUTE raise_salary@newyork(7499, 1500);

You can create synonyms to provide location transparency for remote stand-alone procedures.

________________________________________

ORACLE Precompiler Environment

The ORACLE Precompilers allow you to embed PL/SQL blocks within programs written in any of the following high-level languages:

•	Ada

•	C

•	COBOL

•	FORTRAN

•	Pascal

•	PL/I

Such programs and languages are called host programs and host languages, respectively.

After writing a program, you precompile the source file. The precompiler checks the program for syntax errors, then generates a modified source file, which can be compiled, linked, and executed in the usual way.

Embedding PL/SQL Blocks

You can embed a PL/SQL block wherever you can embed a SQL statement; the precompiler treats them alike. To embed a PL/SQL block in your host program, you must place the block between the keywords EXEC SQL EXECUTE and END-EXEC, as follows:

EXEC SQL EXECUTE

   BEGIN

      ...

   END;

END-EXEC;

Be sure to follow the keyword END-EXEC with the host-language statement terminator.

Using Host Variables

You use host variables to pass values and status codes back and forth between a host program and an embedded PL/SQL block. Both the host program and the PL/SQL block can set and reference the value of a host variable.

The value of an input host variable is set by the host program and referenced by ORACLE. Conversely, the value of an output host variable is set by ORACLE and referenced by the host program.

You declare host variables in the program Declare Section using regular host language syntax. Inside a PL/SQL block, the scope of host variables is global.

All references to host variables in a PL/SQL block must be prefixed with a colon. That way, the precompiler can tell host variables from PL/SQL variables and database objects.

 Some Examples

The Pro*C program below illustrates the use of host variables in a PL/SQL block. The program prompts the user for the name of an employee, then passes the name to an embedded PL/SQL block, which uses the name to query an ORACLE database. Finally, the results of the query are passed back to the host program, which displays them.

-- available online in file EXAMP9

#include <stdio.h>

EXEC SQL BEGIN DECLARE SECTION;

   VARCHAR   empname[11];

   VARCHAR   jobtype[9];

   VARCHAR   hired[9];

   int       salary;

   int       dept;

   int       worked_longer;

   int       higher_sal;

   int       total_in_dept;

   VARCHAR   uid[20];

   VARCHAR   pwd[20];

EXEC SQL END DECLARE SECTION;

EXEC SQL INCLUDE SQLCA;

main()

{

      /* Set up userid and password */

   strcpy (uid.arr,"scott");

   uid.len = strlen(uid.arr);

   strcpy (pwd.arr,"tiger");

   pwd.len = strlen(pwd.arr);

   printf("\n\n\tEmbedded PL/SQL Demo\n\n");

   printf("Trying to connect...");

   EXEC SQL WHENEVER SQLERROR GOTO errprint;

      /* Connect to ORACLE */

   EXEC SQL CONNECT :uid IDENTIFIED BY :pwd;

   printf(" connected.\n");

   for (;;) /* Loop infinitely */

      {

      printf("\n** Name of employee? (<return> to end)  ");

      gets(empname.arr);                 /* Get the name      */

      if (strlen(empname.arr) == 0)      /* No name entered,  */

         {

         EXEC SQL COMMIT WORK RELEASE;  /* so log off ORACLE */

         exit(0);                       /* and exit program  */

         }

      empname.len = strlen(empname.arr);

      jobtype.len = 9;

      hired.len = 9;

      /* ---------------------------------- */

      /* ----- Begin the PL/SQL block ----- */

      /* ---------------------------------- */

      EXEC SQL EXECUTE

      BEGIN

         SELECT job, hiredate, sal, deptno

            INTO :jobtype, :hired, :salary, :dept FROM emp

            WHERE ename = UPPER(:empname);

            /* Get number of people whose length of *

             * service is longer                    */

         SELECT COUNT(*) INTO :worked_longer FROM emp

            WHERE hiredate < :hired;

            /* Get number of people with a higher salary */

         SELECT COUNT(*) INTO :higher_sal FROM emp

            WHERE sal > :salary;

            /* Get number of people in the same department */

         SELECT COUNT(*) INTO :total_in_dept FROM emp

            WHERE deptno = :dept;

      END;

      END-EXEC;

      /* -------------------------------- */

      /* ----- End the PL/SQL block ----- */

      /* -------------------------------- */

         /* Properly terminate character strings *

          * returned by ORACLE                   */

      jobtype.arr[jobtype.len] = '\0';

      hired.arr[hired.len] = '\0';

         /* Display all the information */

      printf("\n%s's job is: %s\n", empname.arr,

         jobtype.arr);

      printf("Hired on: %s\n", hired.arr);

      printf("    %d people have served longer\n",

         worked_longer);

      printf("Salary is: %d\n", salary);

      printf("    %d people have a higher salary\n"

         higher_sal);

      printf("Department number is: %d\n", dept);

      printf("    %d people in the department\n",

         total_in_dept);

   }   /* End of loop */

errprint:

      /* We end up here if an error occurs */

   EXEC SQL WHENEVER SQLERROR CONTINUE;

   printf("\n\n>>>>> Error during execution:\n");

      /* Print ORACLE error message and log off the database */

   printf("%s\n",sqlca.sqlerrm.sqlerrmc);

   EXEC SQL ROLLBACK RELEASE;

   exit(1);

}

Notice that the host variable empname is assigned a value before the PL/SQL block is entered and that the other host variables (jobtype, hired, and so on) are assigned values inside the block. When necessary, ORACLE converts between its internal datatypes and standard host-language datatypes.

The next Pro*C example shows how two PL/SQL banking transactions might be implemented:

-- available online in file EXAMP10

#include <stdio.h>

EXEC SQL BEGIN DECLARE SECTION;

   int      acct, amount;

   VARCHAR  tran_type[10];

   VARCHAR  status[65];

   VARCHAR  uid[20];

   VARCHAR  pwd[20];

EXEC SQL END DECLARE SECTION;

EXEC SQL INCLUDE SQLCA;

main()

{

   strcpy (uid.arr,"scott");

   uid.len=strlen(uid.arr);

   strcpy (pwd.arr,"tiger");

   pwd.len=strlen(pwd.arr);

   printf("\n\n\tEmbedded PL/SQL Demo\n\n");

   printf("Trying to connect...");

   EXEC SQL WHENEVER SQLERROR GOTO errprint;

   EXEC SQL CONNECT :uid IDENTIFIED BY :pwd;

   printf(" connected.\n");

   for (;;)  /* Loop infinitely */

      {

      printf("\n\n** What is the account number? (-1 to end)");

      scanf("%d", &acct);

      if (acct == -1)    /* Need to disconnect from ORACLE */

      {                  /* and end program if acct is -1  */

         EXEC SQL COMMIT RELEASE;

         exit(0);

      }

      printf("\n   What type of transaction? (C)redit or

         (D)ebit   ");

      scanf("%s", &tran_type.arr);

      tran_type.len = 1;   /* Only want the first character */

      printf("\n   What is the transaction amount? (Whole

         dollars only)  ");

      scanf("%d", &amount);

      /* ---------------------------------- */

      /* ----- Begin the PL/SQL block ----- */

      /* ---------------------------------- */

      EXEC SQL EXECUTE

      DECLARE

         old_bal     NUMBER(11,2);

         no_account  EXCEPTION;

      BEGIN

         :tran_type := UPPER(:tran_type);

         IF :tran_type = 'C' THEN       -- credit the account

            UPDATE accounts SET bal = bal + :amount

               WHERE account_id = :acct;

            IF SQL%ROWCOUNT = 0 THEN    -- no rows affected

               RAISE no_account;

            ELSE

               :status := 'Credit complete.';

            END IF;

         ELSIF :tran_type = 'D' THEN    -- debit the account

            SELECT bal INTO old_bal FROM accounts

               WHERE account_id = :acct;

            IF old_bal >= :amount THEN  -- there is enough

                                        -- money

                UPDATE accounts SET bal = bal - :amount

                   WHERE account_id = :acct;

               :status := 'Debit complete.';

            ELSE

               :status := 'Not enough funds.';

            END IF;

         ELSE

            :status := :tran_type || ' is not a legal

                transaction.';

         END IF;

         COMMIT;

      EXCEPTION

         WHEN NO_DATA_FOUND OR no_account THEN

            :status := 'Account does not exist.';

         WHEN OTHERS THEN

            :status := 'Error: ' || SQLERRM(SQLCODE);

      END;

      END-EXEC;

      /* -------------------------------- */

      /* ----- End the PL/SQL block ----- */

      /* -------------------------------- */

   status.arr[status.len] = '\0';  /* null-terminate the string */

   printf("\n\n   Status: %s", status.arr);

   }  /* End of loop */

errprint:

   EXEC SQL WHENEVER SQLERROR CONTINUE;

   printf("\n\n>>>>> Error during execution:\n");

   printf("%s\n",sqlca.sqlerrm.sqlerrmc);

   EXEC SQL ROLLBACK RELEASE;

   exit(1);

}

Using Indicator Variables

You can associate any host variable with an optional indicator variable. An indicator variable is an integer variable that indicates the value or condition of a host variable. You use indicator variables to assign nulls to input host variables and to detect nulls or truncated values in output host variables.

For input host variables, the values your program can assign to an indicator variable have the following meanings:

-1	ORACLE will ignore the value of the host variable and assign a null to the database column.

w0	ORACLE will assign the value of the host variable to the database column.

For output host variables, the values ORACLE can assign to an indicator variable have the following meanings:

-1	The database column contains a null, so the value of the host variable is indeterminate.

0	ORACLE assigned an intact column value to the host variable.

>0	ORACLE assigned a truncated column value to the host variable. The integer returned by the indicator variable is the original length of the column value.

An indicator variable must be defined in the Declare Section as a 2-byte integer and, in SQL statements, must be prefixed with a colon and appended to its host variable.

A host language needs indicator variables because it cannot manipulate nulls. PL/SQL meets this need by allowing an embedded PL/SQL block to accept nulls from the host program and return nulls or truncated values to it.

In the following Pro*COBOL example, the PL/SQL block uses an indicator variable to return a null status code to the host program:

EXEC SQL EXECUTE

   BEGIN

      SELECT ENAME, COMM

         INTO :EMP-NAME, :COMMISSION:COMM-IND

         FROM EMP

         WHERE EMPNO = :EMP-NUMBER

      ...

   END;

END-EXEC.

MOVE COMMISSION TO COMMISSION-OUT.

DISPLAY "Commission: "

   WITH NO ADVANCING.

IF COMM-IND = -1

*  if the value returned by an indicator variable is -1,

*  the value of its output host variable is null

   DISPLAY "N/A"

ELSE

   DISPLAY COMMISSION-OUT.

Inside a PL/SQL block, an indicator variable must be prefixed with a colon and appended to its host variable.

You cannot refer to an indicator variable by itself. Furthermore, if you refer to a host variable with its indicator variable, you must always refer to it that way in the same block. In the next example, because the host variable appears with its indicator variable in the SELECT statement, it must also appear that way in the IF statement:

EXEC SQL EXECUTE

   BEGIN

      ...

      SELECT ename, job

         INTO :ename_host, :job_host:job_ind

         FROM emp

         WHERE empno = :empno_host;

      ...

      IF :job_host:job_ind IS NULL THEN

         RAISE status_unknown;

      END IF;

      ...

   END;

END-EXEC;

Although you cannot refer directly to indicator variables inside a PL/SQL block, PL/SQL checks their values upon entering the block and sets their values correctly upon exiting the block.

 Nulls

Upon entering a block, if an indicator variable has a value of -1, PL/SQL assigns a null to the host variable. Upon exiting the block, if a host variable is null, PL/SQL assigns a value of -1 to the indicator variable. In the following example, the exception name_missing is raised if the indicator variable ename_ind had a value of -1 before the PL/SQL block was entered:

EXEC SQL EXECUTE

   BEGIN

      ...

      IF :ename_host:ename_ind IS NULL THEN

         RAISE name_missing;

      END IF;

      ...

   EXCEPTION

      WHEN name_missing THEN

         ...

   END;

END-EXEC;

 Truncated Values

PL/SQL does not raise an exception when a truncated string value is assigned to a host variable. However, if you use an indicator variable, PL/SQL sets it to the original length of the string. In the following example, the host program will be able to tell, by checking the value of ename_ind, if a truncated value was assigned to ename_host:

EXEC SQL EXECUTE

   DECLARE

      new_ename  CHAR(10);

      ...

   BEGIN

      ...

      :ename_host:ename_ind := new_ename;

      ...

   END;

END-EXEC;

Using the VARCHAR Pseudotype

You can use the VARCHAR pseudotype to declare variable-length character strings. (A pseudotype is a datatype not native to your host language.) VARCHAR variables have a 2-byte length field followed by a 65533-byte string field. For example, the Pro*C Precompiler expands the declaration

EXEC SQL BEGIN DECLARE SECTION;

   VARCHAR   my_ename[10]

EXEC SQL END DECLARE SECTION;

into the following data structure:

struct {

   unsigned short  len;

   unsigned char   arr[10];

}  my_ename;

To get the length of a VARCHAR, simply refer to its length field. You need not use a string function or character-counting algorithm.

ORACLE automatically sets the length field of a VARCHAR output host variable. However, to use a VARCHAR output host variable in your PL/SQL block, you must initialize the length field before entering the PL/SQL block. So, set the length field to the declared (maximum) length of the VARCHAR, as shown in the following Pro*C example:

EXEC SQL BEGIN DECLARE SECTION;

   int      my_empno;

   VARCHAR  my_ename[10]   /* declare variable-length string */

   float    my_sal;

   ...

EXEC SQL END DECLARE SECTION;

   ...

   my_ename.len = 10;   /* initialize length field */

   EXEC SQL EXECUTE

      BEGIN

         SELECT ename, sal INTO :my_ename, :my_sal

            FROM emp

            WHERE empno = :my_empno;

         ...

      END;

   END-EXEC;

   ...

For more information about VARCHARs, see the relevant supplement to the Programmer's Guide to the ORACLE Precompilers.

Using the DECLARE TABLE Statement

If an embedded PL/SQL block refers to a database table that does not yet exist, the precompiler generates an error. To avoid such errors, you can use the DECLARE TABLE statement to tell the precompiler what the table will look like. In the following Pro*C example, you declare the dept table:

EXEC SQL DECLARE dept TABLE(

   deptno  NUMBER(2),

   dname   CHAR(14),

   loc     CHAR(13));

If you use DECLARE TABLE to define a table that already exists, the precompiler uses your definition, ignoring the one in the ORACLE data dictionary. Note that you cannot use the DECLARE TABLE statement inside a PL/SQL block.

Using the SQLCHECK Option

The ORACLE Precompilers can help you debug a program by checking the syntax and semantics of embedded SQL statements and PL/SQL blocks. You control the level of checking by entering the SQLCHECK option inline or on the command line. You can specify the following values for SQLCHECK:

•	SEMANTICS

•	SYNTAX

•	NONE

However, if you embed PL/SQL blocks in your program, you must specify SQLCHECK=SEMANTICS. When SQLCHECK=SEMANTICS, the precompiler checks the syntax and semantics of SQL data manipulation statements, host variable datatypes, and PL/SQL blocks.

The precompiler gets information needed for the semantic check by using embedded DECLARE TABLE statements or, if you specify the USERID option on the command line, by connecting to ORACLE and accessing the data dictionary. You need not connect to ORACLE if every database table referenced in a SQL statement or PL/SQL block is defined by a DECLARE TABLE statement.

Using Host Arrays with PL/SQL Tables

You can pass input host arrays and indicator arrays to a PL/SQL block. They can be indexed by a PL/SQL variable of type BINARY_INTEGER or by a host variable compatible with that type. Normally, the entire host array is passed to PL/SQL, but you can use the ARRAYLEN statement (discussed later) to specify a smaller array dimension.

Furthermore, you can use a procedure call to assign all the values in a host array to rows in a PL/SQL table. Given that the array subscript range is m .. n, the corresponding PL/SQL table index range is always  1 .. n - m + 1. For example, if the array subscript range is 5 .. 10, the corresponding PL/SQL table index range is 1 .. (10 - 5 + 1) or 1 .. 6.

In the Pro*C example below, you pass a host array named salary to a PL/SQL block, which uses the host array in a function call. The function's formal parameters include a PL/SQL table named num_tab. The function call assigns all the values in the actual parameter salary to rows in the formal parameter num_tab.

#include <stdio.h>

main()

{

   /* Declare host array */

   EXEC SQL BEGIN DECLARE SECTION;

      ...

      float  salary [100];

   EXEC SQL END DECLARE SECTION;

   /* Populate host array */

   ...

   EXEC SQL EXECUTE

   DECLARE

      TYPE NumTabTyp IS TABLE OF REAL

         INDEX BY BINARY_INTEGER;

      mid_salary  REAL;

      n  BINARY_INTEGER := 100;

      FUNCTION median (num_tab NumTabTyp, n INTEGER)

         RETURN REAL IS

      BEGIN

          -- compute median

      END;

   BEGIN

      mid_salary := median(:salary, n);  -- pass array

      ...

   END;

   END-EXEC;

   ...

}

You can also use a procedure call to assign all row values in a PL/SQL table to corresponding elements in a host array. See Sample Program 6 in Appendix B.

Table 8 - 1 shows the legal conversions between row values in a PL/SQL table and elements in a host array. For example, a host array of type LONG is compatible with a PL/SQL table of type LONG, LONG RAW, RAW, or VARCHAR2. Notably, it is not compatible with a PL/SQL table of type CHAR.

HOST ARRAY

PL/SQL	CHAR	DATE	LONG	LONG	NUMBER	RAW	ROWID	VARCHAR2

TABLE	RAW

CHAR	Yes

DATE	Yes

LONG	Yes	Yes	Yes	Yes

LONGRAW	Yes	Yes	Yes	Yes

NUMBER	Yes

RAW	Yes	Yes	Yes	Yes

ROWID	Yes

VARCHAR2	Yes	Yes	Yes	Yes

Table 8 - 1.  Legal Datatype Conversions

The ORACLE Precompilers do not check your usage of host arrays. For instance, no index range-checking is done.

 ARRAYLEN Statement

Suppose you must pass an input host array to a PL/SQL block for processing. By default, when binding such a host array, the ORACLE Precompilers use its declared dimension. However, you might not want to process the entire array, in which case you can use the ARRAYLEN statement to specify a smaller dimension. ARRAYLEN associates the host array with a host variable, which stores the smaller dimension.

Let us repeat the last example, but use ARRAYLEN to override the default dimension of host array salary:

#include <stdio.h>

main()

{

   /* Declare host array */

   EXEC SQL BEGIN DECLARE SECTION;

      ...

      float  salary [100];

      int    my_dim;

      EXEC SQL ARRAYLEN salary (my_dim);

   EXEC SQL END DECLARE SECTION;

   /* Populate host array */

   ...

   /* Set smaller host array dimension */

   my_dim = 25;

   EXEC SQL EXECUTE

   DECLARE

      TYPE NumTabTyp IS TABLE OF REAL

         INDEX BY BINARY_INTEGER;

      mid_salary  REAL;

      FUNCTION median (num_tab NumTabTyp, n INTEGER)

         RETURN REAL IS

      BEGIN

         -- compute median

      END;

   BEGIN

      mid_salary := median(:salary, :my_dim);  -- pass array

      ...

   END;

   END-EXEC;

   ...

}

Only 25 array elements are passed to the PL/SQL block because ARRAYLEN downsizes the host array from 100 to 25 elements. As a result, when the PL/SQL block is sent to ORACLE for execution, a much smaller host array is sent along. This saves time and, in a networked environment, reduces network traffic.

The following Pro*C example shows how values are assigned to host array elements and how individual array elements are referenced:

#include <stdio.h>

...

main()

{

   /* Declare host and indicator arrays */

   EXEC SQL BEGIN DECLARE SECTION;

      float  sal [100];

      float  comm [100];

      short  icomm [100];

      int    i = 50;

   EXEC SQL END DECLARE SECTION;

   EXEC SQL EXECUTE

   DECLARE

      TYPE SalTabTyp IS TABLE OF emp.sal%TYPE

         INDEX BY BINARY_INTEGER;

      TYPE CommTabTyp IS TABLE OF emp.comm%TYPE

         INDEX BY BINARY_INTEGER;

      sal_tab   SalTabTyp;

      comm_tab  CommTabTyp;

      j         BINARY_INTEGER := 0;

      ...

   BEGIN

      /* Load salaries and commissions into PL/SQL tables */

      FOR emprec IN (SELECT sal, comm FROM emp) LOOP

         j := j + 1;

         sal_tab(j) := emprec.sal;

         comm_tab(j) := emprec.comm;

      END LOOP;

      /* Process the PL/SQL tables */

      ...

      /* Assign row values to host arrays */

      WHILE :i > 0 LOOP

         :sal(:i) := sal_tab(:i);

         /* if comm is assigned a null, icomm is assigned -1 */

         :comm:icomm(:i) := comm_tab(:i);

         :i := :i - 1;

      END LOOP;

   END;

   END-EXEC;

   ...

}

Using Dynamic SQL

Unlike static SQL statements, dynamic SQL statements are not embedded in your source program. Instead, they are stored in character strings input to (or built by) the program at run time. For example, they might be entered interactively or read from a file.

The ORACLE Precompilers treat a PL/SQL block like a single SQL statement. So, like a SQL statement, a PL/SQL block can be stored in a string host variable for processing by dynamic SQL commands.

However, recall from Chapter 2 that you cannot use single-line comments in a PL/SQL block that will be processed dynamically. Instead, use multiline comments.

Following is a brief look at how PL/SQL is used with dynamic SQL Methods 1, 2, and 4. For more information, see the Programmer's Guide to the ORACLE Precompilers.

 With Method 1

If your PL/SQL block contains no host variables, you can use Method 1 to EXECUTE the PL/SQL string in the usual way. In the following Pro*C example, you prompt the user for a PL/SQL block, store it in a string host variable named user_block, then execute it:

main()

{

   printf("\nEnter a PL/SQL block: ");

   scanf("%s", user_block);

   EXEC SQL EXECUTE IMMEDIATE :user_block;

   ...

When you store a PL/SQL block in a string host variable, omit the keywords EXEC SQL EXECUTE, the keyword END-EXEC, and the statement terminator.

 With Method 2

If your PL/SQL block contains a known number of input and output host variables, you can use dynamic SQL Method 2 to PREPARE and EXECUTE the PL/SQL string in the usual way. In the Pro*C example below, the PL/SQL block uses one host variable named my_empno. The program prompts the user for a PL/SQL block, stores it in a string host variable named user_block, then prepares and executes the block:

main()

{

   printf("\nEnter a PL/SQL block: ");

   scanf("%s", user_block);

   EXEC SQL PREPARE my_block FROM :user_block;

   EXEC SQL EXECUTE my_block USING :my_empno;

   ...

Note that my_block is an identifier used by the precompiler, not a host or program variable.

The precompiler treats all PL/SQL host variables as input host variables whether they serve as input or output host variables (or both) inside the PL/SQL block. So, you must put all host variables in the USING clause.

When the PL/SQL string is EXECUTEd, host variables in the USING clause replace corresponding placeholders in the PREPAREd string. Although the precompiler treats all PL/SQL host variables as input host variables, values are assigned correctly. Input (program) values are assigned to input host variables, and output (column) values are assigned to output host variables.

 With Method 4

If your PL/SQL block contains an unknown number of input or output host variables, you must use Method 4. To do so, you set up a bind descriptor for all the input and output host variables. Executing the DESCRIBE BIND VARIABLES statement stores information about input and output host variables in the bind descriptor.

For full coverage of Method 4, see the relevant supplement to the Programmer's Guide to the ORACLE Precompilers.

Mimicking Dynamic SQL

Without dynamic SQL, you cannot use PL/SQL variables in a query to specify database columns. Consider the SELECT statement below, which does not assign a value from the ename database column to the variable my_ename. If the emp table has a column named colx, a value from that column is assigned to my_ename. If the table has no such column, the value of PL/SQL variable colx (that is, the string value 'ename') is assigned to my_ename.

DECLARE

   colx      CHAR(10);

   my_ename  CHAR(10);

   ...

BEGIN

   colx := 'ename';

   SELECT colx INTO my_ename FROM emp WHERE ...

   ...

END;

However, you can mimic dynamic SQL by using the DECODE function. In the following example, the data returned depends on the value of my_column:

DECLARE

   my_column  CHAR(10);

   my_data    emp.ename%TYPE;

BEGIN

   ...

   my_column := 'hiredate';

   ...

   SELECT DECODE(my_column, 'ename', ename,

       'hiredate', TO_CHAR(hiredate, 'ddmmyy'), 'empno', empno)

       INTO my_data FROM emp WHERE ... ;

END;

The value that DECODE returns is always forced to the datatype of the first result expression. In this example, the first result expression is ename, which belongs to type CHAR, so the returned value is forced to type CHAR. Thus, my_data is correctly declared as emp.ename%TYPE.

You can use this technique in many environments. For example, it works in SQL*Forms, SQL*Menu, and SQL*Plus.

Calling Stored Subprograms

To call a stored subprogram from a host program, you must use an anonymous PL/SQL block. In the following example, you call the stand-alone procedure create_dept:

EXEC SQL EXECUTE

   BEGIN

       create_dept(:number, :name, :location);

   END;

END-EXEC;

Notice that the actual parameters number, name, and location are host variables.

In the next example, the procedure create_dept is part of a package named emp_actions, so you must use dot notation to qualify the procedure call:

EXEC SQL EXECUTE

   BEGIN

       emp_actions.create_dept(:number, :name, :location);

   END;

END-EXEC;

________________________________________

OCI Environment

The OCIs process SQL statements and PL/SQL blocks similarly with one exception. Inside a PL/SQL block, you must use the OBNDRV call, not ODEFIN, to bind all placeholders in a SQL or PL/SQL statement. This holds for both input and output placeholders. The ODEFIN call is not supported for PL/SQL blocks.

In PL/SQL, all queries must have an INTO clause containing placeholders (host variables and/or PL/SQL variables) that correspond to items in the select list. For example, the following SELECT statement is not valid inside a PL/SQL block:

SELECT ename, sal FROM emp;

Instead, it must be coded as follows:

SELECT ename, sal INTO :my_ename, :my_sal FROM emp;

In the last statement, my_ename and my_sal are SQL placeholders that correspond to the ename and sal columns in the select list. You must bind these placeholders using the OBNDRV call.

Also, you must use named placeholders such as my_ename in PL/SQL blocks. Numbered placeholders such as 10 and the corresponding OBNDRN call are not yet supported for PL/SQL blocks.

 A Complete Example

The OCI program below, which is written in C, shows how two PL/SQL banking transactions might be implemented. For listings of the header files ocidfn.h and ocidem.h, see the Programmer's Guide to the ORACLE Call Interfaces.

#include <stdio.h>

#include <string.h>

#include <stdlib.h>

#define ANSI

#include "ocidfn.h"

#include "ocidem.h"

cda_def cda;

lda_def lda;

char  hda[256];

char  sqlstm[2048];

void  error_handler(struct cda_def *);

main()

{

   int    acct_number;

   char   trans_type[1];

   float  trans_amt;

   char   status[80];

   if (orlon(&lda, hda, "scott/tiger", -1, (char *) 0, -1, -1))

   {

      printf("Connect failed.\n");

      exit(EXIT_FAILURE);

   }

   if (oopen(&cda, &lda, (char *) 0, -1, -1, (char *) 0, -1))

   {

      printf("Error opening cursor.  Exiting...\n");

      exit(EXIT_FAILURE);

   }

   printf("\nConnected to ORACLE.\n");

   /* Construct a PL/SQL block. */

   strcpy(sqlstm, "DECLARE\

         old_bal      NUMBER(9,2);\

         err_msg      CHAR(70);\

         nonexistent  EXCEPTION;\

      BEGIN\

         :xtrans_type := UPPER(:xtrans_type);\

         IF :xtrans_type = 'C' THEN\

            UPDATE ACCTS SET BAL = BAL + :xtrans_amt\

               WHERE ACCTID = :xacct_number;\

            IF SQL%ROWCOUNT = 0 THEN\

               RAISE nonexistent;\

            ELSE\

               :xstatus := 'Credit applied';\

            END IF;\

         ELSIF :xtrans_type = 'D' THEN\

            SELECT BAL INTO old_bal FROM accts\

               WHERE acctid = :xacct_number;\

            IF old_bal = :xtrans_amt THEN\

               UPDATE accts SET bal = bal - :xtrans_amt\

                  WHERE acctid = :xacct_number;\

               :xstatus := 'Debit applied';\

            ELSE\

               :xstatus := 'Insufficient funds';\

            END IF;\

         ELSE\

            :xstatus := 'Invalid type: ' || :xtrans_type;\

         END IF;\

         COMMIT;\

      EXCEPTION\

         WHEN NO_DATA_FOUND OR nonexistent THEN\

            :xstatus := 'Nonexistent account';\

         WHEN OTHERS THEN\

            err_msg := SUBSTR(SQLERRM, 1, 70);\

            :xstatus := 'Error: ' || err_msg;\

      END;");

   /* Parse the PL/SQL block. */

   if (oparse(&cda, sqlstm, -1, 0, 2))

   {

      error_handler(&cda);

      exit(EXIT_FAILURE);

   }

   /* Bind the status variable. */

   if (obndrv(&cda,

      ":xstatus",

      -1,

      status,

      70,

      5,

      -1,

      (char *) 0,

      (char *) 0, -1, -1))

   {

      error_handler(&cda);

      exit(EXIT_FAILURE);

   }

   /* Bind the transaction type variable. */

   if (obndrv(&cda,

      ":xtrans_type",

      -1,

      trans_type,

      1,

      1,

      -1,

      (char *) 0,

      (char *) 0, -1, -1))

   {

       error_handler(&cda);

       exit(EXIT_FAILURE);

   }

   /* Bind the account number. */

   if (obndrv(&cda,

      ":xacct_number",

      -1,

      &acct_number,

      sizeof (int),

      3,

      -1,

      (char *) 0,

      (char *) 0, -1, -1))

   {

      error_handler(&cda);

      exit(EXIT_FAILURE);

   }

   /* Bind the transaction amount variable. */

   if (obndrv(&cda,

      ":xtrans_amt",

      -1,

      &trans_amt,

      sizeof (float),

      4,

      -1,

      (char *) 0,

      (char *) 0, -1, -1))

   {

      error_handler(&cda);

      exit(EXIT_FAILURE);

   }

   for (;;)

   {

      printf("\nAccount number: ");

      scanf("%d", &acct_number);

      fflush(stdin);

      if (acct_number == 0)

         break;

      printf("Transaction type (D or C): ");

      scanf("%c", trans_type);

      fflush(stdin);

      printf("Transaction amount:        ");

      scanf("%f", &trans_amt);

      fflush(stdin);

      /* Execute the block. */

      if (oexec(&cda))

         error_handler(&cda);

      printf("%s\n", status);

   }

   printf("Have a good day!\n");

   exit(EXIT_SUCCESS);

}

void

error_handler(struct cda_def *cda)

{

   char  msg[512];

   int   n;

   printf("\n>>> ORACLE Error\n");

   n = oerhms(&lda, cda-rc, msg, sizeof (msg));

   printf("%.*s\n", n, msg);

   printf("Processing OCI function %s\n\n",

      oci_func_tab[cda-fc]);

}

Calling Stored Subprograms

To call a stored subprogram from an OCI program, you must use an anonymous PL/SQL block. In the following C example, a call to the stand-alone procedure raise_salary is copied into the string variable plsql_block:

strcpy(plsql_block, "BEGIN raise_salary(:emp_id, :amount); END;");

Then, the PL/SQL string can be bound and executed like a SQL statement.


PART  II . LANGUAGE REFERENCE


CHAPTER 9. LANGUAGE ELEMENTS

Grammar, which knows how to control even kings.

Moliè re

This chapter uses syntax diagrams to show you how commands, parameters, and other language elements are sequenced to form PL/SQL statements. It serves as a quick reference guide to PL/SQL syntax and coding conventions. In addition, it provides usage notes and short examples to save you time and trouble.

The following sections are arranged alphabetically for easy reference:

Assignment Statement    %NOTFOUND Attribute

Blocks                  NULL Statement

CLOSE Statement         OPEN Statement

Comments                Packages

COMMIT Statement        PL/SQL Tables

Conditions              Procedures

Cursors                 RAISE Statement

DELETE Statement        Records

EXCEPTION_INIT Pragma   RETURN Statement

Exceptions              ROLLBACK Statement

EXIT Statement          %ROWCOUNT Attribute

Expressions             %ROWTYPE Attribute

FETCH Statement         SAVEPOINT Statement

%FOUND Attribute        SELECT INTO Statement

Functions               SET TRANSACTION Statement

GOTO Statement          SQL Cursor

IF Statement            SQLCODE Function

INSERT Statement        SQLERRM Function

%ISOPEN Attribute       %TYPE Attribute

Literals                UPDATE Statement

LOCK TABLE Statement    Variables and Constants

LOOP Statement

Each of these sections has some or all of the following subsections:

Description

Syntax

Keyword and Parameter Description

Usage Notes

Examples

Related Topics

Easy-to-understand syntax diagrams are used to illustrate PL/SQL syntax. If you are not familiar with syntax diagrams, do not worry. The next section tells you all you need to know.

________________________________________

Using Syntax Diagrams

If you are unsure of the exact syntax to use in a PL/SQL statement, refer to its syntax diagram. A syntax diagram is a line-and-arrow drawing that depicts valid syntax. You can verify or construct any PL/SQL statement by tracing through its syntax diagram.

How to Read Syntax Diagrams

Syntax diagrams use lines and arrows to show how commands, parameters, and other language elements are sequenced to form statements. Follow each diagram in the direction shown by the lines and arrows. The following symbols will guide you:

Commands and other keywords appear in uppercase; parameters appear in lowercase. Operators, delimiters, and terminators appear as usual.

If the syntax diagram contains more than one possible path, you must select the path appropriate for your program.

If you have the choice of more than one keyword, operator, or parameter, the choices appear in a vertical list. In the following examples, you can travel up or down a vertical line as far as you like, then continue along any horizontal line:

 Required Parameters

Required parameters can appear singly or in a vertical list of alternatives. Single required parameters appear on the main path, that is, on the horizontal line you are currently traveling. In the following example, cursor_name is a required parameter:

If there is a cursor named c1, then, according to the diagram, the following statement is valid:

CLOSE c1;

If any of the parameters in a vertical list appears on the main path, one of them is required. That is, you must choose one of the parameters, but not necessarily the one that appears on the main path. In the following example, you must choose one of the four types of expressions:

 Optional Parameters

If parameters appear in a vertical list below the main path, they are optional; that is, you need not choose one of them. In the following example, instead of traveling down the vertical line, you can continue along the main path:

According to the diagram, all of the following statements are valid:

COMMIT;

COMMIT WORK;

COMMIT COMMENT 'In-doubt transaction; notify Order Entry';

COMMIT WORK COMMENT 'In-doubt transaction; notify Order Entry';

 Syntax Loops

Loops let you repeat the syntax contained within them as many times as you like. In the following example, the list of declarations is within a loop. So, after choosing one type of declaration, you can go back repeatedly to choose the same or another type.

According to the last diagram, all of the following declarations are valid:

First example:

DECLARE

   credit_limit  CONSTANT  NUMBER(9,2) := 5000.00;

Second example:

DECLARE

   over_limit  EXCEPTION;

   past_due    EXCEPTION;

Third example:

DECLARE

   account_name  CHAR(25);

   over_limit    EXCEPTION;

   new_balance   NUMBER(9,2);

   old_balance   NUMBER(9,2);

   past_due      EXCEPTION;

 Multipart Syntax Diagrams

Read a multipart diagram as if all the main paths were joined end-to-end. The following example is a two-part diagram:

If there is a table named salaries with columns named grade, low, middle, and high, then, according to the diagram, the following statement is valid:

INSERT INTO salaries (grade, low, high) VALUES (4, 2000, 2999);

How to Code from a Syntax Diagram

To code from a syntax diagram, go to the beginning mark, then follow the lines and arrows. When you meet a keyword, spell it exactly as shown. Case does not matter. When you meet a parameter, replace it with the value, identifier, or object it represents. (If the parameter has its own syntax diagram, detour to that diagram, then return.) When you meet operators, delimiters, or terminators, type them exactly as shown. Separate keywords and identifiers with spaces.

In the following example, first you meet a keyword, then a parameter, and finally a terminator:

If there is a label named end_loop, then, according to the diagram, you code the statement as follows:

GOTO end_loop;

Be sure to read the parameter descriptions and usage notes. If you use certain keywords, clauses that are normally optional might be required. For example, if you use the keyword CONSTANT in a variable_declaration, you must include an initialization clause.

________________________________________

Assignment Statement

Description

An assignment statement sets the current value of a variable, formal parameter, field in a record, or row in a PL/SQL table. For more information, see the section "Declarations and Assignments" in Chapter 2.

Syntax

Alternatively, you can use the SELECT or FETCH statement to have ORACLE assign values to a variable. For more information, see the sections "FETCH" and "SELECT INTO" later in this chapter.

Keyword and Parameter Description

 object_name

This is the name of a previously declared object to which you want to assign a value.

 plsql_expression

This is an arbitrarily complex expression. The syntax for plsql_expression is defined in the section "Expressions" later in this chapter. The value of plsql_expression is assigned to the object identified by object_name. The datatype of plsql_expression must be the same as or convertible to the datatype of object. For more information, see the section "Datatype Conversion" in Chapter 2.

 plsql_variable

This refers to a PL/SQL variable previously declared within the current scope.

 record.field

This refers to a field in a user-defined or %ROWTYPE record previously declared within the current scope.

 plsql_table(subscript)

This refers to a row in a PL/SQL table previously declared within the current scope.

 host_variable

This refers to a host variable previously declared within the current scope. For information about host objects, see the section "Expressions" later in this chapter.

Usage Notes

By default, unless an object is initialized in its declaration, it is initialized to NULL every time a block or subprogram is entered. So, never reference an object before you assign it a value.

You cannot assign nulls to an object defined as NOT NULL. If you try, the predefined exception VALUE_ERROR is raised.

Only the values TRUE and FALSE and the non-value NULL can be assigned to a Boolean variable. When applied to PL/SQL expressions, the relational operators return a Boolean value. So, the following assignment is legal:

DECLARE

   out_of_range  BOOLEAN;

   ...

BEGIN

   ...

   out_of_range := (salary < minimum) OR (salary > maximum);

As the next example shows, you can assign the value of a PL/SQL expression to a specific field in a record:

DECLARE

   emp_rec  emp%ROWTYPE;

BEGIN

   ...

   emp_rec.sal := current_salary + increase;

Moreover, you can assign values to all fields in a record at once. PL/SQL allows aggregate assignment between entire records if their declarations refer to the same cursor or table. For example, the following assignment is legal:

DECLARE

   emp_rec1  emp%ROWTYPE;

   emp_rec2  emp%ROWTYPE;

   dept_rec  dept%ROWTYPE;

BEGIN

   ...

   emp_rec1 := emp_rec2;

The next assignment is illegal because you cannot use the assignment operator to assign a list of values to a record:

dept_rec := (60, 'PUBLICITY', 'LOS ANGELES');

You can assign the value of a PL/SQL expression to a specific row in a PL/SQL table by using the syntax

plsql_table_name(primary_key_value) := plsql_expression;

In the following example, you assign the uppercase value of last_name to the third row in PL/SQL table ename_tab:

ename_tab(3) := UPPER(last_name);

Examples

wages := hours_worked * hourly_salary;

country := 'France';

costs := labor + supplies;

done := (count > 100);

dept_rec.loc := 'BOSTON';

comm_tab(5) := sales * 0.15;

Related Topics

Expressions, FETCH, SELECT INTO, Variables and Constants

________________________________________

Blocks

Description

The basic program unit in PL/SQL is the block. A PL/SQL block is defined by the following keywords:

•	DECLARE

•	BEGIN

•	EXCEPTION

•	END

These keywords partition the PL/SQL block as follows:

•	declarative part

•	executable part

•	exception-handling part

Only the executable part is required.

You can nest a block within another block wherever you can place an executable statement. For more information, see the section "Block Structure" in Chapter 1 and the section "Scope and Visibility" in Chapter 2.

Syntax

Keyword and Parameter Description

 label_name

This is an undeclared identifier, which optionally labels a PL/SQL block. For naming conventions, see the section "Identifiers" in Chapter 2. If used, label_name must be enclosed by double angle brackets and must appear at the beginning of the block. (However, in the SQL*Plus environment, the first line you input cannot start with label_name.) Optionally, label_name can also appear at the end of the block.

A global identifier declared in an enclosing block can be redeclared in a sub-block, in which case the local declaration prevails and the sub-block cannot reference the global identifier. To reference the global identifier, you must use a block label to qualify the reference, as follows:

block_label.global_identifier

In the following example, you compare two INTEGER variables declared with the same name, one in an enclosing block, the other in a sub-block:

<<outer>>

DECLARE

   x  INTEGER;

BEGIN

   ...

   DECLARE

      x  INTEGER;

   BEGIN

      ...

      IF x = outer.x THEN

         ...

      END IF;

   END;

END outer;

 DECLARE

This keyword signals the start of the optional declarative part of a PL/SQL block, which contains local declarations. Objects declared locally exist only within the current block and all its sub-blocks and are not visible to enclosing blocks.

The declarative part of a PL/SQL block is optional. It is terminated implicitly by the keyword BEGIN, which introduces the executable part of the block.

PL/SQL does not allow forward references. You must declare an object before referencing it in other statements, including other declarative statements.

You can use the pragma EXCEPTION_INIT in the declarative part of a block to associate exception names with ORACLE error numbers. For more information, see the section "Using EXCEPTION_INIT" in Chapter 5.

 variable_declaration

This construct declares variables and constants. For the syntax of variable_declaration, see the section "Variables and Constants" later in this chapter.

 cursor_declaration

This construct declares an explicit cursor. For the syntax of cursor_declaration, see the section "Cursors" later in this chapter.

 exception_declaration

This construct declares exceptions. For the syntax of exception_declaration, see the section "Exceptions" later in this chapter.

 record_declaration

This construct declares user-defined records. For the syntax of record_declaration, see the section "Records" later in this chapter.

 plsql_table_declaration

This construct declares PL/SQL tables. For the syntax of plsql_table_declaration, see the section "PL/SQL Tables" later in this chapter.

 procedure_declaration

This construct declares a procedure. For the syntax of procedure_declaration, see the section "Procedures" later in this chapter.

 function_declaration

This construct declares a function. For the syntax of function_declaration, see the section "Functions" later in this chapter.

 BEGIN

This keyword signals the start of the executable part of a PL/SQL block, which contains executable statements. The executable part of a PL/SQL block or subprogram is required. That is, a block or subprogram must contain at least one executable statement. The NULL statement meets this requirement, as the following example shows:

BEGIN

   NULL;

END;

 seq_of_statements

This represents a sequence of statements. The syntax is

where statement can be any legal PL/SQL statement, including another plsql_block. Variable, constant, and exception declarations are declarative (not executable) statements.

 statement

You use this construct to create algorithms. There are PL/SQL statements for conditional, iterative, and sequential control, as well as for error handling. PL/SQL statements are free-format; that is, they can continue from line to line, providing you do not split keywords, delimiters, or literals across lines. A semicolon (;) must terminate every PL/SQL statement.

The syntax for statement follows:

 sql_statement

Following is the syntax for sql_statement, which is defined in PL/SQL as a specific subset of all SQL statements and excludes data definition and data control statements:

 EXCEPTION

This keyword signals the start of the exception-handling part of a PL/SQL block. When an exception is raised, normal execution of the block stops and control transfers to the appropriate exception handler. After the exception handler completes, execution proceeds with the statement following the block.

If there is no exception handler for the raised exception in the current block, control passes to the enclosing block. This process repeats until an exception handler is found or there are no more enclosing blocks. If PL/SQL can find no exception handler for the exception, execution of the block stops and an "unhandled exception" error is returned to the host environment. For more information, see Chapter 5.

 exception_handler

For the syntax of exception_handler, see the section "Exceptions" later in this chapter. An exception handler associates an exception with a sequence of statements, which is executed when that exception is raised. A couple of examples follow:

EXCEPTION

   WHEN ZERO_DIVIDE THEN  -- division by zero exception

      ROLLBACK;

   WHEN VALUE_ERROR THEN  -- constraint violation

      INSERT INTO audit_table

         VALUES (trans_id, kind, amount, 'Overflow Error');

      COMMIT;

   ...

END;

 END

The keyword END signals the end of a PL/SQL block. It must be the last keyword in a block. Neither the END IF in an IF statement nor the END LOOP in a LOOP statement can substitute for the keyword END.

Example

-- available online in file EXAMP11

DECLARE

   numerator    NUMBER;

   denominator  NUMBER;

   the_ratio    NUMBER;

   lower_limit  CONSTANT NUMBER := 0.72;

   samp_num     CONSTANT NUMBER := 132;

BEGIN

   SELECT x, y INTO numerator, denominator FROM result_table

      WHERE sample_id = samp_num;

   the_ratio := numerator/denominator;

   IF the_ratio > lower_limit THEN

      INSERT INTO ratio VALUES (samp_num, the_ratio);

   ELSE

      INSERT INTO ratio VALUES (samp_num, -1);

   END IF;

   COMMIT;

EXCEPTION

   WHEN ZERO_DIVIDE THEN

      INSERT INTO ratio VALUES (samp_num, 0);

      COMMIT;

   WHEN OTHERS THEN

      ROLLBACK;

END;

Related Topics

Exceptions, Cursors, Variables and Constants, Procedures

________________________________________

CLOSE Statement

Description

The CLOSE statement allows resources held by an opened cursor to be reused. No more rows can be fetched from a closed cursor. Parameter information and the parsed representation of the associated query are marked as reusable. For more information, see the section "Transaction Processing" in Chapter 4.

Syntax

Keyword and Parameter Description

 cursor_name

This must be the name of a previously declared and currently open cursor.

Usage Notes

Once a cursor is closed, you can reopen it either by issuing the OPEN command to re-evaluate parameters and reinitialize the active set or by using a cursor FOR loop to implicitly open the cursor. An attempt to execute any other operation on a closed cursor raises the predefined exception INVALID_CURSOR.

You must CLOSE a cursor before reOPENing it.

Related Topics

DECLARE, FETCH, OPEN

________________________________________

Comments

Description

Comments describe the purpose and use of code segments and so promote readability. PL/SQL supports two comment styles: single-line and multiline. Single-line comments begin with a double hyphen (--) anywhere on a line and extend to the end of the line. Multiline comments begin with a slash-asterisk (/*), end with an asterisk-slash (*/), and can span multiple lines. For more information, see the section "Comments" in Chapter 2.

Syntax

Usage Notes

Comments can appear within a statement at the end of a line. However, you cannot nest comments. Also, you cannot use single-line comments in a PL/SQL block that will be processed dynamically by an ORACLE Precompiler program because end-of-line characters are ignored. As a result, single-line comments extend to the end of the block, not just to the end of a line. Instead, use multiline comments.

While testing or debugging a program, you might want to disable a line of code. The following example shows how you can "comment out" the line:

-- UPDATE dept SET loc = my_loc WHERE deptno = my_deptno;

You can use multiline comment delimiters to comment out whole sections of code.

Examples

-- compute the area of a circle

area := pi * radius**2;  -- pi equals 3.14159

/* compute the area

of a circle */

area := pi * radius**2;  /* pi equals 3.14159 */

________________________________________

COMMIT Statement

Description

The COMMIT statement explicitly makes permanent any changes made to the database during the current transaction. Changes made to the database are not considered permanent until they are committed. COMMIT also makes the changes visible to other users. For more information, see the section "Transaction Processing" in Chapter 4.

Syntax

Keyword and Parameter Description

 COMMIT and COMMIT WORK

Both COMMIT and COMMIT WORK make any changes to the database permanent. The keyword WORK is optional and has no effect except to improve readability.

 COMMENT

COMMENT specifies a comment to be associated with the current transaction and is most often used with distributed transactions. The text must be a quoted literal <50 characters in length.

Usage Notes

The COMMIT statement releases all row and table locks. It also erases any savepoints you marked since the last commit or rollback. Until your changes are committed, the following conditions hold:

•	You can see the changes when you query the tables you modified, but other users cannot see the changes when they query those tables.

•	If you change your mind or need to correct a mistake, you can use the ROLLBACK statement to roll back (discard) the changes. For more information, see the section "ROLLBACK" later in this chapter.

If COMMIT is executed while a cursor that was declared using FOR UPDATE is open, a subsequent FETCH on that cursor raises an exception. The cursor remains open, however, so you should CLOSE it. For more information, see the sections "Using FOR UPDATE" and "Fetching Across Commits" in Chapter 4.

When a distributed transaction fails, the text specified by COMMENT helps you diagnose the problem. If a distributed transaction is ever in doubt, ORACLE stores the text in the data dictionary along with the transaction ID. For more information about distributed transactions, see the ORACLE7 Server Application Developer's Guide.

With embedded SQL, the optional RELEASE parameter is allowed after COMMIT WORK. Serving the purpose of a "disconnect" statement, RELEASE signifies that you want to log off the database once your transaction is committed. Since PL/SQL does not allow data control statements such as CONNECT, GRANT and REVOKE, it does not allow the RELEASE parameter.

Related Topics

ROLLBACK, SAVEPOINT

________________________________________

Conditions

Description

PL/SQL conditions are the basis for conditional control. Like Boolean expressions, PL/SQL conditions always evaluate to TRUE, FALSE, or NULL. Moreover, a PL/SQL condition is allowed wherever a Boolean expression is allowed.

In conditional control statements, if a PL/SQL condition evaluates to TRUE, its associated sequence of statements is executed. If a PL/SQL condition evaluates to FALSE or NULL, its associated sequence of statements is not executed. For more information, see the section "Expressions and Comparisons" in Chapter 2.

Syntax

Keyword and Parameter Description

 AND, OR, NOT

The logical operators AND, OR, and NOT operate according to the tri-state logic illustrated by the truth tables in Figure 2-4 in Chapter 2. AND returns the value TRUE only if both its operands are true. OR returns the value TRUE if either of its operands is true. NOT returns the opposite value (logical negation) of its operand. NOT NULL returns NULL because nulls are indeterminate. For more information, see the Usage Notes and the section "Logical Operators" in Chapter 2.

 boolean_literal

This is the predefined value TRUE or FALSE or the non-value NULL, which stands for a missing, unknown, or inapplicable value. You cannot insert the values TRUE and FALSE into a database column.

 boolean_variable

In a variable_declaration, this parameter is any variable or constant that belongs to type BOOLEAN. Only the values TRUE and FALSE and the non-value NULL can be assigned to a BOOLEAN variable. However, you cannot select or fetch column values into a BOOLEAN variable. Also, arithmetic operations on Boolean variables are illegal.

 boolean_function_call

This is any function call that returns a value of type BOOLEAN.

 boolean_expression

When parentheses enclose a boolean_expression that is part of a larger boolean_expression, PL/SQL evaluates the innermost expression first. The result value is then used in the larger expression.

 plsql_expression

This is an arbitrarily complex expression. The syntax for plsql_expression is defined in the section "Expressions" later in this chapter.

 relational_operator

The relational operators allow you to you compare arbitrarily complex expressions. For the meaning of each operator, see the section "Comparison Operators" in Chapter 2.

 IS [NOT] NULL

The IS NULL operator returns the Boolean value TRUE if its operand is null, or FALSE if it is not null.

 [NOT] LIKE

The LIKE operator compares a character value to a pattern. Case is significant. LIKE returns the Boolean value TRUE if the character patterns match, or FALSE if they do not match.

 pattern

This is a character string compared by the LIKE operator to a specified string value. It can include two special-purpose characters called wildcards. An underscore (_) matches exactly one character; a percent sign (%) matches zero or more characters.

 [NOT] BETWEEN

The BETWEEN operator tests whether a value lies in a specified range. It means "greater than or equal to <low value> and less than or equal to <high value>."

 [NOT] IN

The IN operator tests set membership. It means "equal to any member of." The set can contain nulls, but they are ignored. Furthermore, expressions of the form

value NOT IN set

evaluate to FALSE if the set contains a null.

 cursor_name

This is the name of a previously declared cursor.

 %NOTFOUND, %FOUND, %ISOPEN

These parameters are cursor attributes. Each cursor that you explicitly define has these attributes. When appended to the cursor name, they let you access useful information about the execution of a multirow query. You can also use them to access the SQL cursor's private SQL area, in which case their values always refer to the most recently executed SQL statement. For more information, see the section "Cursor Management" in Chapter 4.

Usage Notes

In a plsql_condition, you can only compare values that belong to (or are convertible to) the same datatype. For more information, see the section "Datatype Conversion" in Chapter 2.

When PL/SQL evaluates a boolean_expression, NOT has the highest precedence, AND has the next-highest precedence, and OR has the lowest precedence. However, you can use parentheses to override the default operator precedence.

AND and OR are short circuit operators. If the first operand of OR evaluates to TRUE, its second operand is not evaluated. Similarly, if the first operand of AND evaluates to FALSE, its second operand is not evaluated.

The relational operators can be applied to operands of type BOOLEAN. By definition, TRUE is greater than FALSE. Comparisons involving nulls always result in a null.

The value of a Boolean expression can be assigned only to Boolean variables, not to host variables or database columns. Furthermore, no implicit or explicit datatype conversion to (or from) type BOOLEAN is supported.

Related Topics

Assignment Statement, EXIT, Expressions, IF, LOOP

________________________________________

Cursors

Description

For queries that return more than one row, a cursor lets you name the query and process the rows individually. For more information, see the section "Cursors" in Chapter 1 and the section "Cursor Management" in Chapter 4.

Syntax

Keyword and Parameter Description

 cursor_name

This identifier names a cursor. The cursor name is like a function name and follows the usual scope rules. For naming conventions, see the section "Identifiers" in Chapter 2.

 parameter_name

This identifier names a cursor formal parameter. For naming conventions, see the section "Identifiers" in Chapter 2.

A cursor parameter can appear in a query wherever a constant can appear. The formal parameters of a cursor must be IN parameters. For information about parameter modes, see Chapter 6. The query can also reference other PL/SQL variables within its scope.

 parameter_type

This specifies the datatype of a cursor parameter. The datatype of the corresponding actual parameter must be the same as or convertible to parameter_type. For more information, see the section "Datatype Conversion" in Chapter 2.

 RETURN

This keyword introduces the RETURN clause, which defines the datatype of a cursor result value. You can use the %ROWTYPE attribute in a RETURN clause to provide a record that represents a row in a database table. You can also use the %TYPE attribute in a RETURN clause to provide the datatype of a variable, constant, or database column.

A cursor body must have a SELECT statement and the same RETURN clause as its corresponding cursor specification. Furthermore, the number and datatypes of select-list items in the SELECT statement must match the RETURN clause.

 type_name

This specifies the datatype of the result value returned by the cursor. For more information, see the section "Datatypes" in Chapter 2.

 %TYPE

The %TYPE attribute provides the datatype of a variable, constant, or database column.

 table.column

This refers to a database table and column that must be accessible when the declaration is elaborated.

 table

This refers to a database table that must be accessible when the declaration is elaborated.

 %ROWTYPE

The %ROWTYPE attribute provides a record that represents a row in a database table. Columns in a row and corresponding fields in a record have the same names and datatypes.

 select_statement

This is a query associated with cursor_name, which returns a set of values. The syntax for select_statement is similar to the syntax for select_into_statement, defined in the section "SELECT INTO" later in this chapter, except that select_statement cannot have an INTO clause.

If the cursor declaration defines parameters, each parameter must be used in the select_statement.

Usage Notes

You must declare a cursor before referencing it in an OPEN, FETCH, or CLOSE statement. And, you must declare a variable before referencing it in a cursor declaration. For more information, see the section "Declaring a Cursor" in Chapter 4.

You cannot assign values to a cursor name or use it in an expression. However, cursors and variables follow the same scoping rules. For more information, see the section "Scope and Visibility" in Chapter 2.

The word SQL is reserved by PL/SQL for use as the default name for implicit cursors and cannot be used in a cursor declaration.

You retrieve data from a cursor by OPENing it, then FETCHing from it. Since the FETCH statement specifies the target variables, using an INTO clause in the SELECT statement of a cursor_declaration is redundant and invalid.

The scope of cursor parameters is local to the cursor, meaning that they can be referenced only within the query used in the cursor declaration. The values of cursor parameters are used by the associated query when the cursor is OPENed. The query can also reference other PL/SQL variables within its scope. The parameter_type cannot be constrained. For example, you must specify NUMBER, not NUMBER(11,2).

Examples

Some examples of cursor declarations follow:

CURSOR c1 IS

   SELECT ename, job, sal FROM emp WHERE deptno = 20;

CURSOR c2 (start_date  DATE) IS

   SELECT empno, sal FROM emp WHERE hiredate > start_date;

Related Topics

CLOSE, FETCH, OPEN, SELECT INTO

________________________________________

DELETE Statement

Description

The DELETE statement removes entire rows of data from a specified table or view. For a full description of the DELETE statement, refer to the ORACLE7 Server SQL Language Reference Manual.

Syntax

Keyword and Parameter Description

 table_reference

The table or view specified by table_reference must be accessible when you execute the DELETE statement, and you must have DELETE privileges.

 alias

This is another (usually short) name for the referenced table or view and is typically used in the WHERE clause.

 WHERE search_condition

This clause conditionally chooses rows to be deleted from the referenced table or view. Only rows that meet the search_condition are deleted. If you omit the WHERE clause, all rows in the table or view are deleted.

 WHERE CURRENT OF cursor_name

This refers to the latest row processed by the FETCH statement associated with cursor_name. The named cursor must have been declared using the FOR UPDATE clause and must be open and positioned on a row. If the cursor is not open, the CURRENT OF clause results in an error.

Usage Notes

A plsql_expression (except one of type BOOLEAN) can be used in a DELETE statement wherever a literal can be used.

The DELETE ... WHERE CURRENT OF statement can be used after a FETCH is executed on an open cursor (this includes implicit FETCHes executed in a cursor FOR loop), provided the associated query was declared with a FOR UPDATE clause. The DELETE ... WHERE CURRENT OF cursor_name deletes the current row; that is, the one just FETCHed.

The implicit SQL cursor and the cursor attributes %NOTFOUND, %FOUND, and %ROWCOUNT let you access useful information about the execution of a DELETE statement. For details, see the section "Cursor Management" in Chapter 4.

A DELETE might delete one or more rows or it might delete no rows. If one or more rows are deleted, the following things occur:

•	SQL%NOTFOUND evaluates to FALSE

•	SQL%FOUND evaluates to TRUE

•	SQL%ROWCOUNT returns the number of rows deleted

If no rows are deleted, the following things occur:

•	SQL%NOTFOUND evaluates to TRUE

•	SQL%FOUND evaluates to FALSE

•	SQL%ROWCOUNT returns the number 0

Examples

The following statement deletes from the bonus table all employees whose sales were below quota:

DELETE FROM bonus WHERE sales_amt < quota;

________________________________________

EXCEPTION_INIT Pragma

Description

EXCEPTION_INIT associates an exception name with an ORACLE error number. That allows you to refer to any internal exception by name and to write a specific handler for it instead of using the OTHERS handler. For more information, see the section "Using EXCEPTION_INT" in Chapter 5.

Syntax

Keyword and Parameter Description

 PRAGMA

This signifies that the statement is a pragma (compiler directive). Pragmas are processed at compile time, not at run time. They do not affect the meaning of a program; they simply convey information to the compiler.

 exception_name

This is the name of an exception previously declared using an exception_declaration.

 error_number

The error_number can be any valid ORACLE error number. These are the same error numbers that the function SQLCODE returns.

Usage Notes

The pragma EXCEPTION_INIT must appear in the same declarative section as its associated exception, somewhere after the exception declaration. Thus, EXCEPTION_INIT can be used only in the declarative part of a PL/SQL block, subprogram, or package.

Be sure to assign only one exception name to an error number.

Example

DECLARE

   invalid_table  EXCEPTION;

   PRAGMA EXCEPTION_INIT(invalid_table, -942);

      /* ORACLE issues error number -942 if you */

      /* refer to a nonexistent database table  */

BEGIN

   ...

EXCEPTION

   WHEN invalid_table THEN

      -- handle the error

   ...

END;

Related Topics

Exceptions, EXCEPTION_INIT, SQLCODE

________________________________________

Exceptions

Description

An exception declaration names a user-defined exception. You raise an exception using the RAISE statement, then process the exception in an exception handler. An exception handler executes statements in response to a raised exception. When an exception is raised, normal execution of the PL/SQL block stops, and the statements in the appropriate exception handler are executed. After the exception handler completes, processing of the block stops and control returns to the host environment. For more information, see Chapter 5.

Syntax

Keyword and Parameter Description

 exception_name

This identifier names a predefined or user-defined exception. For naming conventions, see the section "Identifiers" in Chapter 2.

 WHEN

You can have multiple exceptions execute the same sequence of statements by following the keyword WHEN with a list of the exceptions, separating them by the keyword OR. If any exception in the list is raised, the associated statements are executed.

Each WHEN clause can associate a different sequence of statements with a list of exceptions. However, an exception name can appear only once in the exception-handling part of a PL/SQL block or subprogram.

 OTHERS

OTHERS stands for all the other exceptions not explicitly named in the exception-handling part of the block. The use of OTHERS is optional and is allowed only as the last exception handler. You cannot include OTHERS in a list of exceptions following the keyword WHEN.

 seq_of_statements

This represents a sequence of statements. For the syntax of seq_of_statements, see the section "Blocks" earlier in this chapter.

Usage Notes

An exception declaration can appear only in the declarative part of a block, subprogram, or package. The scope rules for exceptions and variables are the same. But, unlike variables and constants, exceptions cannot be passed as parameters to subprograms.

Some exceptions are predefined by PL/SQL. For a list of these exceptions, see the section "Predefined Exception" in Chapter 5. PL/SQL declares predefined exceptions globally in package STANDARD, so you need not declare them yourself. Redeclaring predefined exceptions is error-prone because your local declaration overrides the global declaration. In such cases, you must use dot notation to specify the predefined exception, as follows:

EXCEPTION

   WHEN invalid_number OR STANDARD.INVALID_NUMBER THEN

      ...

The exception-handling part of a PL/SQL block is optional. Exception handlers must come at the end of the block. They are introduced by the keyword EXCEPTION. The exception-handling part of the block is terminated by the same keyword END that terminates the entire block.

An exception should be raised only when an error occurs that makes it impossible or undesirable to finish processing. If there is no exception handler in the current block for a raised exception, the exception propagates according to the following rules:

•	If there is an enclosing block for the current block, the exception is passed on to that block. The enclosing block then becomes the current block. If a handler for the raised exception is not found, the process repeats.

•	If there is no enclosing block for the current block, an "unhandled exception" error is passed back to the host environment.

Only one exception at a time can be active in the exception-handling part of a block. Therefore, if an exception is raised inside a handler, the block that encloses the current block is the first block searched to find a handler for the newly raised exception. From there on, the exception propagates normally.

An exception handler can reference only those variables that the current block can reference.

Example

DECLARE

   bad_employee_num  EXCEPTION;

   bad_act_num       EXCEPTION;

   ...

BEGIN

   ...

EXCEPTION

   WHEN bad_employee_num OR bad_acct_num THEN  -- user defined

      ROLLBACK;

   WHEN ZERO_DIVIDE THEN   -- a predefined exception

      INSERT INTO inventory_table VALUES (prod_name, quantity);

      COMMIT;

END;

Related Topics

Blocks, EXCEPTION_INIT, RAISE

________________________________________

EXIT Statement

Description

You use the EXIT statement to exit a loop. The EXIT statement has two forms: the unconditional EXIT and the conditional EXIT WHEN. With either form, you can name the loop to be exited. For more information, see the section "Sequential Control" in Chapter 3.

Syntax

Keyword and Parameter Description

 EXIT

When the EXIT statement is processed and there is no label_name and no WHEN clause in the statement, PL/SQL exits the current loop immediately. Execution resumes with the statement following the loop.

 label_name

This identifies the loop that you want to exit. By using label_name, you can exit not only the current loop, but any outer loop which encloses the current loop, providing the outer loop has been named in an enclosing loop_statement.

 plsql_condition

This is a condition to be evaluated each time PL/SQL encounters the EXIT statement during normal execution of the sequence of statements in a loop. If plsql_condition evaluates to TRUE, PL/SQL exits the current loop (or the loop labeled by label_name) immediately. This is equivalent to the following statement:

IF plsql_condition THEN EXIT; END IF;

The syntax for plsql_condition is defined in the section "Conditions" earlier in this chapter.

Usage Notes

An exit_statement can be used only within the seq_of_statements contained within loop_statement.

You can write an infinite loop in PL/SQL. For example, WHILE TRUE LOOP ... will never terminate in the normal way. In this case, you must use exit_statement to exit the loop.

If you use exit_statement to leave a cursor FOR loop prematurely, the cursor is closed automatically. The cursor is also closed automatically if an exception is raised inside the loop.

Example

The EXIT statement in the following example is illegal because you cannot exit from a block directly; you can exit only from a loop:

DECLARE

   amount   NUMBER;

   maximum  NUMBER;

BEGIN

   ...

   BEGIN

      ...

      IF amount >= maximum THEN

         EXIT;

      END IF;

   END;

   ...

END;

The following loop normally executes ten times, but it will exit prematurely if it finds no more data to return:

FOR i IN 1..10

   LOOP

      FETCH c1 INTO emp_rec;

      EXIT WHEN c1%NOTFOUND;

      total := total + emp_rec.comm;

   END LOOP;

The following example demonstrates the use of label_name:

<<outer>>

FOR i IN 1..10 LOOP

   ...

   <<inner>>

   FOR j IN 1..100 LOOP

      ...

      EXIT outer WHEN ...  -- exits both loops

   END LOOP inner;

END LOOP outer;

Related Topics

Conditions, LOOP

________________________________________

Expressions

Description

An expression is a combination of variables, constants, literals, and operators. (In some contexts, you can use host variables. For more information, see the section "Using Host Variables" in Chapter 8.) The PL/SQL compiler determines the datatype of an expression from the types of the variables, constants, literals, and operators that comprise the expression. Every time the expression is evaluated, a value of that type results. For more information, see the section "Expressions and Comparisons" in Chapter 2.

Syntax

Keyword and Parameter Description

 boolean_expression

This is an expression that evaluates to TRUE, FALSE, or NULL. For the syntax of boolean_expression, see the section "Conditions" earlier in this chapter.

num_expression:

 numeric_literal

This is a numeric literal, or a literal that can be implicitly converted to a numeric value.

 numeric_variable

This is the name of a previously declared variable or constant of type NUMBER or a type that can be implicitly converted to type NUMBER.

 host_object_reference

See the subsection "Host Objects."

 numeric_function_call

This is a function call that returns a value of type NUMBER or of a type that can be implicitly converted to type NUMBER. Examples are the ABS, SQRT, and LENGTH functions.

 NULL

This represents a null. When used in a num_expression, the result is always a null.

 integer_expr

This is a numeric expression with an integer value.

 +, -

The symbols plus (+) and minus (-) are unary operators when used as the first characters in num_expression. The + has no effect. The - negates the value of num_expression. When used in num_expression, + and - are the addition and subtraction operators, respectively.

 /, *, **

The symbols  /,  *,  and  **  are the division, multiplication, and exponentiation operators, respectively.

char_expression:

 char_literal

This is any valid string literal. For a definition of string literal, see the section "Literals" later in this chapter.

 char_variable

This is the name of a previously declared string variable or constant. For more information, see the section "Variables and Constants" later in this chapter.

 host_object_reference

See the subsection "Host Objects."

 char_function_call

This is a function that returns a value of type CHAR. Examples are the UPPER() and SQLERRM() functions.

 ||

The symbol || is the concatenation operator. The result of concatenating string1 with string2 is a character string that contains string1 followed by string2. An example follows:

'Good' || ' Morning.'    results in    'Good Morning.'

 NULL

The keyword NULL represents a null. When used in concatenation, nulls have no effect on the result, as the next example shows:

'suit' || NULL || 'case'    results in    'suitcase'

A string zero characters in length ('') is called a null string and is treated like a null. An example follows:

'suit' || '' || 'case'    results in    'suitcase'

date_expression:

 date_literal

This is a string literal that contains a valid date. For a definition of string literal, see the section "Literals" later in this chapter. A couple of examples follow:

'05-JUL-59'

'02-DEC-77'

 date_variable

This is the name of a previously declared variable or constant of type DATE or of a type that can be implicitly converted to type DATE.

 host_object_reference

See the subsection, "Host Objects."

 date_function_call

This is a function call that returns a value of type DATE or of a type that can be implicitly converted to type DATE. Examples are the TO_DATE, LAST_DAY, and NEXT_DAY functions.

 NULL

The keyword NULL represents a null. When used in a date_expression, the result is always a null.

Host Objects

Objects from an external (host) environment are called host objects. For example, in the embedded PL/SQL environment, a variable declared in the host language is called a host variable. A form field in the SQL*Forms environment is another example of a host object. For more information about host variables, see Chapter 8. The syntax for a host_object_reference follows

:

 :num_host_object

This is the name of a previously declared object of type NUMBER or of a type that can be implicitly converted to type NUMBER.

 :char_host_object

This is the name of a previously declared object of type CHAR or of a type that can be implicitly converted to type CHAR.

 :date_host_object

This is the name of a previously declared object of type DATE or of a type that can be implicitly converted to type DATE. (An object of type CHAR in the default date format 'DD-MON-YY' would qualify.)

 :indicator

This indicates the value or condition of a host variable. For example, in the embedded SQL environment, an integer indicator variable is used to assign null values to input host variables and detect null or truncated values in output host variables. For more information about indicator variables, see Chapter 8.

Usage Notes

The operations occur in their predefined order of precedence. From first to last (top to bottom), the default order of operations is as follows:

•	parentheses

•	exponents

•	unary operators

•	multiplication and division

•	addition, subtraction, and concatenation

PL/SQL evaluates multiple operators of equal precedence in an undefined order.

When parentheses surround an expression that is part of a larger expression, the expression within the parentheses is evaluated first. The result is then used as a single value in the larger expression.

In a plsql_expression, you can use only values having datatypes that are compatible with (or convertible to) each other. For more information, see the section "Datatype Conversion" in Chapter 2.

Examples

5.0                -- a num_expression with a numeric_literal

6 + b*4            -- a num_expression

'JONES'            -- a char_expression with a character_literal

'FAT ' || 'CATS'   -- a char_expression with a concatenation

last_name          -- a char_expression with a char_variable

'26-NOV-65'        -- a date_expression that is a string literal

Related Topics

Assignment Statement, Conditions, Variables and Constants

________________________________________

FETCH Statement

Description

The FETCH statement retrieves the next row of data from the active set (those rows that satisfy the query associated with a cursor). The data is stored in variables that correspond to the columns selected by the query. For more information, see the section "Transaction Processing" in Chapter 4.

Syntax

Keyword and Parameter Description

 cursor_name

This parameter names an explicitly declared and currently open cursor. For naming conventions, see the section "Identifiers" in Chapter 2.

 INTO variable_name

INTO variable_name defines the scalar variables that will store the retrieved data. All variables in the variable_name list must have been declared.

For each column returned by the query associated with the cursor, there must be a corresponding variable in the variable_name list. Also, the datatypes column values returned by the query must be the same as or convertible to the datatypes of corresponding variables in the variable_name list. For more information, see the section "Datatype Conversions" in Chapter 2.

 INTO record_name

This parameter indicates that retrieved data is stored in a record variable declared using the %ROWTYPE attribute. An example follows:

DECLARE

   CURSOR c1 IS SELECT ename, empno FROM emp;

   emp_rec  c1%ROWTYPE;

   ...

BEGIN

   OPEN c1;

   ...

   LOOP

      FETCH c1 INTO emp_rec;

      EXIT WHEN c1%NOTFOUND;

      ...

   END LOOP;

   CLOSE c1;

END;

You use dot notation to access field values, as the following example shows:

emp_rec.ename

Usage Notes

In PL/SQL, a SELECT INTO statement should return only one row. If no rows are returned, the predefined exception NO_DATA_FOUND is raised. If more than one row is returned, the predefined exception TOO_MANY_ROWS is raised. You must use either a cursor FOR loop or the FETCH statement to process multirow queries.

FETCH is typically used as follows:

...

OPEN my_cursor;

...

LOOP

   FETCH my_cursor INTO my_record;

   EXIT WHEN my_cursor%NOTFOUND;

   ...

      -- process the retrieved data

   ...

END LOOP;

Any variables in the WHERE clause of the query associated with cursor_name are evaluated only when the cursor is opened, as in the following example:

DECLARE

   multiplied_sal  NUMBER(10);

   multiplier      NUMBER(10) := 2;

   CURSOR my_cursor IS SELECT multiplier*sal FROM emp;

BEGIN

   OPEN my_cursor;    -- multiplier equals 2 here

   LOOP

      FETCH my_cursor INTO multiplied_sal;

      EXIT WHEN my_cursor%NOTFOUND;

         -- process the retrieved data

      multiplier := multiplier + 1;

         /* Doesn't affect the FETCH.  sal remains */

         /* multiplied by 2.                       */

   END LOOP;

END;

In this example, all the retrieved values will be 2 * SAL, even though multiplier is incremented for each FETCH (since the cursor was opened with multiplier set to 2). To change the active set or the values of variables in the query, you must CLOSE and reOPEN the cursor with the input variables (in this case, multiplier) set to their new values.

However, you can use different INTO lists on separate FETCHes with the same cursor. Each FETCH retrieves another row and assigns values to the INTO variables, as the following example shows:

DECLARE

   CURSOR my_cursor IS SELECT ename FROM emp;

   var1  emp.ename%TYPE;

   var2  emp.ename%TYPE;

   var3  emp.ename%TYPE;

BEGIN

   OPEN my_cursor;

   FETCH my_cursor INTO var1;  -- this fetches first row

   FETCH my_cursor INTO var2;  -- this fetches second row

   FETCH my_cursor INTO var3;  -- this fetches third row

   ...

   CLOSE my_cursor;

END;

If you execute a FETCH and there are no more rows left in the active set, the %NOTFOUND attribute for that cursor evaluates to TRUE. At that time, the values of the INTO variables are undefined.

Usually, you can use a cursor FOR loop instead of explicitly opening, fetching, and closing the cursor.

Related Topics

Assignment Statement, CLOSE, Cursors, LOOP, %NOTFOUND, OPEN, %ROWTYPE, SELECT INTO

________________________________________

%FOUND Attribute

Description

PL/SQL cursors have four attributes, including %FOUND, which, when appended to the cursor name, let you access useful information about the cursor. For more information, see the section "Cursor Management" in Chapter 4.

There are two kinds of cursors: implicit and explicit. PL/SQL implicitly declares a cursor for all SQL data manipulation statements, including single-row queries. Until the SQL statement is executed, %FOUND evaluates to NULL. Thereafter, %FOUND evaluates to TRUE if an INSERT, UPDATE, or DELETE affected one or more rows or a SELECT INTO returned one or more rows. Otherwise, %FOUND evaluates to FALSE.

For multirow queries, you can explicitly declare a cursor to process the rows. After the cursor is open but before the first fetch, %FOUND evaluates to NULL. Thereafter, it evaluates to TRUE if the last fetch returned a row or to FALSE if no row was returned.

Syntax

Keyword and Parameter Description

 cursor_name

This parameter must be the name of an explicitly declared cursor or the name of the implicit cursor (SQL).

Usage Notes

You can use the %FOUND attribute in procedural statements but not in SQL statements. %FOUND is associated with every explicit cursor. So, you can open multiple cursors, then use %FOUND to tell which cursors have rows left to fetch. If a cursor is not open, referencing it with %FOUND raises INVALID_CURSOR.

When an explicit cursor is opened, the rows that satisfy the associated query are identified and form the active set. Rows are fetched from the active set one at a time. If the last fetch returned a row, %FOUND evaluates to TRUE. If the last fetch failed to return a row (because the active set was empty), %FOUND evaluates to FALSE.

Examples

The block in the following example returns a number from each of two tables, then inserts the sum of the numbers into a third table. It completes when all rows have been fetched from either table.

-- available online in file EXAMP12

DECLARE

   CURSOR num1_cur IS SELECT num FROM num1_tab

      ORDER BY sequence;

   CURSOR num2_cur IS SELECT num FROM num2_tab

      ORDER BY sequence;

   num1      num1_tab.num%TYPE;

   num2      num2_tab.num%TYPE;

   pair_num  NUMBER := 0;

BEGIN

   OPEN num1_cur;

   OPEN num2_cur;

   LOOP   -- loop through the two tables and get

         -- pairs of numbers

      FETCH num1_cur INTO num1;

      FETCH num2_cur INTO num2;

      IF (num1_cur%FOUND) AND (num2_cur%FOUND) THEN

         pair_num := pair_num + 1;

         INSERT INTO sum_tab VALUES (pair_num, num1 + num2);

      ELSE

         EXIT;

      END IF;

   END LOOP;

   CLOSE num1_cur;

   CLOSE num2_cur;

END;

In the next example, %FOUND is used to do an INSERT if an UPDATE succeeds:

UPDATE emp SET sal = sal * 1.1 WHERE ename = my_ename;

IF SQL%FOUND THEN

   INSERT INTO bonus_amts VALUES (my_deptno, my_ename, my_sal);

END IF;

Related Topics

CLOSE, Cursors, DELETE, FETCH, INSERT, %NOTFOUND, OPEN, SELECT INTO, UPDATE

________________________________________

Functions

Description

A function is a named program unit that takes parameters and returns a computed value. For more information, see the section "Functions" in Chapter 6.

A function has two parts: the specification and the body. The function specification begins with the keyword FUNCTION and ends with the RETURN clause, which specifies the datatype of the result value. Argument declarations are optional. Functions that take no arguments are written without parentheses.

The function body begins with the keyword IS and ends with the keyword END followed by an optional function name. The function body has three parts: a declarative part, an executable part, and an optional exception-handling part.

The declarative part contains declarations of types, cursors, constants, variables, exceptions, and subprograms. These objects are local and cease to exist when you exit the function. The executable part contains statements that assign values, control execution, and manipulate ORACLE data. The exception-handling part contains exception handlers, which deal with exceptions raised during execution.

Syntax

Keyword and Parameter Description

 function_name

This identifier names a function. For naming conventions, see the section "Identifiers" in Chapter 2.

 argument_name

This identifier names a formal parameter, which is a variable declared in a function specification and referenced in the function body. For naming conventio0ns, see the section "Identifiers" in Chapter 2.

 RETURN

This keyword introduces the RETURN clause, which specifies the datatype of the result value.

 type_name

This specifies the datatype of a formal argument or result value. For more information, see the section "Datatypes" in Chapter 2.

Unlike the datatype specifier in a variable declaration, the datatype specifier in an argument declaration must be unconstrained. For example, the following declaration of acct_id is illegal:

FUNCTION ... (acct_id INTEGER(5)) ... IS  -- illegal

BEGIN ... END;

 table.column

This refers to a database table and column that must be accessible when the declaration is elaborated.

 %TYPE

The %TYPE attribute provides the datatype of a variable, constant, or database column.

 table

This refers to a database table that must be accessible when the declaration is elaborated.

 %ROWTYPE

The %ROWTYPE attribute provides a record that represents a row in a database table. Columns in a row and corresponding fields in a record have the same names and datatypes.

 variable_declaration

This construct declares variables and constants. For the syntax of variable_declaration, see the section "Variables and Constants" later in this chapter.

 cursor_declaration

This construct declares an explicit cursor. For the syntax of cursor_declaration, see the section "Cursors" earlier in this chapter.

 exception_declaration

This construct declares exceptions. For the syntax of exception_declaration, see the section "Exceptions" earlier in this chapter.

 record_declaration

This construct declares user-defined records. For the syntax of record_declaration, see the section "Records" later in this chapter.

 plsql_table_declaration

This construct declares PL/SQL tables. For the syntax of plsql_table_declaration, see the section "PL/SQL Tables" later in this chapter.

 procedure_declaration

This construct declares a procedure. For the syntax of procedure_declaration, see the section "Procedures" later in this chapter.

 function_declaration

This construct declares a nested function.

 seq_of_statements

This represents a sequence of statements. For the syntax of seq_of_statements, see the section "Blocks" earlier in this chapter.

 exception_handler

This construct associates an exception with a sequence of statements, which is executed when that exception is raised. For the syntax of exception_handler, see the section "Exceptions" earlier in this chapter.

 IN, OUT, IN OUT

These parameter modes define the behavior of formal parameters. The IN parameter mode lets you pass values to the subprogram being called. An OUT parameter lets you return values to the caller of the subprogram. An IN OUT parameter lets you pass initial values to the subprogram being called and return updated values to the caller.

 DEFAULT or :=

This keyword or assignment operator allows you to initialize IN parameters to default values.

Usage Notes

Every function must contain at least one RETURN statement. Otherwise, PL/SQL raises the predefined exception PROGRAM_ERROR at runtime.

A function is called as part of an expression. For example, the function sal_ok might be called as follows:

promotable := sal_ok(new_sal, new_title) AND (rating > 3);

The function identifier is an expression that yields a result.

Inside a function, an IN parameter acts like a constant. Therefore, it cannot be assigned a value. An OUT parameter acts like an uninitialized variable. So, its value cannot be assigned to another variable or reassigned to itself. An IN OUT parameter acts like an initialized variable. Therefore, it can be assigned a value, and its value can be assigned to another variable. For summary information about the parameter modes, see Table 6-1 in Chapter 6.

Avoid using the OUT and IN OUT modes with functions. The purpose of a function is to take zero or more arguments and return a single value. It is poor programming practice to have a function return multiple values. Also, functions should be free from side effects, which change the values of variables not local to the subprogram. Thus, a function should not change the values of its actual parameters.

You can write the function specification and body as a unit. Or, you can separate the function specification from its body. That way, you can hide implementation details by placing the function in a package.

You can define functions in a package body without declaring their specifications in the package specification. However, such functions can be called only from inside the package.

Functions can be defined using any ORACLE tool that supports PL/SQL. To become available for general use, however, functions must be CREATEd and stored in an ORACLE database.

You can issue the CREATE FUNCTION statement interactively from SQL*Plus or SQL*DBA. For the full syntax of the CREATE statement, see the SQL Language Reference Manual.

Related Topics

Cursors, Exceptions, Packages, PL/SQL Tables, Procedures, Records

Example

The following function returns the balance of a specified bank account:

FUNCTION balance (acct_id INTEGER) RETURN REAL IS

   acct_bal  REAL;

BEGIN

   SELECT bal INTO acct_bal FROM accts WHERE acctno = acct_id;

   RETURN acct_bal;

END balance;

________________________________________

GOTO Statement

Description

The GOTO statement branches to a labeled statement or PL/SQL block unconditionally. The label must be unique within its scope and must precede an executable statement or a PL/SQL block. When executed, the GOTO statement transfers control to the labelled statement or block. For more information, see the section "Sequential Control" in Chapter 3.

Syntax

Keyword and Parameter Description

 label_name

This is an undeclared identifier that optionally labels a statement or block to which you want to transfer control. For naming conventions, see the section "Identifiers" in Chapter 2.

You use label_name in a GOTO statement to transfer control to the statement or block following <<label_name>>. For more information about label_name, see the section "Blocks" earlier in this chapter.

Usage Notes

Some possible destinations of a GOTO statement are illegal. In particular, a GOTO statement cannot branch into an IF statement, LOOP statement, or sub-block. For example, the following GOTO statement is illegal:

BEGIN

   ...

   GOTO update_row;  -- illegal

   ...

   IF valid THEN

      ...

      <<update_row>>

      UPDATE emp SET ...

   END IF;

END;

From the current block, a GOTO statement can branch to another place in the block or into an enclosing block, but not into an exception handler. From an exception handler, a GOTO statement can branch into an enclosing block, but not into the current block.

If you use the GOTO statement to leave a cursor FOR loop prematurely, the cursor is closed automatically. The cursor is also closed automatically if an exception is raised inside the loop.

A given label_name can appear at most once in a block, although it can appear in other blocks, including enclosing blocks and sub-blocks. If label_name does not appear in the current block, the GOTO statement branches to the first enclosing block in which label_name appears.

Examples

A GOTO statement cannot be used to label just any keyword. It must label an executable statement or a block. For example, the following GOTO statement is illegal:

BEGIN

   ...

   FOR ctr IN 1..50 LOOP

      DELETE FROM emp WHERE ...

      IF SQL%FOUND THEN

         GOTO end_loop;

      END IF;

      ...

   <<end_loop>>

   END LOOP;   -- not an executable statement

END;

To debug the last example, simply add the NULL statement, as follows:

BEGIN

   ...

   FOR ctr IN 1..50 LOOP

      DELETE FROM emp WHERE ...

      IF SQL%FOUND THEN

         GOTO end_loop;

      END IF;

      ...

   <<end_loop>>

   NULL;   -- an executable statement that specifies inaction

   END LOOP;

END;

You cannot branch into an IF statement, so the following GOTO statement is illegal:

BEGIN

   ...

   GOTO my_label;  -- illegal

   IF a > b THEN

      b := b - c;

      <<my_label>>

      x := x + 1;

   END IF;

END;

For more examples of legal and illegal GOTO statements, see the section "Sequential Control" in Chapter 3.

________________________________________

IF Statement

Description

The IF statement lets you execute a sequence of statements conditionally. That is, whether the sequence is executed or not depends on the value of a condition. For more information, see the section "Conditional Control" in Chapter 3.

Syntax

Keyword and Parameter Description

 plsql_condition

This is a condition associated with a sequence of statements, which is executed only if the condition evaluates to TRUE. For the syntax of plsql_condition, see the section "Conditions" earlier in this chapter.

 seq_of_statements

This represents a sequence of statements. For the syntax of seq_of_statements, see the section "Blocks" earlier in this chapter.

 THEN

This keyword associates the condition that precedes THEN with the seq_of_statements that follows. If the condition evaluates to TRUE, the associated seq_of_statements is executed.

 ELSIF

This keyword introduces a condition to be evaluated if the condition following IF and all the conditions following any preceding ELSIFs evaluate to FALSE or NULL.

 ELSE

No condition follows this keyword. If control reaches the keyword ELSE, the seq_of_statements that follows is executed.

Usage Notes

There are three forms of IF statements: IF-THEN, IF-THEN-ELSE, and IF-THEN-ELSIF. The simplest form of IF statement associates a condition with a sequence of statements enclosed by the keywords THEN and END IF. The sequence of statements is executed only if the condition evaluates to TRUE. If the condition evaluates to FALSE or NULL, the IF statement does nothing. In either case, control passes to the next statement.

The second form of IF statement adds the keyword ELSE followed by an alternative sequence of statements. The sequence of statements in the ELSE clause is executed only if the condition evaluates to FALSE or NULL. Thus, the ELSE clause ensures that a sequence of statements is executed.

The third form of IF statement uses the keyword ELSIF to introduce additional conditions. If the first condition evaluates to FALSE or NULL, the ELSIF clause tests another condition. An IF statement can have any number of ELSIF clauses; the final ELSE clause is optional. Conditions are evaluated one by one from top to bottom. If any condition evaluates to TRUE, its associated sequence of statements is executed and control passes to the next statement. If all conditions evaluate to FALSE or NULL, the sequence in the ELSE clause is executed.

An IF statement never executes more than one sequence of statements because processing is complete after a sequence of statements is executed.

The THEN and ELSE clauses can include IF statements. That is, IF statements can be nested.

Examples

In the example below, if shoe_count has a value of 10, both the first and second conditions are true. Nonetheless, order_quantity is assigned the proper value of 50 because processing of an IF statement stops after a condition evaluates to TRUE and its associated seq_of_statements is executed. The condition associated with ELSIF is never evaluated and control passes to the INSERT statement.

IF shoe_count < 20 THEN

   order_quantity := 50;

ELSIF shoe_count < 30 THEN

   order_quantity := 20;

ELSE

   order_quantity := 10;

END IF;

INSERT INTO purchase_order VALUES (shoe_type, order_quantity);

In the following example, depending on the value of score, one of three status messages is inserted into the grades table:

IF score < 70 THEN

   fail := fail + 1;

   INSERT INTO grades VALUES (student_id, 'Failed');

ELSIF score IS NULL THEN

   INSERT INTO grades VALUES (student_id, 'Unknown');

ELSE

   pass := pass + 1;

   INSERT INTO grades VALUES (student_id, 'Passed');

END IF;

Related Topics

Conditions

________________________________________

INSERT Statement

Description

The INSERT statement adds new rows of data to a specified database table or view. For a full description of the INSERT statement, see the ORACLE7 Server SQL Language Reference Manual.

Syntax

Keyword and Parameter Description

 table_reference

The table or view specified by table_reference must be accessible when you execute the INSERT statement, and you must have INSERT privileges.

 alias

This is another (usually short) name for the referenced table or view and is typically used in the WHERE clause of the subquery.

 column_name

This identifier names a column in the table or view into which data is inserted. Column names must not be specified more than once in the column_name list and need not appear in the order in which they were defined by CREATE TABLE or CREATE VIEW. If a column_name list does not include all the columns in a table, the excluded columns are set to NULL or to a default value specified in the CREATE TABLE statement.

 VALUES (sql_expression, sql_expression, ...)

This clause assigns the values of sql_expressions in the VALUES list to corresponding columns in the column list. If no column list is supplied, the first value is inserted into the first column defined by CREATE TABLE, the second value is inserted into the second column, and so on. A sql_expression is any expression valid in SQL. For more information, see the ORACLE7 Server SQL Language Reference Manual.

There must be only one value for each column_name in the column list. The first value is associated with the first column name, the second value is associated with the second column name, and so on. If there is no column list, a value must be supplied for each column in the table.

The datatypes of the values being inserted must be the same as or convertible to the datatypes of the corresponding columns in the column list. For more information, see the section "Datatypes" in Chapter 2.

 select_statement

This is a query that returns a set of values for insertion into a database table (or view). The syntax for select_statement is similar to the syntax for select_into_statement, defined in the section "SELECT INTO" later in this chapter, except that select_statement cannot have an INTO clause.

As many rows are added to the table as are returned by select_statement. The query must return a value for every column in the column list or for every column in the table if no column list is supplied. As with the VALUES clause, there is a positional, one-to-one correspondence between select-list items and the columns in the column list.

Usage Notes

All character and date literals in the VALUES list must be enclosed by single quotes ('). Numeric literals are not enclosed by quotes.

The implicit SQL cursor and cursor attributes (%NOTFOUND, %FOUND, %ROWCOUNT, and %ISOPEN) let you access useful information about the execution of an INSERT statement. For more information, see the section "Cursor Management" in Chapter 4.

An INSERT statement might insert one or more rows, or it might insert no rows. If one or more rows are inserted, the following things occur:

•	SQL%NOTFOUND evaluates to FALSE

•	SQL%FOUND evaluates to TRUE

•	SQL%ROWCOUNT returns the number of rows inserted

If no rows are inserted, the following things occur:

•	SQL%NOTFOUND evaluates to TRUE

•	SQL%FOUND evaluates to FALSE

•	SQL%ROWCOUNT returns the number 0

Examples

INSERT INTO bonus SELECT ename, job, sal, comm FROM emp

   WHERE comm > sal * 0.25;

INSERT INTO emp (empno, ename, job, sal, comm, deptno)

   VALUES (4160, 'STURDEVIN', 'SECURITY GUARD', 2045, NULL, 30);

DECLARE

   my_deptno  NUMBER;

   my_dname   CHAR(15);

BEGIN

   my_deptno := 70;

   my_dname := 'Distribution';

   INSERT INTO dept

      VALUES (my_deptno, UPPER(my_dname), 'CHICAGO');

END;

________________________________________

%ISOPEN Attribute

Description

PL/SQL cursors have four attributes, including %ISOPEN, which, when appended to the cursor name, let you access useful information about the cursor. For more information, see the section "Cursor Management" in Chapter 4.

There are two kinds of cursors: implicit and explicit. PL/SQL implicitly declares a cursor for all SQL data manipulation statements, including single-row queries. ORACLE automatically closes the SQL cursor after executing its associated SQL statement, so %ISOPEN always evaluates to FALSE.

For multirow queries, you can explicitly declare a cursor to process the rows. %ISOPEN evaluates to TRUE if the cursor is open; otherwise, %ISOPEN evaluates to FALSE.

Syntax

Keyword and Parameter Description

 cursor_name

This identifier designates the implicit SQL cursor or names an explicitly declared cursor. For naming conventions, see the section "Identifiers" in Chapter 2.

Usage Notes

You can use the %ISOPEN attribute in procedural statements but not in SQL statements. %ISOPEN is associated with every explicit cursor. So, if you are unsure of a cursor's status, use the %ISOPEN attribute to see if the cursor is open. However, with the implicit SQL cursor, %ISOPEN always evaluates to FALSE.

Example

IF NOT (my_cursor%ISOPEN) THEN

   OPEN my_cursor;

END IF;

FETCH my_cursor INTO ...

Related Topics

CLOSE, Cursors, DELETE, FETCH, INSERT, OPEN, SELECT INTO, UPDATE

________________________________________

Literals

Description

A literal is an explicit numeric, character, string, or Boolean value not represented by an identifier. The numeric literal 135 and the string literal 'Tom & Jerry' are examples. For more information, see the section "Literals" in Chapter 2.

Syntax

Keyword and Parameter Description

 integer

This is an optionally signed whole number without a decimal point.

 real_number

This is an optionally signed whole or fractional number with a decimal point.

 digit

This must be one of the numerals 0 .. 9.

 char

This is a member of the PL/SQL character set. For more information, see the section "Character Set" in Chapter 2.

 TRUE, FALSE

This is a predefined Boolean value.

 NULL

This is a predefined non-value, which stands for a missing, unknown, or inapplicable value.

Usage Notes

Two kinds of numeric literals can be used in arithmetic expressions: integers and reals. Numeric literals must be separated by punctuation. Space characters can be used in addition to the punctuation.

A character literal is an individual character enclosed by single quotes (apostrophes). Character literals include all the printable characters in the PL/SQL character set: letters, numerals, spaces, and special symbols. PL/SQL is case sensitive within character literals. So, for example, PL/SQL considers the literals 'Q' and 'q' to be different.

A string literal is a sequence of zero or more characters enclosed by single quotes. The null string ('') contains zero characters. To represent an apostrophe within a string, write two single quotes. PL/SQL is case sensitive within string literals. So, for example, PL/SQL considers the literals 'white' and 'White' to be different.

Also, trailing blanks are significant within string literals, so 'White' and 'White  ' are different. How a string literal compares to a variable does not depend on the variable-trailing blanks in a literal are never trimmed.

Unlike the non-value NULL, the Boolean values TRUE and FALSE cannot be inserted into a database column.

Examples

Several examples of numeric literals follow:

25   6.34   7E2   25e-03   .1   1.   +17  -4.4

Several examples of character literals follow:

'H'   '&'   ' '   '9'   ']'   'g'

A few examples of string literals follow:

'$5,000'

'02-AUG-87'

'Don''t leave without saving your work.'

Related Topics

Variables and Constants

________________________________________

LOCK TABLE Statement

Description

The LOCK TABLE statement lets you lock entire database tables in a specified lock mode so that you can share or deny access to tables while maintaining their integrity. For more information, see the section "Using LOCK TABLE" in Chapter 4.

Syntax

Keyword and Parameter Description

 table_reference

The table or view specified by table_reference must be accessible when you execute the LOCK TABLE statement.

 lock_mode

This parameter specifies the lock mode. It must be one of the following: ROW SHARE, ROW EXCLUSIVE, SHARE UPDATE, SHARE, SHARE ROW EXCLUSIVE, or EXCLUSIVE.

 NOWAIT

This optional keyword tells ORACLE not to wait if the table has been locked by another user. Control is immediately returned to your program, so it can do other work before trying again to acquire the lock.

Usage Notes

If you omit the keyword NOWAIT, ORACLE waits until the table is available; the wait has no set limit. Table locks are released when your transaction issues a COMMIT or ROLLBACK. For more information, refer to the ORACLE7 Server SQL Language Reference Manual.

Example

The following statement locks the accts table in shared mode:

LOCK TABLE accts IN SHARE MODE;

Related Topics

COMMIT, DELETE, INSERT, ROLLBACK, SAVEPOINT, UPDATE

________________________________________

LOOP Statement

Description

The LOOP statement executes a sequence of statements multiple times. The loop encloses the sequence of statements that is to be repeated. PL/SQL supports the following four types of loops:

•	basic loops

•	WHILE loops

•	numeric FOR loops

•	cursor FOR loops

For more information, see the section "Iterative Control" in Chapter 3.

Syntax

Keyword and Parameter Description

 label_name

This is an undeclared identifier, which optionally labels a loop. For naming conventions, see the section "Identifiers" in Chapter 2. If used, label_name must be enclosed by double angle brackets and must appear at the beginning of the LOOP statement. Optionally, label_name can also appear at the end of the LOOP statement.

You can use label_name in an EXIT statement to exit the loop labeled by label_name.

You cannot reference the index of an outer loop from an inner (nested) loop if both indexes have the same name-unless the outer loop is labeled by label_name and you use dot notation, as follows:

label_name.index_name

In the following example, you compare two loop indexes that have the same name, one used by an enclosing loop, the other by a nested loop:

<<outer>>

FOR ctr IN 1..20 LOOP

   ...

   <<inner>>

   FOR ctr IN 1..10 LOOP

      IF outer.ctr > ctr THEN ...

         ...

   END LOOP inner;

END LOOP outer;

 seq_of_statements

This represents a sequence of statements to be repeated. For the syntax of seq_of_statements, see the section "Blocks" earlier in this chapter.

Basic Loops

The simplest form of LOOP statement is the basic (or infinite) loop, which encloses a sequence of statements between the keywords LOOP and END LOOP. With each iteration of the loop, the sequence of statements is executed, then control resumes at the top of the loop. If further processing is undesirable or impossible, you can use the EXIT, GOTO, or RAISE statement to complete the loop. A raised exception will also complete the loop.

WHILE Loops

 WHILE plsql_condition

The WHILE-LOOP statement associates a condition with a sequence of statements enclosed by the keywords LOOP and END LOOP. Before each iteration of the loop, the condition is evaluated. If the condition evaluates to TRUE, the sequence of statements is executed, then control resumes at the top of the loop. If the condition evaluates to FALSE or NULL, the loop is bypassed and control passes to the next statement.

For the syntax of plsql_condition, see the section "Conditions" earlier in this chapter.

Numeric FOR Loops

 FOR numeric_loop_param

Whereas the number of iterations through a WHILE loop is unknown until the loop completes, the number of iterations through a FOR loop is known before the loop is entered. Numeric FOR loops iterate over a specified range of integers. (Cursor FOR loops, which iterate over the active set of a cursor, are discussed later.) The range is part of an iteration scheme, which is enclosed by the keywords FOR and LOOP.

The range is evaluated when the FOR loop is first entered and is never re-evaluated. The seq_of_statements is executed once for each integer in the range defined by integer_expr..integer_expr. After each iteration, the loop index is incremented.

 index

This identifier names a loop index. For naming conventions, see the section "Identifiers" in Chapter 2.

You need not declare index. It is implicitly declared as a variable of type INTEGER. The scope of index is the loop itself. Therefore, you cannot access its value outside the loop.

The implicit declaration of index overrides any other declaration outside the loop. So, a variable declared with the same name as index outside the loop cannot be referenced inside the loop unless a label is used, as follows:

<<main>>

DECLARE

   num  NUMBER;

BEGIN

   ...

   FOR num IN 1..10 LOOP

      ...

      IF main.num > 5 THEN   -- refers to the explicitly

         ...                 -- declared num, not

                             -- the loop index

      END IF;

   END LOOP;

END main;

Inside the loop, index is treated like a constant. It can appear in expressions, but you cannot assign it a value.

 integer_expr

This parameter is an expression that evaluates to an integer. The expression is evaluated only when the loop is first entered.

By default, index is assigned the value of the left integer_expr. If it is not greater than the right integer_expr, the seq_of_statements is executed, then index is incremented. If index is still not greater than the right integer_expr, the seq_of_statements is executed again. The process repeats until index is greater than the right integer_expr. At this point, the loop completes.

 REVERSE

By default, iteration proceeds upward from the lower bound to the higher bound. However, if you use the keyword REVERSE, iteration proceeds downward from the higher bound to the lower bound. After each iteration, the loop index is decremented.

The index is assigned the value of the right integer_expr. If it is not less than the left integer_expr, the seq_of_statements is executed, then index is decremented. If index is still not less than the left integer_expr, the seq_of_statements is executed again. The process repeats until index is less than the left integer_expr, at which point the loop completes. An example follows:

FOR i IN REVERSE 1..10 LOOP  -- i starts at 10, ends at 1

   -- statements here execute 10 times

END LOOP;

Cursor FOR Loops

 FOR cursor_loop_param

A cursor FOR loop implicitly declares its loop index as a %ROWTYPE record, opens a cursor, repeatedly fetches rows of values from the active set into fields in the record, and closes the cursor when all rows have been processed.

When a cursor FOR loop is entered, an implicit OPEN cursor_name is executed. Then, for each row that satisfies the query associated with the cursor, an implicit FETCH is done into the implicitly declared record_name and the seq_of_statements is executed. When there are no more rows left to fetch, an implicit CLOSE cursor_name is executed and the loop completes. Thus, the seq_of_statements is executed once for each row that satisfies the query associated with cursor_name.

 record_name

This identifier names an implicitly declared record. For naming conventions, see the section "Identifiers" in Chapter 2.

The record has the same structure as a row retrieved by cursor_name and is equivalent to a record explicitly declared as follows:

record_name  cursor_name%ROWTYPE;

The record is defined only inside the loop. You cannot refer to its fields outside the loop.

Fields in the record hold column values from the implicitly FETCHed row. The fields have the same names and datatypes as their corresponding columns. To access field values, you use dot notation, as follows:

record_name.column_name

Select-list items fetched by the FOR loop cursor must have simple names or, if they are expressions, must have aliases. In the next example, wages is an alias for the select-list item sal+NVL(comm,0):

CURSOR c1 IS SELECT empno, sal+NVL(comm,0) wages, job ...

 cursor_name

This identifier names a previously declared cursor. For naming conventions, see the section "Identifiers" in Chapter 2.

When the cursor FOR loop is entered, cursor_name cannot refer to a cursor that is currently open as the result of an explicit OPEN or because cursor_name was used in an enclosing cursor FOR loop.

 parameter

This identifier names a formal cursor parameter. For naming conventions, see the section "Identifiers" in Chapter 2.

The syntax for parameter is the same as the syntax for plsql_expression, which is defined in the section "Expressions" earlier in this chapter.

If formal parameters are declared, actual parameters must be passed to the cursor. The values of actual parameters are used when the cursor is OPENed. Their datatypes must be the same as or convertible to the datatypes of corresponding formal parameters. For more information, see the section "Datatypes" in Chapter 2.

 select_statement

This is a query associated with an internal cursor unavailable to you. PL/SQL automatically declares, opens, fetches from, and closes the internal cursor. Because select_statement is not an independent statement, the implicit SQL cursor does not apply to it.

The syntax for select_statement is similar to the syntax for select_into_statement, defined in the section "SELECT INTO" later in this chapter, except that select_statement cannot have an INTO clause.

Usage Notes

You can use the EXIT WHEN statement to exit any loop prematurely. If the condition in the WHEN clause evaluates to TRUE, you exit the loop immediately. For more information, see the section "EXIT" earlier in this chapter.

When you leave a cursor FOR loop, the cursor is closed automatically even if you use an EXIT or GOTO statement to leave the loop prematurely. The cursor is also closed automatically if an exception is raised inside the loop.

Example

DECLARE

   bonus  REAL;

   CURSOR c1 IS SELECT empno, sal, comm FROM emp;

BEGIN

   FOR c1rec IN c1 LOOP

      bonus := (c1rec.sal * 0.05) + (c1rec.comm * 0.25);

      INSERT INTO bonuses VALUES (c1rec.empno, bonus);

   END LOOP;

   COMMIT;

END;

Related Topics

CLOSE, Conditions, Cursors, EXIT, FETCH, OPEN, %ROWTYPE

________________________________________

%NOTFOUND Attribute

Description

PL/SQL cursors have four attributes, including %NOTFOUND, which, when appended to the cursor name, let you access useful information about the cursor. For more information, see the section "Cursor Management" in Chapter 4.

There are two kinds of cursors: implicit and explicit. PL/SQL implicitly declares a cursor for all SQL data manipulation statements, including single-row queries. Until the SQL statement is executed, %NOTFOUND evaluates to NULL. Thereafter, %NOTFOUND evaluates to FALSE if an INSERT, UPDATE, or DELETE affected one or more rows or a SELECT INTO returned one or more rows. Otherwise, %NOTFOUND evaluates to TRUE.

For multirow queries, you can explicitly declare a cursor to process the rows. After the cursor is open but before the first fetch, %NOTFOUND evaluates to NULL. Thereafter, it evaluates to FALSE if the last fetch returned a row or to TRUE if no row was returned.

Syntax

Keyword and Parameter Description

 cursor_name

This identifier designates the implicit SQL cursor or names an explicitly declared cursor. For naming conventions, see the section "Identifiers" in Chapter 2.

Usage Notes

You can use the %NOTFOUND attribute in procedural statements but not in SQL statements. %NOTFOUND is associated with every explicit cursor. So, you can open multiple cursors, then use %NOTFOUND to tell which cursors have rows left to fetch. If a cursor is not open, referencing it with %NOTFOUND raises INVALID_CURSOR.

When an explicit cursor is opened, the rows that satisfy the associated query are identified and form the active set. Rows are fetched from the active set one at a time. If the last fetch returned a row, %NOTFOUND evaluates to FALSE. If the last fetch failed to return a row (because the active set was empty), %NOTFOUND evaluates to TRUE.

Examples

In the following example, %NOTFOUND is used to raise an exception if a deletion fails:

DELETE FROM parts WHERE status = 'OBSOLETE';

IF SQL%NOTFOUND THEN

   RAISE none_purged;

END IF;

The block in the next example returns a number from each of two tables, then inserts the sum of the numbers into a third table. It completes when all rows have been fetched from either of the two tables.

-- available online in file EXAMP13

DECLARE

   CURSOR num1_cur IS SELECT num FROM num1_tab

      ORDER BY sequence;

   CURSOR num2_cur IS SELECT num FROM num2_tab

      ORDER BY sequence;

   num1       num1_tab.num%TYPE;

   num2       num2_tab.num%TYPE;

   pair_num   NUMBER := 0;

BEGIN

   OPEN num1_cur;

   OPEN num2_cur;

   LOOP   -- loop through the two tables and get

          -- pairs of numbers

      FETCH num1_cur INTO num1;

      FETCH num2_cur INTO num2;

      EXIT WHEN (num1_cur%NOTFOUND) OR (num2_cur%NOTFOUND);

      pair_num := pair_num + 1;

      INSERT INTO sum_tab VALUES (pair_num, num1 + num2);

   END LOOP;

   CLOSE num1_cur;

   CLOSE num2_cur;

END;

Related Topics

CLOSE, Cursors, DELETE, FETCH, %FOUND, INSERT, OPEN, SELECT INTO, UPDATE

________________________________________

NULL Statement

Description

The NULL statement explicitly specifies inaction; it does nothing other than pass control to the next statement. In a construct allowing alternative actions, the NULL statement serves as a placeholder. For more information, see the section "Sequential Control" in Chapter 3.

Syntax

Usage Notes

The NULL statement improves readability by making the meaning and action of conditional statements clear. It tells readers that the associated alternative has not been overlooked, but that indeed no action is necessary.

Each clause in an IF statement must contain at least one executable statement. The NULL statement meets this requirement. So, you can use the NULL statement in clauses that correspond to circumstances in which no action is taken.

Do not confuse the NULL statement with the Boolean non-value NULL; they are unrelated.

Examples

In the following example, the NULL statement emphasizes that only salespeople receive commissions:

IF job_title = 'SALESPERSON' THEN

   compute_commission(emp_id);

ELSE

   NULL;

END IF;

In the next example, the NULL statement shows that no action is taken for unnamed exceptions:

EXCEPTION

   WHEN ZERO_DIVIDE THEN

      ROLLBACK;

   ...

   WHEN OTHERS THEN

      NULL;

END;

________________________________________

OPEN Statement

Description

The OPEN statement executes the query associated with an explicitly declared cursor. It also allocates resources used by ORACLE to process the query and identifies the active set, which consists of all rows that meet the query search criteria. The cursor is positioned before the first row in the active set. For more information, see the section "Transaction Processing" in Chapter 4.

Syntax

Keyword and Parameter Description

 cursor_name

This identifier names an explicitly declared cursor that is not currently open. For naming conventions, see the section "Identifiers" in Chapter 2.

 input_parameter

This identifier names a formal cursor parameter and is typically referenced in the WHERE clause. For naming conventions, see the section "Identifiers" in Chapter 2. The syntax for parameter is the same as the syntax for plsql_expression, which is defined in the section "Expressions" earlier in this chapter.

If formal parameters are declared, actual parameters must be passed to the cursor. The values of actual parameters are used when the cursor is OPENed. Their datatypes must be the same as or convertible to the datatypes of corresponding formal parameters. For more information, see the section "Datatypes" in Chapter 2. In addition to the actual parameters, the query can reference PL/SQL variables defined within its scope.

Unless you want to accept default values, each formal parameter in the cursor declaration must have a corresponding actual parameter in the OPEN statement. Formal parameters declared with a default value need not have a corresponding actual parameter. They can simply assume their default values when the OPEN statement is executed.

The formal parameters of a cursor must be IN parameters. Therefore, they cannot return values to actual parameters.

You can associate the actual parameters in an OPEN statement with the formal parameters in a cursor declaration using positional or named notation. For more information, see the section "Positional and Named Notation" in Chapter 6.

Usage Notes

Generally, PL/SQL parses an explicit cursor only the first time it is OPENed and parses a SQL statement (thereby creating an implicit cursor) only the first time the statement is executed.

All the parsed SQL statements are cached. A SQL statement must be reparsed only if it is bumped out of the cache by a new SQL statement.

So, although you must CLOSE a cursor before you can reOPEN it, PL/SQL need not reparse the associated SELECT statement. If you CLOSE, then immediately reOPEN the cursor, a reparse is definitely not needed.

Rows in the active set are not retrieved when the OPEN statement is executed. The FETCH statement retrieves the rows. With a FOR UPDATE cursor, the rows are locked when the cursor is OPENed.

If a cursor is currently open because you OPENed it, you cannot use the same cursor name in a cursor FOR loop.

Examples

Given the cursor declaration

CURSOR parts_cur IS SELECT part_num, part_price FROM parts;

the following statement opens the cursor:

OPEN parts_cur;

Given the cursor declaration

CURSOR emp_cur(my_ename CHAR, my_comm NUMBER DEFAULT 0)

   IS SELECT ...

any of the following statements opens the cursor:

OPEN emp_cur('BLAKE', 300);

OPEN emp_cur(employee_name, 150);

OPEN emp_cur('TRUSDALE', my_comm);

OPEN emp_cur('LEE');

In the last example, the variable referenced in the OPEN statement has the same name as the formal parameter in the cursor declaration. When my_comm is used in the cursor declaration, it refers to the formal parameter my_comm. When it is used outside the declaration, it refers to the variable my_comm. For clarity, use unique identifiers.

Related Topics

CLOSE, Cursors, FETCH, LOOP

________________________________________

Packages

Description

A package is a database object that groups logically related PL/SQL types, objects, and subprograms. Packages usually have two parts, a specification and a body, although sometimes the body is unnecessary. The specification is the interface to your applications; it declares the types, variables, constants, exceptions, cursors, and subprograms available for use. The body fully defines cursors and subprograms, and so implements the specification. For more information, see Chapter 7.

Syntax

Keyword and Parameter Description

 package_name

This identifier names a package. For naming conventions, see the section "Identifiers" in Chapter 2.

 variable_declaration

This construct declares variables and constants. For the syntax of variable_declaration, see the section "Variables and Constants" later in this chapter.

 cursor_declaration

This construct, which cannot contain a RETURN clause, declares an explicit cursor. For the syntax of cursor_declaration, see the section "Cursors" earlier in this chapter.

 cursor_specification

This construct declares the interface to an explicit cursor. For the syntax of cursor_specification, see the section "Cursors" earlier in this chapter.

 exception_declaration

This construct declares exceptions. For the syntax of exception_declaration, see the section "Exceptions" earlier in this chapter.

 record_declaration

This construct declares user-defined records. For the syntax of record_declaration, see the section "Records" later in this chapter.

 plsql_table_declaration

This construct declares PL/SQL tables. For the syntax of plsql_table_declaration, see the section "PL/SQL Tables" later in this chapter.

 procedure_specification

This construct declares the interface to a procedure. For the syntax of procedure_specification, see the section "Procedures" later in this chapter.

 function_specification

This construct declares the interface to a function. For the syntax of function_specification, see the section "Functions" earlier in this chapter.

 cursor_body

This construct defines the underlying implementation of an explicit cursor. For the syntax of cursor_body, see the section "Cursors" earlier in this chapter.

 procedure_body

This construct defines the underlying implementation of a procedure. For the syntax of procedure_body, see the section "Procedures" later in this chapter.

 function_body

This construct defines the underlying implementation of a function. For the syntax of function_body, see the section "Functions" earlier in this chapter.

 seq_of_statements

This represents a sequence of statements. For the syntax of seq_of_statements, see the section "Blocks" earlier in this chapter.

 exception_handler

This construct associates an exception with a sequence of statements, which is executed when that exception is raised. For the syntax of exception_handler, see the section "Exceptions" earlier in this chapter.

Usage Notes

Packages cannot be embedded in a PL/SQL block or subprogram. However, you can define packages using any ORACLE tool that supports PL/SQL.

To become available for general use, packages must be CREATEd and stored in an ORACLE database. You can issue the CREATE PACKAGE and CREATE PACKAGE BODY statements interactively from SQL*Plus or SQL*DBA and from an ORACLE Precompilers host program. For the full syntax of the CREATE statement, see the ORACLE7 Server SQL Language Reference Manual.

When designing an application, all you need initially is the interface information in the package specifications. You can code and compile a specification without its body. Once the specification has been compiled, stored subprograms that reference the package can be compiled as well. You need not define the package bodies fully until you are ready to complete the application.

Furthermore, you can debug, enhance, or replace a package body without changing the interface (package specification) to the package body. That means you need not recompile calling programs.

Cursors and subprograms declared in a package specification must be defined in the package body. Other program objects declared in the package specification cannot be redeclared in the package body.

Related Topics

Cursors, Exceptions, Functions, PL/SQL Tables, Procedures, Records

________________________________________

PL/SQL Tables

Description

PL/SQL tables are objects of type TABLE, which are modelled as (but not the same as) database tables. PL/SQL tables use a primary key to give you array-like access to rows. Like the size of a database table, the size of a PL/SQL table is unconstrained. That is, the number of rows in a PL/SQL table can increase dynamically. For more information, see the section "PL/SQL Tables" in Chapter 2.

PL/SQL tables must be declared in two steps. First, you define a TABLE type, then declare PL/SQL tables of that type.

Syntax

Keyword and Parameter Description

 type_name

This identifier names a user-defined type specifier, which is used in subsequent declarations of PL/SQL tables. For naming conventions, see the section "Identifiers" in Chapter 2.

 column_type

This specifies the datatype of the column in a PL/SQL table. It can be any scalar (not composite) datatype. For more information, see the section "Datatypes" in Chapter 2.

 table.column

This refers to a table and column that must be accessible when the declaration is elaborated.

 INDEX BY BINARY INTEGER

The primary key of a PL/SQL table must belong to type BINARY_INTEGER, which can represent signed integers of any practical size. The magnitude range of a BINARY_INTEGER value is -231- 1 .. 231- 1 (-2147483647 .. 2147483647).

 plsql_table_name

The identifier names an entire PL/SQL table. For naming conventions, see the section "Identifiers" in Chapter 2.

Usage Notes

You can declare TABLE types and PL/SQL tables in the declarative part of any block, subprogram, or package. PL/SQL tables can have one column and a primary key, neither of which can be named. The column can belong to any scalar type, but the primary key must belong to type BINARY_INTEGER. You can use the %TYPE attribute to specify a column datatype.

Unlike an array, a PL/SQL table is unconstrained (not of fixed size) because its primary key can assume any value in the range of values defined for BINARY_INTEGER. As a result, you cannot initialize a PL/SQL table in its declaration. For example, the following declaration is invalid:

job_tab  JobTabTyp := ('CLERK', 'ANALYST', 'MANAGER');

The first reference to a row in a PL/SQL table must be an assignment. Otherwise, the predefined exception NO_DATA_FOUND is raised.

PL/SQL tables follow the usual scoping and instantiation rules. In a package, they are instantiated when you first reference the package and cease to exist when you exit the application or end the database session. In a block or subprogram, they are instantiated when you enter the block or subprogram and cease to exist when you exit the block or subprogram.

Like scalar variables, PL/SQL tables can be declared as the formal parameters of procedures and functions. The restrictions that apply to scalar parameters also apply to PL/SQL tables.

Examples

In the following example, you declare a TABLE type named SalTabTyp:

DECLARE

   TYPE SalTabTyp IS TABLE OF NUMBER(7,2)

      INDEX BY BINARY_INTEGER;

   ...

You could have used %TYPE to provide the column datatype, as follows:

DECLARE

   TYPE SalTabTyp IS TABLE OF emp.sal%TYPE

      INDEX BY BINARY_INTEGER;

   ...

Once you define type SalTabTyp, you can declare PL/SQL tables of that type, as follows:

sal_tab  SalTabTyp;

The identifier sal_tab represents an entire PL/SQL table.

In the following example, you assign the sum of variables salary and increase to the tenth row in PL/SQL table sal_tab:

sal_tab(10) := salary * increase;

Related Topics

Assignment Statement, Functions, Procedures, Records

________________________________________

Procedures

Description

A procedure is a named PL/SQL block, which can take parameters and be invoked. Generally, you use a procedure to perform an action. For more information, see the section "Procedures" in Chapter 6.

A procedure has two parts: the specification and the body. The procedure specification begins with the keyword PROCEDURE and ends with the procedure name or a parameter list. Parameter declarations are optional. Procedures that take no parameters are written without parentheses.

The procedure body begins with the keyword IS and ends with the keyword END followed by an optional procedure name. The procedure body has three parts: a declarative part, an executable part, and an optional exception-handling part.

The declarative part contains declarations of types, cursors, constants, variables, exceptions, and subprograms. These objects are local and cease to exist when you exit the procedure. The executable part contains statements that assign values, control execution, and manipulate ORACLE data. The exception-handling part contains exception handlers, which deal with exceptions raised during execution.

Syntax

Keyword and Parameter Description

 procedure_name

This identifier names a procedure. For naming conventions, see the section "Identifiers" in Chapter 2.

 variable_declaration

This construct declares variables and constants. For the syntax of variable_declaration, see the section "Variables and Constants" later in this chapter.

 cursor_declaration

This construct declares an explicit cursor. For the syntax of cursor_declaration, see the section "Cursors" earlier in this chapter.

 exception_declaration

This construct declares exceptions. For the syntax of exception_declaration, see the section "Exceptions" earlier in this chapter.

 record_declaration

This construct declares user-defined records. For the syntax of record_declaration, see the section "Records" later in this chapter.

 plsql_table_declaration

This construct declares PL/SQL tables. For the syntax of plsql_table_declaration, see the section "PL/SQL Tables" earlier in this chapter.

 procedure_declaration

This construct declares a nested procedure.

 function_declaration

This construct declares a function. For the syntax of function_declaration, see the section "Functions" earlier in this chapter.

 seq_of_statements

This represents a sequence of statements. For the syntax of seq_of_statements, see the section "Blocks" earlier in this chapter.

 exception_handler

This construct associates an exception with a sequence of statements, which is executed when that exception is raised. For the syntax of exception_handler, see the section "Exceptions" earlier in this chapter.

 parameter_name

This identifier names a formal parameter, which is a variable declared in a procedure specification and referenced in the procedure body. For naming conventions, see the section "Identifiers" in Chapter 2.

 IN, OUT, IN OUT

These parameter modes define the behavior of formal parameters. The IN parameter mode lets you pass values to the subprogram being called. An OUT parameter lets you return values to the caller of the subprogram. An IN OUT parameter lets you pass initial values to the subprogram being called and return updated values to the caller.

 type_name

This specifies the datatype of a formal parameter. For more information, see the section "Datatypes" in Chapter 2.

Unlike the datatype specifier in a variable declaration, the datatype specifier in a parameter declaration must be unconstrained. For example, the following declaration of emp_name is illegal:

PROCEDURE ... (emp_name CHAR(20)) IS  -- illegal

BEGIN ... END;

 table.column

This refers to a database table and column that must be accessible when the declaration is elaborated.

 %TYPE

The %TYPE attribute provides the datatype of a variable, constant, or database column.

 table

This refers to a database table that must be accessible when the declaration is elaborated.

 %ROWTYPE

The %ROWTYPE attribute provides a record that represents a row in a database table. Columns in a row and corresponding fields in a record have the same names and datatypes.

Usage Notes

At least one statement must appear in the executable part of a procedure. The NULL statement meets this requirement.

A procedure is called as a PL/SQL statement. For example, the procedure raise_salary might be called as follows:

raise_salary(emp_num, amount);

Inside a procedure, an IN parameter acts like a constant. Therefore, it cannot be assigned a value. An OUT parameter acts like an uninitialized variable. So, its value cannot be assigned to another variable or reassigned to itself. An IN OUT parameter acts like an initialized variable. Therefore, it can be assigned a value, and its value can be assigned to another variable. For summary information about the parameter modes, see Table 6-1 in Chapter 6.

Before exiting a procedure, explicitly assign values to all OUT formal parameters. Otherwise, the values of corresponding actual parameters are indeterminate. If you exit successfully, PL/SQL assigns values to the actual parameters. However, if you exit with an unhandled exception, PL/SQL does not assign values to the actual parameters.

Unlike OUT and IN OUT parameters, IN parameters can be initialized to default values. For more information, see the section "Parameter Default Values" in Chapter 6.

You can write the procedure specification and body as a unit. Or, you can separate the procedure specification from its body. That way, you can hide implementation details by placing the procedure in a package. You can define procedures in a package body without declaring their specifications in the package specification. However, such procedures can be called only from inside the package.

Procedures can be defined using any ORACLE tool that supports PL/SQL. To become available for general use, however, procedures must be CREATEd and stored in an ORACLE database. You can issue the CREATE PROCEDURE statement interactively from SQL*Plus or SQL*DBA. For the full syntax of the CREATE statement, see the ORACLE7 Server SQL Language Reference Manual.

Example

The following procedure debits a bank account:

PROCEDURE debit_account (acct_id INTEGER, amount REAL) IS

   old_balance  REAL;

   new_balance  REAL;

   overdrawn    EXCEPTION;

BEGIN

   SELECT bal INTO old_balance FROM accts WHERE acctno = acct_id;

   new_balance := old_balance - amount;

   IF new_balance < 0 THEN

      RAISE overdrawn;

   ELSE

      UPDATE accts SET bal = new_balance WHERE acctno = acct_id;

   END IF;

EXCEPTION

   WHEN overdrawn THEN

      ...

END debit_account;

In the following example, you call the procedure using named notation:

debit_account(amount => 500, acct_id => 10261);

Related Topics

Cursors, Exceptions, Functions, Packages, PL/SQL Tables, Records

________________________________________

RAISE Statement

Description

The RAISE statement stops normal execution of a PL/SQL block or subprogram and transfers control to the appropriate exception handler. For more information, see the section "User-defined Exceptions" in Chapter 5.

Normally, predefined exceptions are raised implicitly by the runtime system. However, RAISE statements can also raise predefined exceptions. User-defined exceptions must be raised explicitly by RAISE statements.

Syntax

Keyword and Parameter Description

 exception_name

This identifier names a predefined or user-defined exception. For naming conventions, see the section "Identifiers" in Chapter 2. Fora list of the predefined exceptions, see the section "Predefined Exceptions" in Chapter 5.

Usage Notes

PL/SQL blocks and subprograms should RAISE an exception only when an error makes it impractical or impossible to finish processing. You can code a RAISE statement for a given exception anywhere within the scope of that exception.

When an exception is raised, if PL/SQL cannot find a handler for it in the current block or subprogram, the exception propagates. That is, the exception reproduces itself in successive enclosing blocks until a handler is found or there are no more blocks to search. In the latter case, PL/SQL returns an "unhandled exception" error to the host environment.

Omitting the exception name in a RAISE statement-allowed only in an exception handler-reraises the current exception. When a parameterless RAISE statement executes in an exception handler, the first block searched is the enclosing block, not the current block.

IF quantity_on_hand = 0 THEN

   RAISE out_of_stock;

END IF;

Examples

As the following example shows, you can raise a predefined exception explicitly:

RAISE INVALID_NUMBER;

Related Topics

Exceptions

________________________________________

Records

Description

Records are objects of type RECORD. Records have uniquely named fields that can store data values of different types. For more information, see the section "User-defined Records" in Chapter 2.

Records must be declared in two steps. First, you define a RECORD type, then declare user-defined records of that type.

Syntax

Keyword and Parameter Description

 type_name

This identifier names a user-defined type specifier, which is used in subsequent declarations of records. For naming conventions, see the section "Identifiers" in Chapter 2.

 field_name

This identifier names a field in a user-defined record. For naming conventions, see the section "Identifiers" in Chapter 2.

 field_type

This specifies the datatype of a field in a user-defined record. It can be any datatype including RECORD and TABLE. For more information, see the section "Datatypes" in Chapter 2.

 table

This refers to a table that must be accessible when the declaration is elaborated.

 table.column

This refers to a table and column that must be accessible when the declaration is elaborated.

 table

This refers to a table that must be accessible when the declaration is elaborated.

 NOT NULL

This constraint prevents the assigning of nulls to a field. Trying to assign a null to a field defined as NOT NULL raises the predefined exception VALUE_ERROR.

 record_name

This identifier names a user-defined record. For naming conventions, see the section "Identifiers" in Chapter 2.

Usage Notes

You can declare RECORD types and user-defined records in the declarative part of any block, subprogram, or package. Furthermore, a record can be initialized in its declaration, as the following example shows:

DECLARE

   TYPE TimeTyp IS RECORD(

      second  SMALLINT := 0,

      minute  SMALLINT := 0,

      hour    SMALLINT := 0);

   ...

The next example shows that you can use the %TYPE attribute to specify a field datatype. It also shows that you can add the NOT NULL constraint to any field declaration and so prevent the assigning of nulls to that field.

DECLARE

   TYPE DeptRecTyp IS RECORD(

      deptno  NUMBER(2) NOT NULL,

      dname   dept.dname%TYPE,

      loc     dept.loc%TYPE);

   dept_rec  DeptRecTyp;

   ...

To reference individual fields in a record, you use dot notation. For example, you might assign a value to the dname field in the dept_rec record as follows:

dept_rec.dname := 'PURCHASING';

Instead of assigning values separately to each field in a record, you can assign values to all fields at once. This can be done in two ways. First, PL/SQL lets you assign one record to another if they belong to the same datatype. Note, however, that even if their fields match exactly, a user-defined record and a %ROWTYPE record belong to different types. Second, you can assign a list of column values to a record by using the SELECT or FETCH statement. Just make sure the column names appear in the same order as the fields in your record.

You can declare and reference nested records. That is, a record can be the component of another record, as the following example shows:

DECLARE

   TYPE TimeTyp IS RECORD(

      minute  SMALLINT,

      hour    SMALLINT);

   TYPE MeetingTyp IS RECORD(

      day      DATE,

      time     TimeTyp,     -- nested record

      place    CHAR(20),

      purpose  CHAR(50));

   TYPE PartyTyp IS RECORD(

      day   DATE,

      time  TimeTyp,        -- nested record

      loc   CHAR(15));

   meeting  MeetingTyp;

   seminar  MeetingTyp;

   party    PartyTyp;

   ...

The next example shows that you can assign one nested record to another if they belong to the same datatype:

seminar.time := meeting.time;

Such assignments are allowed even if the containing records belong to different datatypes as in

party.time := meeting.time;

User-defined records follow the usual scoping and instantiation rules. In a package, they are instantiated when you first reference the package and cease to exist when you exit the application or end the database session. In a block or subprogram, they are instantiated when you enter the block or subprogram and cease to exist when you exit the block or subprogram.

Like scalar variables, user-defined records can be declared as the formal parameters of procedures and functions. The restrictions that apply to scalar parameters also apply to user-defined records.

Examples

In the following example, you declare a RECORD type named DeptRecTyp and a record named dept_rec, then select a row of values into the record:

DECLARE

   TYPE DeptRecTyp IS RECORD(

      deptno  NUMBER(2),

      dname   CHAR(14),

      loc     CHAR(13));

   dept_rec  DeptRecTyp;

   ...

BEGIN

   SELECT deptno, dname, loc INTO dept_rec FROM dept

      WHERE deptno = 20;

   ...

END;

Related Topics

Assignment Statement, Functions, PL/SQL Tables, Procedures

________________________________________

RETURN Statement

Description

The RETURN statement immediately completes the execution of a subprogram and returns control to the caller. Execution then resumes with the statement following the subprogram call. In a function, the RETURN statement also sets the function identifier to the result value. (Do not confuse the RETURN statement with the RETURN clause, which specifies the datatype of the result value in a function specification.) For more information, see the section "Functions" in Chapter 6.

Syntax

Keyword and Parameter Description

 plsql_expression

This is an arbitrarily complex expression. It is evaluated when the RETURN statement is executed. The syntax for plsql_expression is defined in the section "Expressions" earlier in this chapter.

The value of plsql_expression is assigned to a function identifier. The datatype of plsql_expression must be the same as or convertible to the datatype specified in the RETURN clause of the function specification. For more information, see the section "Datatype Conversion" in Chapter 2.

Usage Notes

A subprogram can contain several RETURN statements, none of which need be the last lexical statement. Executing any of them completes the subprogram immediately. However, it is poor programming practice to have multiple exit points in a subprogram.

In procedures, a RETURN statement cannot contain an expression. The statement simply returns control to the caller before the normal end of the procedure is reached.

However, in functions, a RETURN statement must contain an expression, which is evaluated when the RETURN statement is executed. The resulting value is assigned to the function identifier. Therefore, a function must contain at least one RETURN statement. Otherwise, PL/SQL raises the predefined exception PROGRAM_ERROR at runtime.

The RETURN statement can also be used in an anonymous block to exit the block (and all enclosing blocks) immediately, but the RETURN statement cannot contain an expression.

Example

In the following example, the function balance RETURNs the balance of a specified bank account:

FUNCTION balance (acct_id INTEGER) RETURN REAL IS

    acct_bal  REAL;

BEGIN

    SELECT bal INTO acct_bal FROM accts WHERE acctno = acct_id;

    RETURN acct_bal;

END balance;

________________________________________

ROLLBACK Statement

Description

The ROLLBACK statement is the inverse of the COMMIT statement. It undoes some or all database changes made during the current transaction. For more information, see the section "Transaction Processing" in Chapter 4.

Syntax

Keyword and Parameter Description

 ROLLBACK

When a parameterless ROLLBACK statement is executed, all database changes made during the current transaction are undone.

 WORK

The keyword WORK is optional and has no effect except to improve readability.

 ROLLBACK TO savepoint_name

The ROLLBACK TO statement undoes all database changes (and releases all locks acquired) since the savepoint identified by savepoint_name was marked. The identifier savepoint_name names a savepoint that was marked earlier in the current transaction using the SAVEPOINT statement. For naming conventions, see the section "Identifiers" in Chapter 2.

 SAVEPOINT

This keyword is optional and has no effect except to improve readability.

 COMMENT

The keyword COMMENT specifies a comment to be associated with the current transaction and is typically used with distributed transactions. The text must be a quoted literal <50 characters in length.

Usage Notes

All savepoints marked after the savepoint to which you roll back are erased. However, the savepoint to which you roll back is not erased. For example, if you mark savepoints A, B, C, and D in that order, then ROLLBACK TO savepoint B, only savepoints C and D are erased.

An implicit savepoint is marked before executing an INSERT, UPDATE, or DELETE statement. If the statement fails, a ROLLBACK to the implicit savepoint is done. Normally, just the failed SQL statement is rolled back, not the whole transaction. However, if the statement raises an unhandled exception, the host environment determines what is rolled back. For more information, see the section "Unhandled Exceptions" in Chapter 5.

When a distributed transaction fails, the text specified by COMMENT helps you diagnose the problem. If a distributed transaction is ever in doubt, ORACLE stores the text in the data dictionary along with the transaction ID. For more information about distributed transactions, see the ORACLE7 Server Application Developer's Guide.

Related Topics

COMMIT, SAVEPOINT

________________________________________

%ROWCOUNT Attribute

Description

PL/SQL cursors have four attributes, including %ROWCOUNT, which, when appended to the cursor name, let you access useful information about the cursor. For more information, see the section "Cursor Management" in Chapter 4.

There are two kinds of cursors: implicit and explicit. PL/SQL implicitly declares a cursor for all SQL data manipulation statements, including single-row queries. Until the SQL statement is executed, %ROWCOUNT returns a null. Thereafter, %ROWCOUNT returns the number of rows affected by an INSERT, UPDATE, or DELETE or returned by a SELECT INTO. %ROWCOUNT returns a zero if an INSERT, UPDATE, or DELETE affected no rows or a SELECT INTO returned no rows.

For multirow queries, you can explicitly declare a cursor to process the rows. When you open its cursor, %ROWCOUNT is zeroed. Before the first fetch, %ROWCOUNT returns a zero. Thereafter, it returns the number of rows fetched so far. The number is incremented if the latest fetch returned a row.

Syntax

Keyword and Parameter Description

 cursor_name

This identifier designates the implicit SQL cursor or names an explicitly declared cursor. For naming conventions, see the section "Identifiers" in Chapter 2.

Usage Notes

You can use the %ROWCOUNT attribute in procedural statements but not in SQL statements. %ROWCOUNT is associated with every explicit cursor. So, you can open multiple cursors, then use %ROWCOUNT to tell how many rows have been fetched so far. If a cursor is not open, referencing it with %ROWCOUNT raises INVALID_CURSOR.

If a SELECT INTO returns more than one row, the predefined exception TOO_MANY_ROWS is raised and %ROWCOUNT is set to 1, not the actual number of rows that satisfy the query.

Examples

The block in the following example returns the name, employee number, and salary of the five highest-paid employees:

-- available online in file EXAMP14

DECLARE

   CURSOR c1 is

   SELECT ename, empno, sal FROM emp

      ORDER BY sal DESC;   -- start with highest-paid employee

   my_ename  CHAR(10);

   my_empno  NUMBER(4);

   my_sal    NUMBER(7,2);

BEGIN

   OPEN c1;

   LOOP

      FETCH c1 INTO my_ename, my_empno, my_sal;

      EXIT WHEN (c1%ROWCOUNT > 5) OR (c1%NOTFOUND);

      INSERT INTO temp VALUES (my_sal, my_empno, my_ename);

      COMMIT;

   END LOOP;

   CLOSE c1;

END;

In the next example, %ROWCOUNT is used to raise an exception if an unexpectedly high number of rows is deleted:

DELETE FROM accts WHERE status = 'BAD DEBT';

IF SQL%ROWCOUNT > 10 THEN

    RAISE out_of_bounds;

END IF;

Related Topics

CLOSE, Cursors, FETCH, INSERT, OPEN, SELECT INTO, UPDATE

________________________________________

%ROWTYPE Attribute

Description

The %ROWTYPE attribute provides a record that represents a row in a table (or view). The record can store an entire row of data selected from the table or fetched by a cursor. Columns in a row and corresponding fields in a record have the same names and datatypes.

You use the %ROWTYPE attribute in variable declarations as a datatype specifier. Variables declared using %ROWTYPE are treated like those declared using a datatype name. For more information, see the section "Using %ROWTYPE" in Chapter 2.

Syntax

Keyword and Parameter Description

 identifier

This identifier names a previously declared cursor. For naming conventions, see the section "Identifiers" in Chapter 2.

Alternatively, this identifier names a database table (or view). You can precede the table name with an owner name, as in

scott.dept

The table must be accessible when the declaration is elaborated.

Usage Notes

The %ROWTYPE attribute lets you declare records structured like a row of data in a database table. In the following example, you declare a record that can store an entire row from the emp table:

emp_rec  emp%ROWTYPE;

The column values returned by the SELECT statement are stored in fields. To reference a field, you use dot notation. For example, you might reference the deptno field as follows:

IF emp_rec.deptno = 20 THEN ...

In addition, you can assign the value of an expression to a specific field, as the following example shows:

emp_rec.sal := average * 1.15;

There are two ways to assign values to all fields in a record at once. First, PL/SQL allows aggregate assignment between entire records if their declarations refer to the same table or cursor. Second, you can assign a list of column values to a record by using the SELECT or FETCH statement. The column names must appear in the order in which they were defined by CREATE TABLE or CREATE VIEW. Select-list items fetched by a cursor associated with %ROWTYPE must have simple names or, if they are expressions, must have aliases.

Examples

In the example below, you use %ROWTYPE to declare two records. The first record stores a row selected from the emp table. The second record stores a row fetched by the c1 cursor.

DECLARE

   emp_rec   emp%ROWTYPE;

   CURSOR c1 IS SELECT deptno, dname, loc FROM dept;

   dept_rec  c1%ROWTYPE;

   ...

In the next example, you select a row from the emp table into a %ROWTYPE record:

DECLARE

   emp_rec  emp%ROWTYPE;

   ...

BEGIN

   SELECT * INTO emp_rec FROM emp WHERE empno = my_empno;

   IF (emp_rec.deptno = 20) AND (emp_rec.sal > 2000) THEN

      ...

   END IF;

END;

Related Topics

Cursors, FETCH, Variables and Constants

________________________________________

SAVEPOINT Statement

Description

The SAVEPOINT statement names and marks the current point in the processing of a transaction. With the ROLLBACK TO statement, savepoints let you undo parts of a transaction instead of the whole transaction. For more information, see the section "Transaction Processing" in Chapter 4.

Syntax

Keyword and Parameter Description

 savepoint_name

This is an undeclared identifier, which names the current point in the processing of a transaction. For naming conventions, see the section "Identifiers" in Chapter 2.

Usage Notes

When you roll back to a savepoint, any savepoints marked after that savepoint are erased. However, the savepoint to which you roll back is not erased. A simple ROLLBACK or COMMIT erases all savepoints.

If you mark a savepoint within a recursive subprogram, new instances of the SAVEPOINT statement are executed at each level in the recursive descent. However, you can only ROLLBACK TO the most recently marked savepoint.

Savepoint names can be reused within a transaction. This moves the savepoint from its old position to the current point in the transaction.

An implicit savepoint is marked before executing an INSERT, UPDATE, or DELETE statement. If the statement fails, a ROLLBACK to the implicit savepoint is done. Normally, just the failed SQL statement is rolled back, not the whole transaction. However, if the statement raises an unhandled exception, the host environment determines what is rolled back. For more information, see the section "Unhandled Exceptions" in Chapter 5.

By default, the number of active savepoints per user process is limited to 5. You or your DBA can raise the limit (up to 255) by increasing the value of the ORACLE initialization parameter SAVEPOINTS.

Related Topics

COMMIT, ROLLBACK

________________________________________

SELECT INTO Statement

Description

The SELECT INTO statement retrieves data from one or more database tables, then assigns the selected values to variables. For a full description of the SELECT statement, see the ORACLE7 Server SQL Language Reference Manual.

Syntax

Keyword and Parameter Description

 select_list_item

This parameter retrieves a value for each select_list_item in the select list, then assigns the values to corresponding variables in the variable_name list or to corresponding fields in record_name.

 INTO variable_name

This parameter defines which scalar variables will store the retrieved data. All variables in the variable_name list must be previously declared.

For each select_list_item in the select list, there must be a corresponding variable in the variable_name list. Also, the datatype of the value returned by each select_list_item must be the same as or convertible to the datatype of each corresponding variable. For more information, see the section "Datatype Conversion" in Chapter 2.

 INTO record_name

This parameter indicates that retrieved data is stored in a record variable declared using the %ROWTYPE attribute. An example follows:

DECLARE

   dept_rec  dept%ROWTYPE;

   ...

BEGIN

   SELECT deptno, dname, loc INTO dept_rec FROM dept

      WHERE deptno = 20;

   ...

END;

You use dot notation to access field values, as the following example shows:

dept_rec.deptno

 table_reference

The table or view specified by table_reference must be accessible when you execute the SELECT statement.

 alias

This is another (usually short) name for the referenced column, table, or view, and can be used in the WHERE clause.

 rest_of_select_statement

This parameter is anything that can legally follow the FROM clause in a SELECT statement.

Usage Notes

The implicit SQL cursor and the cursor attributes %NOTFOUND, %FOUND, %ROWCOUNT, and %ISOPEN let you access useful information about the execution of a SELECT INTO statement. For more information, see the section "Cursor Management" in Chapter 4.

When you assign values to variables using a SELECT INTO statement, the SELECT must return only one row from the table. If more than one row is returned, the following things occur:

•	the predefined exception TOO_MANY_ROWS is raised

•	SQLCODE returns -1422 (ORACLE error code ORA-01422)

•	SQLERRM returns ORACLE error message "single-row query returns more than one row"

•	SQL%NOTFOUND evaluates to FALSE

•	SQL%FOUND evaluates to TRUE

•	SQL%ROWCOUNT returns the number 1

If no rows are returned, the following things occur:

•	the predefined exception NO_DATA_FOUND is raised unless the SELECT called a SQL group function (see note below)

•	SQLCODE returns +100 (ORACLE error code ORA-01403)

•	SQLERRM returns ORACLE error message "no data found"

•	SQL%NOTFOUND evaluates to TRUE

•	SQL%FOUND evaluates to FALSE

•	SQL%ROWCOUNT returns the number 0

SQL group functions such as AVG and SUM always return a value or a null. So, a SELECT INTO that calls a group function never raises the predefined exception NO_DATA_FOUND.

Example

SELECT ename, job, sal*1.1 INTO my_ename, my_job, wages FROM emp

   WHERE empno = my_empno;

Related Topics

Assignment Statement, FETCH, %ROWTYPE

________________________________________

SET TRANSACTION Statement

Description

The SET TRANSACTION statement establishes a read-only transaction, which lets you query multiple tables while other users update the same tables. For more information, see the section "Using SET TRANSACTION" in Chapter 4.

Syntax

Keyword and Parameter Description

 READ ONLY

This parameter is required. If a transaction is set to READ ONLY, subsequent queries see only changes committed before the transaction began. The use of READ ONLY does not affect other users or transactions.

Usage Notes

The SET TRANSACTION statement must be the first SQL statement in a read-only transaction and can only appear once in a transaction. Furthermore, only the SELECT, COMMIT, and ROLLBACK statements are allowed in a read-only transaction. For example, including an INSERT or DELETE statement raises an exception.

Example

COMMIT;

SET TRANSACTION READ ONLY;

SELECT ... FROM emp WHERE ...

SELECT ... FROM dept WHERE ...

SELECT ... FROM emp WHERE ...

COMMIT;

Related Topics

COMMIT, ROLLBACK, SAVEPOINT

________________________________________

SQL Cursor

Description

ORACLE implicitly opens a cursor to process each SQL statement not associated with an explicitly declared cursor. PL/SQL lets you refer to the most recent implicit cursor as the "SQL" cursor. The SQL cursor has four attributes: %NOTFOUND, %FOUND, %ROWCOUNT, and %ISOPEN. When appended to the cursor name (SQL), these attributes let you access information about the execution of INSERT, UPDATE, DELETE, and SELECT INTO statements. For more information, see the section "Cursor Management" in Chapter 4.

Syntax

Keyword and Parameter Description

 %NOTFOUND

%NOTFOUND evaluates to TRUE if an INSERT, UPDATE, or DELETE affected no rows or a SELECT INTO returned no rows. Otherwise, %NOTFOUND evaluates to FALSE. If a SELECT INTO fails to return a row, the predefined exception NO_DATA_FOUND is raised whether you check %NOTFOUND on the next line or not. However, a SELECT INTO that calls a SQL group function never raises the exception NO_DATA_FOUND. That is because group functions such as AVG and SUM always return a value or a null. In such cases, %NOTFOUND always evaluates to FALSE.

 %FOUND

%FOUND is the logical opposite of %NOTFOUND. %FOUND evaluates to TRUE if an INSERT, UPDATE, or DELETE affected one or more rows or a SELECT INTO returned one or more rows. Otherwise, %FOUND evaluates to FALSE.

 %ROWCOUNT

%ROWCOUNT returns the number of rows affected by an INSERT, UPDATE, or DELETE or returned by a SELECT INTO.

 %ISOPEN

ORACLE automatically closes the SQL cursor after executing its associated SQL statement. As a result, %ISOPEN always evaluates to FALSE.

Usage Notes

You can use cursor attributes in procedural statements but not in SQL statements. Before ORACLE opens the SQL cursor automatically, the implicit cursor attributes evaluate to NULL.

The values of cursor attributes always refer to the most recently executed SQL statement, wherever that statement appears. It might be in a different scope. So, if you want to save an attribute value for later use, assign it to a Boolean variable immediately.

Examples

In the following example, %NOTFOUND is used to insert a row if an update affects no rows:

UPDATE emp SET sal = sal * 1.05 WHERE empno = my_empno;

IF SQL%NOTFOUND THEN

   INSERT INTO emp VALUES (my_empno, my_ename, ...);

END IF;

In the next example, you use %ROWCOUNT to act if more than 100 rows are deleted:

DELETE FROM parts WHERE status = 'OBSOLETE';

IF SQL%ROWCOUNT > 100 THEN

   ...  -- more than 100 rows were deleted

END IF;

Related Topics

%FOUND, %NOTFOUND, %ISOPEN, %ROWCOUNT

________________________________________

SQLCODE Function

Description

The function SQLCODE returns the number code associated with the most recently raised exception. SQLCODE is meaningful only in an exception handler. Outside a handler, SQLCODE always returns zero.

For internal exceptions, SQLCODE returns the number of the associated ORACLE error. The number that SQLCODE returns is negative unless the ORACLE error is no data found, in which case SQLCODE returns +100. For user-defined exceptions, SQLCODE returns +1 unless you used the pragma EXCEPTION_INIT to associate the exception with an ORACLE error number, in which case SQLCODE returns that error number. For more information, see the section "Using SQLCODE and SQLERRM" in Chapter 5.

Syntax

Usage Notes

You cannot use SQLCODE directly in a SQL statement. For example, the following statement is illegal:

INSERT INTO errors VALUES (SQLCODE, ...);

Instead, you must assign the value of SQLCODE to a local variable, then use the variable in the SQL statement, as follows:

DECLARE

   my_sqlcode  NUMBER;

BEGIN

   ...

EXCEPTION

   ...

   WHEN OTHERS THEN

      my_sqlcode := SQLCODE;

      INSERT INTO errors VALUES (my_sqlcode, ...);

END;

SQLCODE is especially useful in the OTHERS exception handler because it lets you identify which internal exception was raised.

Related Topics

Exceptions, SQLERRM

________________________________________

SQLERRM Function

Description

The function SQLERRM returns the error message associated with its error-number argument or, if the argument is omitted, with the current value of SQLCODE. SQLERRM with no argument is meaningful only in an exception handler. Outside a handler, SQLERRM with no argument always returns the following message:

ORA-0000: normal, successful completion

For internal exceptions, SQLERRM returns the message associated with the ORACLE error that occurred. The message begins with the ORACLE error code.

For user-defined exceptions, SQLERRM returns the message

User-Defined Exception

unless you used the pragma EXCEPTION_INIT to associate the exception with an ORACLE error number, in which case SQLERRM returns the corresponding error message. For more information, see the section "Using SQLCODE and SQLERRM" in Chapter 5.

Syntax

Keyword and Parameter Description

 error_number

This argument must be a valid ORACLE error number. For a numerical list of ORACLE errors, see the ORACLE7 Server Messages and Codes Manual.

Usage Notes

You can pass an error number to SQLERRM, in which case SQLERRM returns the message associated with that error number. The error number passed to SQLERRM should be negative. Passing a zero to SQLERRM always returns the following message:

ORA-0000: normal, successful completion

Passing a positive number to SQLERRM always returns the message

User-Defined Exception

unless you pass +100, in which case SQLERRM returns the following message:

ORA-01403: no data found

You cannot use SQLERRM directly in a SQL statement. For example, the following statement is illegal:

INSERT INTO errors VALUES (SQLERRM, ...);

Instead, you must assign the value of SQLERRM to a local variable, then use the variable in the SQL statement, as follows:

DECLARE

   my_sqlerrm  CHAR(150);

   ...

BEGIN

   ...

EXCEPTION

   ...

   WHEN OTHERS THEN

   my_sqlerrm := SUBSTR(SQLERRM, 1, 150);

   INSERT INTO errors VALUES (my_sqlerrm, ...);

END;

The string function SUBSTR() ensures that a VALUE_ERROR exception (for truncation) is not raised when you assign the value of SQLERRM to my_sqlerrm. SQLERRM is especially useful in the OTHERS exception handler because it lets you identify which internal exception was raised.

Related Topics

Exceptions, SQLCODE

________________________________________

%TYPE Attribute

Description

The %TYPE attribute provides the datatype of a variable, constant, or database column. You use the %TYPE attribute in variable and constant declarations as a datatype specifier. Variables and constants declared using %TYPE are treated like those declared using a datatype name. For more information, see the section "Using %TYPE" in Chapter 2.

Syntax

Keyword and Parameter Description

 variable_name

This identifier names a variable or constant previously declared in the same scope. For naming conventions, see the section "Identifiers" in Chapter 2.

 owner.

This identifier names the owner of a table (or view) that must be accessible when the declaration is elaborated.

 table.column

This refers to a table and column that must be accessible when the declaration is elaborated.

Usage Notes

The %TYPE attribute is particularly useful when declaring variables that refer to database columns. You can reference a table and column or you can reference an owner, table, and column. And, a %TYPE declaration can include an initialization clause, as the following example shows:

my_comm  scott.emp.comm%TYPE DEFAULT 0.0;

However, the NOT NULL column constraint does not apply to variables declared using %TYPE. In the next example, even though the database column empno is defined as NOT NULL, you can assign nulls to the variable my_empno:

DECLARE

   my_empno  emp.empno%TYPE;

   ...

BEGIN

   my_empno := NULL;  -- this works

   ...

END;

Related Topics

%ROWTYPE, Variables and Constants

________________________________________

UPDATE Statement

Description

UPDATE changes the values of specified columns in one or more rows in a table or view. For a full description of the UPDATE statement, see the ORACLE7 Server SQL Language Reference Manual.

Syntax

Keyword and Parameter Description

 table_reference

The table or view specified by table_reference must be accessible when you execute the UPDATE statement, and you must have UPDATE privileges.

 alias

This is another (usually short) name for the referenced table or view and is typically used in the WHERE clause.

 column_name

This parameter is the name of the column (or one of the columns) to be updated. It must be the name of a column in the referenced table or view. The column names must not be repeated in the column_name list. They need not appear in the UPDATE statement in the same order that they appear in the table or view.

 SET column_name = sql_expression

This parameter assigns the value of the sql_expression to the column called column_name. The term sql_expression can be any valid SQL expression.

If sql_expression contains references to columns in the table being updated, the references are resolved in the context of the current row. The old column values are used on the right side of the equal sign.

In the following example, you increase every employee's salary by 10%. The original value of the sal column is multiplied by 1.1, then the result is assigned to the sal column.

UPDATE emp SET sal = sal * 1.1;

 SET column_name = one_val_sel_stmt

This clause assigns the value retrieved from the database by the one_val_sel_stmt to the sole column in the column_name list.

The syntax for one_val_sel_stmt is similar to the syntax for select_into_statement, which is defined in the section "SELECT INTO" earlier in this chapter, except that it cannot have an INTO clause and must return exactly one row and one column.

 SET (column_name) = select_statement

This clause assigns the values retrieved from the database by select_statement to the columns listed in the column_name list.

The parameter select_statement must return exactly one row, which includes all the columns listed in parentheses to the left of the equal sign.

The syntax for select_statement is similar to the syntax for select_into_statement, which is defined in the section "SELECT INTO" earlier in this chapter, except that it cannot have an INTO clause.

The column values returned by select_statement are assigned to the columns in the column_name list in order. Thus, the first column value returned by select_statement is assigned to the first column in the column_name list, the second column value is assigned to the second column in the column_name list, and so on.

In the following correlated query, item_id is assigned the value stored in the item_id_num column and price is assigned the value stored in the item_price column.

UPDATE inventory inv  -- alias

   SET (item_id, price) = (SELECT item_id_num, item_price

      FROM item_table

      WHERE item_name = inv.item_name);

 WHERE search_condition

The search_condition conditionally chooses the rows in table_reference to be updated. Only rows that meet the search_condition are updated. If you omit search_condition, all rows in the table are updated.

 WHERE CURRENT OF cursor_name

This parameter refers to the latest row processed by the FETCH statement associated with cursor_name. The named cursor must have been declared using the FOR UPDATE clause and must be open and positioned on a row. If the cursor is not open, using the CURRENT OF clause results in an error. If the cursor is open, but no FETCH has been done or the last FETCH returned no rows, the predefined exception NO_DATA_FOUND is raised.

Usage Notes

The UPDATE ... WHERE CURRENT OF statement can be used after a FETCH from an open cursor, provided the associated query was declared with a FOR UPDATE clause. The UPDATE ... WHERE CURRENT OF statement updates the current row.

The implicit SQL cursor and the cursor attributes %NOTFOUND, %FOUND, %ROWCOUNT, and %ISOPEN let you access useful information about the execution of an UPDATE statement. For more information, see the section "Cursor Management" in Chapter 4.

An UPDATE might update one or more rows or it might update no rows. If one or more rows are updated, the following things occur:

•	SQL%NOTFOUND evaluates to FALSE

•	SQL%FOUND evaluates to TRUE

•	SQL%ROWCOUNT returns the number of rows updated

If no rows are updated, the following things occur:

•	SQL%NOTFOUND evaluates to TRUE

•	SQL%FOUND evaluates to FALSE

•	SQL%ROWCOUNT returns the number 0

Examples

In the following example, a 10% raise is given to all analysts and clerks in department 20:

UPDATE emp SET sal = sal * 1.10

   WHERE (job = 'ANALYST' OR job = 'CLERK') AND DEPTNO = 20;

In the next example, Ford's job is changed and her salary raised by 15%:

UPDATE emp SET job = 'ANALYST', sal = sal * 1.15

   WHERE ename = 'FORD';

________________________________________

Variables and Constants

Description

You can declare variables and constants in the declarative part of any PL/SQL block, subprogram, or package. Declarations allocate storage space for a value, specify its datatype, and name the storage location so the value can be referenced. They can also assign an initial value and add the NOT NULL constraint. For more information, see the section "Declarations and Assignments" in Chapter 2.

Syntax

Keyword and Parameter Description

 variable_name

This names a variable or constant. For naming conventions, see the section "Identifiers" in Chapter 2.

 CONSTANT

This denotes the declaration of a constant. You must initialize a constant in its declaration using a plsql_expression. Once initialized, the value of a constant cannot be changed.

 type_name

This specifies the datatype of a variable or constant. For more information, see the section "Datatypes" in Chapter 2.

 %TYPE

The %TYPE attribute provides the datatype of a variable, constant, or database column.

 table.column

This refers to a database table and column that must be accessible when the declaration is elaborated.

 table

This refers to a database table that must be accessible when the declaration is elaborated.

 %ROWTYPE

The %ROWTYPE attribute provides a record that represents a row in a database table. Columns in a row and corresponding fields in a record have the same names and datatypes.

 NOT NULL

This prevents the assigning of nulls to a variable or constant. Trying to assign a null to an object defined as NOT NULL raises the predefined exception VALUE_ERROR. In variable declarations, the constraint NOT NULL must be followed by an initialization clause.

 plsql_expression

This is an arbitrarily complex expression. It is used to initialize a variable or constant. The syntax for plsql_expression is defined in the section "Expressions" earlier in this chapter.

The value of plsql_expression is assigned to the variable or constant identified by variable_name. The datatype of plsql_expression must be the same as or convertible to the datatype of the variable or constant. For more information, see the section "Datatype Conversion" in Chapter 2.

Usage Notes

Variables and constants are initialized every time a block or subprogram is entered. By default, variables are initialized to NULL. So, unless you expressly initialize a variable, its value is undefined.

Whether public or private, variables and constants declared in a package specification are initialized only once per session.

A plsql_expression is required when declaring NOT NULL variables and when declaring constants. If a plsql_expression is not included in a variable declaration, the variable is assigned a null by default.

You cannot use the %ROWTYPE attribute to declare a constant. If %ROWTYPE is used, initialization is not allowed.

Examples

Several examples of variable and constant declarations follow:

salary           REAL;

invalid          BOOLEAN;

minimum_balance  REAL CONSTANT := 10.00;

acct_id          INTEGER NOT NULL := 1000;

In the following example, %TYPE provides the datatype of a column:

my_ename  emp.ename%TYPE;

Related Topics

Assignment Statement, Expressions, %ROWTYPE, %TYPE


CHAPTER 10. ERROR MESSAGES

We often discover what will do, by finding out what will not do.

Samuel Smiles

This chapter lists error messages issued by PL/SQL. For each error, the probable cause and corrective action are given.

To help you find and fix errors, PL/SQL embeds object names, numbers, and character strings in some error messages. These embedded variables are represented by name, num, and str respectively. For example, the error message listed as

PLS-00388: undefined column 'name' in subquery

might actually appear as:

PLS-00388: undefined column 'AMPNO' in subquery

________________________________________

PL/SQL Error Messages

PLS-00101:  reserved for future use

Not in Release 2.0.

PLS-00102:  parser stack overflow because nesting is too deep

Cause:	The parser, which checks the syntax of PL/SQL statements, uses a data structure called a stack; the number of levels of nesting in your PL/SQL block exceeded the stack capacity.

Action:	Reorganize your block structure to avoid nesting at too deep a level. For example, move the lowest-level sub-block to a higher level.

PLS-00103:  found 'str' but expected one of the following: 'str'

Cause:	This error message is from the parser. It found a token (language element) that is inappropriate in this context.

Action:	Check previous tokens as well as the one given in the error message. The line and column numbers given in the error message refer to the end of the faulty language construct.

PLS-00104:  empty argument list in call of procedure 'name' must be omitted

Cause:	In a subprogram call, the name of the subprogram was followed by an empty parameter list. For example, procedure P was called as P(). This is not allowed.

Action:	Remove the empty parameter list. In the example, change the procedure call to P.

PLS-00105:  at most one forward declaration of type 'name' is permitted

Not in Release 2.0.

PLS-00108:  declarative units must be a single variable declaration

Cause:	While checking a declarative unit (a top-level declare block without the BEGIN...END), PL/SQL found that there was more than one item declared or that the item was not a variable declaration. A table is a common variable declaration at the unit level. To define a TABLE you can compile a DECLARE compilation unit, but only one at a time is allowed.

Action:	Declare variables in separate declarative units.

PLS-00109:  unknown exception name 'name' in PRAGMA EXCEPTION_INIT

Cause:	No declaration for the exception name was found within its scope.

Action:	Make sure the pragma follows the exception declaration and is within the same scope.

PLS-00110:  bind variable 'name' not allowed in this context

Cause:	A bind variable, that is, an identifier prefixed with a colon, was found in an inappropriate context.

Action:	Remove the colon or replace the bind variable with the appropriate object.

PLS-00111:  end-of-file in comment

Cause:	A comment had a comment initiator (/*), but before the comment terminator (*/) was found, an end-of-file marker was encountered.

Action:	Remove the comment initiator or add a comment terminator. The line and column numbers given in the error message refer to the beginning of the last legal token before the comment initiator.

PLS-00112:  end-of-line in quoted identifier

Cause:	A quoted identifier had a beginning quote ("), but before the ending quote (") was found, an end-of-line marker was encountered.

Action:	Remove the beginning quote or add the ending quote. The line and column numbers given in the error message refer to the beginning of the quoted identifier.

PLS-00113:  END identifier 'name1' must match 'name2' at line num, column num

Cause:	Following the keyword END, which terminates some language constructs (such as loops, blocks, functions, and procedures), you can optionally place the name of that construct. For example, at the end of the definition of loop L you might write END L.

This error occurs when the optional name does not match the name given to the language construct. It is usually caused by a misspelled identifier or by faulty block structure.

Action:	Make sure the spelling of the END identifier matches the name given to the language construct and that the block structure is correct.

PLS-00114:  bind variable 'name' exceeds implementation length

Cause:	The name of a PL/SQL variable is longer than 30 characters. Legal identifiers (including quoted identifiers) have a maximum length of 30 characters. You might have mistakenly enclosed a string literal in double quotes instead of single quotes, in which case PL/SQL considers it a quoted identifier.

Action:	Shorten the name to 30 characters or less, or if you are using a string literal, replace the double quotes with single quotes.

PLS-00115:  this PRAGMA must follow the declaration of 'name'

Cause:	The pragma refers to a PL/SQL object that was not declared or is not within the scope of the reference. Identifiers must be declared before they are used in a pragma; forward references are not allowed.

Action:	Check your spelling and declaration of the identifier. Also confirm that the declaration is placed correctly in the block structure.

PLS-00116:  duplicate WHERE clause in table expression

Cause:	Two or more WHERE clauses were found in a DELETE, SELECT, or UPDATE statement. The WHERE clause specifies a condition under which rows in a table are processed. The condition can contain several logical expressions connected by AND or OR, but a statement can contain only one WHERE clause.

Action:	Remove one of the WHERE clauses and, if necessary, connect logical expressions by AND or OR.

PLS-00117:  duplicate CONNECT BY clause in table expression

Cause:	Two or more CONNECT BY clauses were found in a SELECT statement. The CONNECT BY clause defines a relationship used to return rows in a hierarchical order. The relationship can contain two expressions separated by a relational operator (such as = or !=), but a statement can contain only one CONNECT BY clause.

Action:	Remove one of the CONNECT BY clauses and, if necessary, separate expressions by a relational operator.

PLS-00118:  duplicate GROUP BY clause in table expression

Cause:	Two or more GROUP BY clauses were found in a SELECT statement. The GROUP BY clause lists column expressions used to form a summary row for each group of selected rows. The list can contain several column expressions separated by commas, but a statement can contain only one GROUP BY clause.

Action:	Remove one of the GROUP BY clauses and, if necessary, separate column expressions by commas.

PLS-00119:  duplicate HAVING clause in table expression

Cause:	Two or more HAVING clauses were found in a SELECT statement. The HAVING clause specifies a condition under which groups of rows (formed by the GROUP BY clause) are included in the result. The condition can include several logical expressions connected by AND or OR, but a statement can contain only one HAVING clause.

Action:	Remove one of the HAVING clauses and, if necessary, connect logical expressions by AND or OR.

PLS-00120:  inappropriate argument in OPEN statement

Cause:	The cursor_name parameter in an OPEN statement is misspelled or does not refer to a legally declared cursor.

Action:	Check your spelling of the cursor_name parameter. Make sure the cursor was declared properly.

PLS-00123:  program too large

Cause:	PL/SQL was designed primarily for robust transaction processing. One consequence of the special-purpose design is that the PL/SQL compiler imposes a limit on block size. The limit depends on the mix of statements in your PL/SQL block. Blocks that exceed the limit cause this error.

Action:	The best solution is to modularize your program by defining subprograms, which can be stored in an ORACLE database. Another solution is to break your program into two sub-blocks. Have the first block INSERT any data the second block needs into a temporary database table. Then, have the second block SELECT the data from the table.

PLS-00124:  name of exception expected for first argument in EXCEPTION_INIT pragma

Cause:	The first argument passed to the EXCEPTION_INIT pragma was something other than an exception name. The first argument must be the name of a legally declared exception.

Action:	Replace the first argument with the name of a legally declared exception.

PLS-00201:  identifier 'name' must be declared

Cause:	You tried to reference an undefined variable, exception, procedure, function, or other object. Either you failed to declare the identifier or it is not within the scope of the reference.

Action:	Check your spelling and declaration of the identifier. Also confirm that the declaration is placed correctly in the block structure.

PLS-00202:  type 'name' must be declared

Cause:	You tried to reference an undefined type. Either you failed to declare the type identifier or it is not within the scope of the reference.

Action:	Check your spelling and declaration of the type identifier. Also confirm that the declaration is placed correctly in the block structure.

PLS-00203:  function DECODE must be called with at least 3 non-Boolean arguments

Cause:	Less than three arguments were passed to the built-in function DECODE. Though DECODE takes a variable number of (non-Boolean) arguments, you must pass it at least three.

Action:	Call DECODE with three or more arguments.

PLS-00204:  function or pseudocolumn 'name' may be used inside a SQL statement only

Cause:	A pseudocolumn or proscribed function was used in a procedural statement. The SQL pseudocolumns (CURRVAL, LEVEL, NEXTVAL, ROWID, ROWNUM) can be used only in SQL statements. Likewise, certain functions such as DECODE and the SQL group functions (AVG, MIN, MAX, COUNT, SUM, STDDEV, VARIANCE) can be used only in SQL statements.

Action:	Remove the pseudocolumn reference or function call from the procedural statement. Or, replace the procedural statement with a SELECT INTO statement; for example, replace

bonus := DECODE(rating, 1, 5000, 2, 2500, ...);

with the following statement:

SELECT DECODE(rating, 1, 5000, 2, 2500, ...) INTO bonus FROM dual;

PLS-00205:  aggregate not allowed here

Cause:	An aggregate, that is, a parenthesized list of values such as (7788, 'SCOTT', 20), was found in an inappropriate context.

Action:	Remove or relocate the aggregate.

PLS-00206:  %TYPE must be applied to a variable or column, not 'name'

Cause:	The program object declared using the %TYPE datatype attribute is not of the appropriate class. It must be a variable, column, record component, subprogram formal parameter, or other object to which values can be assigned.

Action:	Declare an object of the appropriate class or define the datatype in another way (for example, use %ROWTYPE).

PLS-00207:  identifier 'name', applied to implicit cursor SQL, is not a legal cursor attribute

Cause:	An identifier that is not a cursor attribute was applied to the identifier SQL. For example, this error occurs if the cursor attribute is misspelled.

Action:	Check your spelling of the cursor attribute name. Make sure the attribute is one of these: %NOTFOUND, %FOUND, %ROWCOUNT, %ISOPEN.

PLS-00208:  identifier 'name' is not a legal cursor attribute

Cause:	An identifier not declared as a cursor attribute was applied to an identifier declared as a cursor. For example, this error occurs if the cursor attribute is misspelled.

Action:	Check your spelling of the cursor attribute name. Make sure the attribute is one of these: %NOTFOUND, %FOUND, %ROWCOUNT, %ISOPEN.

PLS-00209:  table 'name' is not in FROM clause

Cause:	In a query, a table referenced by the select list is not named in the FROM clause.

Action:	Check your spelling of the table names, make sure each column in the select list refers to a table in the FROM clause, then re-execute the query.

PLS-00210:  an OTHERS clause is required in this CASE statement

Not in Release 2.0.

PLS-00211:  CASE labels or ranges must not be duplicated in different WHEN clauses

Not in Release 2.0.

PLS-00212:  could not obtain enough memory to compile CASE statement

Not in Release 2.0.

PLS-00213:  package STANDARD not accessible

Cause:	The PL/SQL compiler could not find package STANDARD in the current ORACLE database. To compile a program, PL/SQL needs package STANDARD.

Action:	Make sure that package STANDARD is available in the current ORACLE database, then retry the operation.

PLS-00214:  BEGIN...END block nesting is too deep

Cause:	The number of levels of nesting in your PL/SQL block is too large. You can nest blocks up to 255 levels deep, depending on the availability of system resources such as memory.

Action:	Reorganize your block structure to avoid nesting at too deep a level. For example, move the lowest-level sub-block to a higher level

PLS-00215:  string length constraints must be in range (1 .. 32767)

Cause:	When declaring a character variable, you specified a length that is outside the legal range. For example, the following declarations are illegal:

flag  CHAR(0);        -- illegal; zero length

name  VARCHAR2(-10);  -- illegal; negative length

Action:	Change the length constraint, making sure that it lies in the range 1 .. 32767

PLS-00216:  NUMBER precision constraint must be in range (1 .. 38)

Cause:	You declared a NUMBER variable with a precision that is outside the legal range. Declarations such as N NUMBER(800) or N NUMBER(123,10) are not supported.

Action:	Change the illegal NUMBER precision constraint, making sure that it lies in the range 1 .. 38.

PLS-00217:  NUMBER scale constraint must be in range (-84 .. 127)

Cause:	You declared a NUMBER variable with a scale that is outside the legal range. Declarations such as N NUMBER(10,345) or N NUMBER(10,-100) are not supported.

Action:	Change the illegal NUMBER scale constraint, making sure that it lies in the range -84 .. 127.

PLS-00218:  a variable declared NOT NULL must have an initialization assignment

Cause:	In general, variables that have no initialization clause in their declaration are automatically initialized to NULL. This is illogical for NOT NULL variables, and therefore an initialization clause is required.

Action:	Add an initialization clause to the variable declaration.

PLS-00219:  label 'name' reference is out of scope

Cause:	A block or loop label was used to qualify a variable (as in outer_block.date) that was not declared or is not within the scope of the label. The variable name might be misspelled, its declaration might be faulty, or the declaration might be placed incorrectly in the block structure.

Action:	Check your spelling and declaration of the variable name. Also confirm that the declaration is placed correctly in the block structure.

PLS-00220:  simple name required in this context

Cause:	A qualified name such as A.B or A.B.C is not permitted here.

Action:	Use a simple name such as A instead.

PLS-00221:  'name' is not a procedure or is undefined

Cause:	The named identifier is being referenced as a procedure, but the identifier was not declared or actually represents another object (for example, it might have been declared as a function).

Action:	Check your spelling and declaration of the identifier. Also confirm that the declaration is placed correctly in the block structure.

PLS-00222:  no function with name 'name' exists in this scope

Cause:	The named identifier is being referenced as a function, but the identifier was not declared or actually represents another object (for example, it might have been declared as a procedure).

Action:	Check your spelling and declaration of the identifier. Also confirm that the declaration is placed correctly in the block structure.

PLS-00223:  parameterless procedure 'name' used as function

Cause:	The named identifier is being referenced as a parameterless function, but the identifier actually represents a procedure.

Action:	Check your spelling and declaration of the identifier. Also confirm that the declaration is placed correctly in the block structure. If necessary, change the declaration of the identifier or change the reference so that it does not require a return value.

PLS-00224:  object 'name' must be of type function or array to be used this way

Cause:	The named identifier is being referenced as a function or an array, but the identifier actually represents an object (a number or date, for example) that cannot be referenced in this way.

Action:	Check your spelling and declaration of the identifier. Also confirm that the declaration is placed correctly in the block structure.

PLS-00225:  subprogram or cursor 'name' reference is out of scope

Cause:	A subprogram or cursor references a variable that was not declared or is not within the scope of the subprogram or cursor. The variable name might be misspelled, its declaration might be faulty, or the declaration might be placed incorrectly in the block structure.

Action:	Check your spelling and declaration of the variable name. Also confirm that the declaration is placed correctly in the block structure.

PLS-00226:  package 'name' used as variable reference

Cause:	A package was referenced in an expression as if it were a variable or function. Either the name of the variable or function is misspelled or the reference is not fully qualified. For example, to call the function my_function, which is stored in package my_package, you must use dot notation as follows:

... my_package.my_function ...

Action:	Correct your spelling of the variable or function name or use dot notation to reference the packaged variable or function.

PLS-00227:  IN formal parameter 'name' not allowed in this context

Cause:	When declaring the formal parameters of a subprogram, you used one parameter to initialize another, as in

PROCEDURE my_proc (j NUMBER, k NUMBER := j) IS ...

The first parameter has no value until run time, so it cannot be used to initialize another parameter.

Action:	Remove the illegal formal parameter reference.

PLS-00229:  attribute expression within SQL expression

Cause:	You used an attribute expression such as SQL%NOTFOUND in a SQL statement, but attribute expressions are allowed only in procedural statements.

Action:	To work around this limitation, assign the value of the attribute expression to a variable, then use the variable in the SQL statement. For example, replace the statement

INSERT INTO audits VALUES (c1%ROWCOUNT, ...);

with the following statements:

row_count := c1%ROWCOUNT;

INSERT INTO audits VALUES (row_count, ...);

PLS-00230:  OUT and IN OUT formal parameters may not have default expressions

Cause:	When declaring the formal parameters of a procedure, you initialized an OUT or IN OUT parameter to a default value, as in

PROCEDURE calc_bonus (bonus OUT REAL := 0, ...) IS ...

However, only IN parameters can be initialized to default values.

Action:	Remove the illegal default expression.

PLS-00231:  function 'name' may not be used in SQL

Cause:	You used a proscribed function in a SQL statement. Certain functions such as SQLCODE and SQLERRM can be used only in procedural statements.

Action:	Remove the function call from the SQL statement. Or, replace the function call with a local variable. For example, the following statement is illegal:

INSERT INTO errors VALUES (SQLCODE, SQLERRM);

However, you can assign the values of SQLCODE and SQLERRM to local variables, then use the variables in the SQL statement, as follows:

err_num := SQLCODE;

err_msg := SQLERRM;

INSERT INTO errors VALUES (err_num, err_msg);

PLS-00232:  nested packages not permitted

Cause:	You declared a package inside another package, but package declarations are allowed only at the top level. In other words, you cannot nest packages.

Action:	Move the package declaration outside the enclosing package.

PLS-00233:  function name used as an exception name in WHEN clause

Cause:	The WHEN clause in an exception handler contains a function call instead of an exception name. A valid exception handler consists of a WHEN clause, which must specify an exception, followed by a sequence of statements to be executed when that exception is raised.

Action:	Check your spelling of the identifier in the WHEN clause, then replace the function call with an exception name.

PLS-00302:  component 'name' must be declared

Cause:	In a reference to a component (for example, in the name A.B, B is a component of A), the component was not declared. The component might be misspelled, its declaration might be faulty, or the declaration might be placed incorrectly in the block structure.

Action:	Check your spelling and declaration of the component. Also confirm that the declaration is placed correctly in the block structure.

PLS-00303:  qualifier 'name' must be declared

Cause:	In a name such as A.B, A is a qualifier, and B is a component of the qualifier. This error occurs when no declaration for the qualifier is found. The qualifier might be misspelled, its declaration might be faulty, or the declaration might be placed incorrectly in the block structure.

Action:	Check your spelling and declaration of the qualifier. Also confirm that the declaration is placed correctly in the block structure.

PLS-00304:  cannot compile body of 'name' without its specification

Cause:	The compiled package specification needed to compile a package body could not be found. Some possible causes follow:

  the package name is misspelled

  the package specification was never compiled

  the compiled package specification is not accessible

You must compile the package specification before compiling the package body, and the compiler must have access to the compiled specification.

Action:	Check your spelling of the package name. Compile the package specification before compiling the package body. And, make sure the compiler has access to the compiled specification.

PLS-00305:  previous use of 'name' conflicts with this use

Cause:	While looking for prior declarations of a cursor, procedure, function, or package, the compiler found another object with the same name in the same scope.

Action:	Check your spelling of the cursor, procedure, function, or package name. Also check the names of all constants, variables, parameters, and exceptions declared in the same scope. Then, remove or rename the object with the duplicate name.

PLS-00306:  	wrong number or types of arguments in call to 'name'

Cause:	This error occurs when the named subprogram call cannot be matched to any declaration for that subprogram name. The subprogram name might be misspelled, a parameter might be of the wrong datatype, the declaration might be faulty, or the declaration might be placed incorrectly in the block structure. For example, this error occurs if you call the built-in square root function SQRT with a misspelled name or with a parameter of the wrong datatype.

Action:	Check your spelling and declaration of the subprogram name. Also confirm that its call is correct, its parameters are of the right datatype, and, if it is not a built-in function, that its declaration is placed correctly in the block structure.

PLS-00307:  	too many declarations of 'name' match this call

Cause:	The declaration of a subprogram name is ambiguous because there was no exact match between the declaration and the call and more than one declaration matched the call when implicit conversions of the parameter datatypes were used. The subprogram name might be misspelled, its declaration might be faulty, or the declaration might be placed incorrectly in the block structure.

Action:	Check your spelling and declaration of the subprogram name. Also confirm that its call is correct, its parameters are of the right datatype, and, if it is not a built-in function, that its declaration is placed correctly in the block structure.

PLS-00308:  	this construct is not allowed as the origin of an assignment

Cause:	The construct or expression does not designate a value that can be assigned to a variable. For example, the datatype name NUMBER cannot appear on the right hand side of an assignment statement as in X := NUMBER.

Action:	Correct the illegal assignment statement.

PLS-00309:  	with %LAST attribute, 'name' must be a variable of an enumerated type

Not in Release 2.0.

PLS-00310:  	with %ROWTYPE attribute, 'name' must name a cursor or table

Cause:	The %ROWTYPE attribute must be applied to an identifier declared as a cursor or table. This error occurs when %ROWTYPE follows some identifier that has not been so declared.

Action:	Change the declaration or do not apply the %ROWTYPE attribute to the identifier.

PLS-00311:  	the declaration of the type of 'name' is incomplete or malformed

Cause:	This occurrence of the identifier cannot be compiled because its datatype has not been properly defined.

Action:	Correct the faulty datatype declaration.

PLS-00312:  	a positional parameter association may not follow a named association

Cause:	When passing a list of parameters to a subprogram or cursor, if you use both positional and named associations, you must place all positional associations in their declared order and before all named associations, which can be in any order.

Action:	Reorder the parameter list to meet the requirements or use named association only.

PLS-00313:  	'name' not declared in this scope

Cause:	There is no declaration for the given identifier within the scope of reference. The identifier might be misspelled, its declaration might be faulty, or the declaration might be placed incorrectly in the block structure.

Action:	Check your spelling and declaration of the identifier. Also confirm that the declaration is placed correctly in the block structure.

PLS-00314:  	TABLE declarations are not allowed as PL/SQL local variables

Cause:	In a precompiled program, you mistakenly used the DECLARE TABLE statement inside an embedded PL/SQL block. If an embedded PL/SQL block refers to a database table that does not yet exist, you can use the DECLARE TABLE statement to tell the precompiler what the table will look like. But, DECLARE TABLE statements are allowed only in the host program.

Action:	Move the DECLARE TABLE statement outside the embedded PL/SQL block. If you want a variable that can store an entire row of data selected from a database table or fetched by a cursor, use the %ROWTYPE attribute.

PLS-00315:  	PL/SQL TABLE declarations must currently use BINARY_INTEGER indexes

Cause:	In the INDEX BY clause of a PL/SQL table declaration, you specified a datatype other than BINARY_INTEGER. PL/SQL tables can have one column and a primary key. The column can belong to any scalar type, but the primary key must belong to type BINARY_INTEGER.

Action:	Change the datatype specifier to BINARY_INTEGER.

PLS-00316:  	PL/SQL TABLE declarations must currently use a single index

Cause:	In the INDEX BY clause of a PL/SQL table declaration, you specified a composite primary key. PL/SQL tables must have a simple, unnamed primary key of type BINARY_INTEGER.

Action:	Change the faulty clause to INDEX BY BINARY_INTEGER.

PLS-00319:  	subquery in an IN or NOT IN clause must contain exactly one column

Cause:	You used an invalid expression such as:

a IN (SELECT x, y, z FROM ... )

When a [NOT]IN clause is used with a subquery, it does not test for set membership. The number of expressions in the [NOT]IN clause and the subquery select list must match. So, in the example above, the subquery must specify at most one column.

Action:	Change the subquery to select only one column.

PLS-00320:  	the declaration of the type of this expression is incomplete or malformed

Cause:	In a declaration, the name of a variable or cursor is misspelled or the declaration makes a forward reference. Forward references are not allowed in PL/SQL. You must declare a variable or cursor before referencing it in other statements, including other declarative statements. For example, the following declaration of dept_rec raises this exception because it refers to a cursor not yet declared:

DECLARE

   dept_rec  dept_cur%ROWTYPE;

   CURSOR dept_cur IS SELECT ...

   ...

Action:	Check your spelling of all identifiers in the declaration. If necessary, move the declaration so that it makes no forward references.

PLS-00321:  	expression 'str' is inappropriate as the left hand side of an assignment statement

Cause:	The expression does not designate a variable that can have a value assigned to it. For example, the function SYSDATE cannot appear on the left hand side of an assignment statement such as:

SYSDATE := '01-JAN-1990';

Action:	Correct the illegal assignment statement.

PLS-00322:  	declaration of a constant 'name' must contain an initialization assignment

Cause:	A constant declaration is lacking the assignment of the constant value. For example, in the following declaration ":= 3.14159" is the initialization assignment:

pi CONSTANT NUMBER := 3.14159;

Action:	Correct the constant declaration by supplying the missing initialization assignment.

PLS-00323:  	subprogram 'name' is declared in a package specification and must be defined in the package body

Cause:	You placed a subprogram specification in a package specification, but neglected to place the corresponding subprogram body in the package body. The package body implements the package specification. So, the package body must contain the definition of every subprogram declared in the package specification.

Action:	Check your spelling of the subprogram name. If necessary, add the missing subprogram body to the package body.

PLS-00324:  	cursor attribute may not be applied to non-cursor 'name'

Cause:	This error occurs when a cursor attribute (%FOUND, %NOTFOUND, %ROWCOUNT, or %ISOPEN) appears following an identifier not declared as a cursor. It occurs, for example, if the variable name my_cur in my_cur%FOUND was not properly declared as a cursor or if the variable declaration was placed incorrectly in the block structure.

Action:	Check your spelling and declaration of the identifier. Also confirm that the declaration is placed correctly in the block structure.

PLS-00325:  	non-integral numeric literal num is inappropriate in this context

Cause:	A non-integral numeric literal was used in a context that requires an integer (a number with no fractional part).

Action:	Replace the inappropriate literal with an integral literal.

PLS-00326:  	IN clause must contain same number of expressions as subquery

Cause:	The number of expressions in an IN clause did not equal the number of expressions in a corresponding subquery select list. For example, the following statement is invalid because the IN clause contains two expressions, but the subquery select list contains just one:

... WHERE (ename, sal) IN (SELECT sal FROM emp);

Action:	Check the number of expressions in each set, then revise the statement to make the numbers equal.

PLS-00328:  	a subprogram body must be defined for the forward declaration of 'name'

Cause:	You declared a subprogram specification, but failed to define the corresponding subprogram body. You can write the subprogram specification and body as a unit. Or, you can separate the specification from its body, which is necessary when you want to define mutually recursive subprograms or group subprograms in a package.

Action:	Check your spelling of the subprogram name. If necessary, supply the missing subprogram body.

PLS-00341:  	declaration of cursor 'name' is incomplete or malformed

Cause:	A cursor declaration is improper or an identifier referenced in the cursor declaration was not properly declared. You might have specified a return type (%ROWTYPE) that does not refer to an existing database table or previously declared cursor. For example, the following cursor declaration is illegal because c1 is not yet fully defined:

CURSOR c1 RETURN c1%ROWTYPE IS SELECT ...  -- illegal

In this case, you need not specify a return type because it is implicit.

Action:	Check your spelling and declaration of the cursor name and any identifiers referenced in the cursor declaration. Also confirm that the declaration is placed correctly in the block structure. If you specified a return type, make sure that it refers to an existing database table or previously declared cursor.

PLS-00351:  	not logged on to database 'name'

Cause:	You tried to access an ORACLE database without being logged on. Probably, an invalid username or password was entered.

Action:	Log on to ORACLE with a correctly spelled username and password before trying to access the database.

PLS-00352:  	unable to access another database 'name'

Cause:	You tried to reference an object in a database other than the current local or remote ORACLE database.

Action:	Correct your reference and make sure the object is in the current ORACLE database.

PLS-00353:  	'name' must name a user in the database

Cause:	This error occurs when the username was misspelled or when the user does not exist in the database.

Action:	Check your spelling of the username and make sure the user exists.

PLS-00354:  	username must be a simple identifier

Cause:	A qualified username such as scott.accts is not permitted in this context.

Action:	Specify a simple username such as scott instead.

PLS-00356:  	'name' must name a table to which the user has access

Cause:	The named table is not accessible to the user. This error occurs when the table name or username was misspelled, the table and/or user does not exist in the database, the user was not granted the necessary privileges, or the table name duplicates the name of a local variable or loop counter.

Action:	Check your spelling of the table name and username. Also confirm that the table and user exist, that the user has the necessary privileges, and that the table name does not duplicate the name of a local variable or loop counter.

PLS-00357:  	table, view or sequence reference 'name' not allowed in this context

Cause:	A reference to database table, view, or sequence was found in an inappropriate context. Such references can appear only in SQL statements or (excluding sequences) in %TYPE and %ROWTYPE declarations. Some valid examples follow:

SELECT ename, emp.deptno, dname INTO my_ename, my_deptno, my_dept

   FROM emp, dept WHERE emp.deptno = dept.deptno;

DECLARE

   last_name  emp.ename%TYPE;

   dept_rec   dept%ROWTYPE;

Action:	Remove or relocate the illegal reference.

PLS-00358:  	column 'name' exists in more than one table; use qualifier

Cause:	Your statement is ambiguous because it specifies two or more tables having the same column name. For example, the following statement is ambiguous because deptno is a column in both tables:

SELECT deptno, loc INTO my_deptno, my_loc FROM emp, dept;

Action:	Precede the column name with the table name (as in emp.deptno) so that the column reference is unambiguous.

PLS-00359:  	assignment target in 'str' must have components

Cause:	An assignment target was not declared to have the required components. For example, this error occurs if you try to assign a row of column values to a variable instead of a record, as follows:

DECLARE

   dept_rec   dept%ROWTYPE;

   my_deptno  dept.deptno%TYPE;

   ...

BEGIN

   SELECT deptno, dname, loc INTO my_deptno  -- invalid

      FROM dept WHERE ...

   ...

Action:	Check your spelling of the names of the assignment target and all its components. Make sure the assignment target is declared with the required components and that the declaration is placed correctly in the block structure.

PLS-00360:  	cursor declaration without body needs return type

Cause:	A cursor declaration lacks either a body (SELECT statement) or a return type (%ROWTYPE). If you want to separate a cursor specification from its body, you must supply a return type, as in

CURSOR c1 RETURN emp%ROWTYPE;

Action:	Add a SELECT statement or return type to the cursor declaration.

PLS-00363:  	expression 'str' cannot be used as an assignment target

Cause:	You mistakenly used a literal, constant, IN parameter, loop counter, or function call as the target of an assignment. For example, the following statement is illegal because the assignment target, 30, is a literal:

SELECT deptno INTO 30 FROM dept WHERE ...  -- illegal

Action:	Correct the statement by using a valid assignment target.

PLS-00364:  	loop index variable 'name' use is invalid

Cause:	A reference to a loop counter was found in an inappropriate context. For example, the following statement is illegal because the loop counter is used as the terminal value in its own range expression:

FOR j IN 1 .. j LOOP ...  -- illegal

Action:	Change the loop range expression so that it does not reference the loop counter. If you want to refer in the range expression to another variable with the same name as the loop counter, change either name or qualify the variable name with a label.

PLS-00365:  	'name' is an OUT parameter and cannot be read

Cause:	You tried to assign the value of an OUT parameter to another parameter or variable. Inside a procedure, an OUT parameter acts like an uninitialized variable; therefore, its value cannot be read. For example, the following assignments are illegal:

PROCEDURE calc_wages (bonus OUT REAL, ...) IS

   rating  REAL;

   wages   REAL;

BEGIN

   ...

   IF rating > 90 THEN

      bonus := bonus * 2;  -- illegal

   END IF;

   SELECT sal + bonus INTO wages FROM emp ...  -- illegal

   ...

END calc_bonus;

Action:	Use an IN OUT parameter instead of the OUT parameter. Inside a procedure, an IN OUT parameter acts like an initialized variable; therefore, its value can be read.

PLS-00366:  	subtype of a NOT NULL type must also be NOT NULL

Not in Release 2.0.

PLS-00367:  	a RAISE statement with no exception name must be inside an exception handler

Cause:	A RAISE statement not followed by an exception name was found outside an exception handler.

Action:	Delete the RAISE statement, relocate it to an exception handler, or supply the missing exception name.

PLS-00368:  	in RAISE statement, 'name' must be an exception name

Cause:	The identifier in a RAISE statement is not a valid exception name.

Action:	Make sure the identifier in the RAISE statement was declared as an exception and is correctly placed in the block structure. If you are using one of the PL/SQL predefined exception names, check its spelling.

PLS-00369:  	no choices may appear with choice OTHERS in an exception handler

Cause:	A construct of the form

WHEN excep1 OR OTHERS =>

was encountered in the definition of an exception handler. OTHERS must appear by itself as the last exception handler in a block.

Action:	Remove the identifier that appears with OTHERS or write a separate exception handler for that identifier.

PLS-00370:  	OTHERS handler must be last among the exception handlers of a block

Cause:	One or more exception handlers appear after an OTHERS handler. However, the OTHERS handler must be the last handler in a block or subprogram because it acts as the handler for all exceptions not named specifically.

Action:	Move the OTHERS handler so that it follows all specific exception handlers.

PLS-00371:  	at most one declaration for 'name' is permitted in the declaration section

Cause:	A reference to an identifier is ambiguous because there are conflicting declarations for it in the declaration section of a block, procedure, or function. At most one declaration of the identifier is permitted in a declaration section.

Action:	Check your spelling of the identifier. If necessary, remove all but one declaration of the identifier.

PLS-00372:  	in a procedure, RETURN statement cannot contain an expression

Cause:	In a procedure, a RETURN statement contains an expression, which is not allowed. In functions, a RETURN statement must contain an expression because its value is assigned to the function identifier. However, in procedures, a RETURN statement simply lets you exit before the normal end of the procedure is reached.

Action:	Remove the expression from the RETURN statement, or redefine the procedure as a function.

PLS-00373:  	EXIT label 'name' must label a LOOP statement

Cause:	The statement with the named label is not a loop. An EXIT statement does not require a label operand, but if you specify one (as in EXIT my_label), it must be the label of a loop statement.

Action:	Make sure the label name is spelled correctly and that it refers to a loop statement.

PLS-00374:  	illegal EXIT statement; it must appear inside the loop labeled 'name'

Cause:	An EXIT statement does not require a label operand, but if you specify one (as in EXIT my_label), the EXIT statement must be inside the loop designated by that label.

Action:	Make sure the label name is spelled correctly, placed properly, and refers to the appropriate EXIT statement.

PLS-00375:  	illegal GOTO statement; this GOTO cannot branch to label 'name'

Cause:	The line and column numbers accompanying the error message refer to a GOTO that branches from outside a construct (a loop or exception handler, for example) containing a sequence of statements to a label inside that sequence of statements. Such a branch is not allowed.

Action:	Either move the GOTO statement inside the sequence of statements or move the labeled statement outside the sequence of statements.

PLS-00376:  	illegal EXIT statement; it must appear inside a loop

Cause:	An EXIT statement was found outside of a loop construct. The EXIT statement is used to exit prematurely from a loop and so must always appear within a loop.

Action:	Either remove the EXIT statement or place it inside a loop.

PLS-00377:  	internal type PLS_INTEGER is not included in this release of PL/SQL

Cause:	In a declaration, you mistakenly specified the obsolete datatype PLS_INTEGER, which has been replaced by the datatype BINARY_INTEGER.

Action:	Specify the datatype BINARY_INTEGER instead of PLS_INTEGER.

PLS-00378:  	invalid compilation unit for this release of PL/SQL

Cause:	A compilation unit is a file containing PL/SQL source code that is passed to the compiler. Only compilation units containing blocks, declarations, statements, and subprograms are allowed. This error occurs when some other language construct is passed to the compiler.

Action:	Make sure the compilation unit contains only blocks, declarations, statements, and subprograms.

PLS-00379:  	CASE statements are not included in this release of PL/SQL

Cause:	The unit being compiled contains a CASE statement. However, the current release of PL/SQL does not support CASE statements.

Action:	Remove the CASE statement from the compilation unit.

PLS-00381:  	type mismatch found at 'name' between column and variable in subquery or INSERT

Cause:	The datatypes of a column and a variable do not match. The variable was encountered in a subquery or INSERT statement.

Action:	Change the variable datatype to match that of the column.

PLS-00382:  	expression is of wrong type

Cause:	The given expression variable is of the wrong datatype for the context in which it was found.

Action:	Change the datatype of the expression. You might want to use datatype conversion functions.

PLS-00383:  	type mismatch found at 'name' inside an IN or NOT IN clause

Cause:	In a test for set membership such as X NOT IN (SELECT Y ... ), the expressions X and Y do not match in datatype, and it is unclear which implicit conversion is needed to correct the mismatch.

Action:	Change the expressions so that their datatypes match. You might want to use datatype conversion functions in the select list.

PLS-00384:  	type mismatch found at 'name' in UPDATE's SET clause

Cause:	The column to the left of the equal sign in the SET clause of an UPDATE statement does not match in datatype with the column, expression, or subquery to the right of the equal sign, and it is unclear which implicit conversion is needed to correct the mismatch.

Action:	Change the expressions so that their datatypes match. You might want to use datatype conversion functions in the SET clause.

PLS-00385:  	type mismatch found at 'name' in SELECT...INTO statement

Cause:	The expressions to the left and right of the INTO clause in a SELECT...INTO statement do not match in datatype, and it is unclear which implicit conversion is needed to correct the mismatch.

Action:	Change the expressions so that their datatypes match. You might want to use datatype conversion functions in the select list.

PLS-00386:  	type mismatch found at 'name' between FETCH cursor and INTO variables

Cause:	An assignment target in the INTO list of a FETCH statement does not match in datatype with the corresponding column in the select list of the cursor declaration, and it is unclear which implicit conversion is needed to correct the mismatch.

Action:	Change the cursor declaration or change the datatype of the assignment target. You might want to use datatype conversion functions in the select list of the query associated with the cursor.

PLS-00387:  	INTO variable cannot be a database object

Cause:	An item in the INTO list of a FETCH or SELECT statement was found to be a database object. INTO introduces a list of user-defined variables to which output values are assigned. Therefore, database objects cannot appear in the INTO list.

Action:	Check your spelling of the INTO list item. If necessary, remove the item from the INTO list or replace it with a user-defined output variable.

PLS-00388:  	undefined column 'name' in subquery

Cause:	A subquery contains a column name that was not defined for the specified table.

Action:	Change the expression to specify a column that was defined.

PLS-00389:  	undefined column 'name' in left-hand-side expression

Cause:	A left-hand-side expression in a SQL statement refers to an undefined column.

Action:	Check your spelling of the column name, then change the expression so that it refers only to defined columns.

PLS-00390:  	undefined column 'name' in INSERT statement

Cause:	An INSERT statement refers to a column not defined for the table or view into which data is being INSERTed.

Action:	Check your spelling of the column name, then revise the statement so that it refers only to defined columns.

PLS-00391:  	undefined column 'name' in UPDATE statement

Cause:	An UPDATE statement refers to a column not defined for the table or view being UPDATEd.

Action:	Check your spelling of the column name, then revise the statement so that it refers only to defined columns.

PLS-00392:  	type mismatch in arguments to BETWEEN

Cause:	In a comparison such as X BETWEEN Y AND Z, the expressions X, Y, and Z do not match in datatype, and it is unclear which implicit conversion is needed to correct the mismatch.

Action:	Change the expressions so that their datatypes match. You might want to use datatype conversion functions.

PLS-00393:  	wrong number of columns in SELECT...INTO statement

Cause:	The number of columns selected by a SELECT...INTO statement does not match the number of variables in the INTO clause.

Action:	Change the number of columns in the select list or the number of variables in the INTO clause so that the numbers match.

PLS-00394:  	wrong number of values in the INTO list of a FETCH statement

Cause:	The number of variables in the INTO clause of a FETCH statement does not match the number of columns in the cursor declaration.

Action:	Change the number of variables in the INTO clause or the number of columns in the cursor declaration so that the numbers match.

PLS-00395:  	wrong number of values in VALUES clause of INSERT statement

Cause:	The number of columns in an INSERT statement does not match the number of values in the VALUES clause. For example, the following statement is faulty because no column is specified for the value 20:

INSERT INTO emp (empno, ename) VALUES (7788, 'SCOTT', 20);

Action:	Change the number of items in the column list or the number of items in the VALUES list so that the numbers match.

PLS-00396:  	INSERT statement's subquery yields wrong number of columns

Cause:	The number of columns in an INSERT statement does not match the number of columns in a subquery select list. For example, the following statement is faulty because no corresponding column is specified for col3:

INSERT INTO emp (ename, empno) SELECT col1, col2, col3 FROM ...

Action:	Change the number of items in the column list of the INSERT statement or the number of items the select list so that the numbers match.

PLS-00397:  	type mismatch in arguments to IN

Cause:	In a test for set membership such as X IN (Y, Z), the expressions X, Y, and Z do not match in datatype, and it is unclear which implicit conversion is needed to correct the mismatch.

Action:	Change the expressions so that their datatypes match. You might want to use datatype conversion functions.

PLS-00398:  	wrong number of columns in UNION, INTERSECT, or MINUS expression

Cause:	The SELECT clauses to the left and right of a UNION, INTERSECT, or MINUS expression do not select the same number of columns. For example, the following statement is faulty because the select lists do not contain the same number of items:

CURSOR my_cur IS SELECT ename FROM emp     INTERSECT SELECT ename, empno FROM emp;

Action:	Change the select lists so that they contain the same number of items.

PLS-00399:  	different types of columns in UNION, INTERSECT, or MINUS expression

Cause:	The select lists to the left and right of a UNION, INTERSECT, or MINUS expression select at least one column that is mismatched in datatype. For example, the following statement is faulty because the constant 3 is of datatype NUMBER, whereas SYSDATE is of datatype DATE:

CURSOR my_cur IS SELECT 3 FROM emp     INTERSECT SELECT SYSDATE FROM emp;

Action:	Change the select lists so that they match in datatype. You might want to use datatype conversion functions in the select list of one or more queries.

PLS-00400:  	different number of columns between cursor SELECT statement and return value

Cause:	In a cursor declaration, you specified a return type (such as RETURN emp%ROWTYPE), but the number of returned column values does not match the number of select-list items.

Action:	Change the cursor return type or the select list so that the number of returned column values matches the number of select-list items.

PLS-00401:  	different column types between cursor SELECT statement and return value found at 'name'

Cause:	In a cursor declaration, you specified a return type (such as RETURN emp%ROWTYPE), but a returned column value and its corresponding select-list item belong to different datatypes.

Action:	Change the cursor return type or the select list so that each returned column value and its corresponding select-list item belong to the same datatype.

PLS-00402:  	alias required in SELECT list of cursor to avoid duplicate column names

Cause:	A cursor was declared with a SELECT statement that contains duplicate column names. Such references are ambiguous.

Action:	Replace the duplicate column name in the select list with an alias.

PLS-00403:  	INTO list of FETCH statement contains illegal assignment target

Cause:	A FETCH statement was unable to assign a value to an assignment target in its INTO list because the target is not a legally formed and declared variable. For example, the following assignment is illegal because 'Jones' is a character string, not a variable:

FETCH my_cur INTO 'Jones';

Action:	Check your spelling and declaration of the assignment target. Make sure you followed the rules for forming variable names.

PLS-00404:  	cursor 'name' must be declared with FOR UPDATE to use with CURRENT OF

Cause:	The use of the CURRENT OF name clause is legal only if name was declared with a FOR UPDATE clause.

Action:	Add a FOR UPDATE clause to the definition of the cursor or do not use the CURRENT OF 'name' clause.

PLS-00405:  	subquery not allowed in this context

Cause:	A subquery was used in an inappropriate context, such as:

if (SELECT deptno FROM emp WHERE ... ) = 20 then ...

Subqueries are allowed only in SQL statements.

Action:	You can get the same result by using a temporary variable, as in:

SELECT deptno INTO temp_var FROM emp WHERE ...;

IF temp_var = 20 THEN ...

PLS-00406:  	length of SELECT list in subquery must match number of assignment targets

Cause:	A query select list is not the same length as the list of targets that will receive the returned values. For example, the following statement is faulty because the subquery returns two values for one target:

UPDATE emp SET ename =

   (SELECT ename, empno FROM emp WHERE ename = 'SMITH') ...

Action:	Change one of the lists so that they contain the same number of items.

PLS-00407:  	'*' not allowed here; a list of columns is required

Cause:	An asterisk (*) was used as an abbreviation for a list of column names. However, in this context the column names must be written out explicitly.

Action:	Replace the asterisk with a list of column names.

PLS-00408:  	duplicate column 'name' not permitted in INSERT or UPDATE

Cause:	An UPDATE or INSERT statement has a column list that contains duplicate column names.

Action:	Check your spelling of the column names, then eliminate the duplication.

PLS-00409:  	duplicate variable 'name' in INTO list is not permitted

Cause:	The same variable appears twice in the INTO list of a SELECT or FETCH statement.

Action:	Remove one of the variables from the INTO clause.

PLS-00410:  	duplicate fields in record or table are not allowed

Cause:	When declaring a user-defined record, you gave the same name to two fields. Like column names in a database table, field names in a user-defined record must be unique.

Action:	Check your spelling of the field names, then remove the duplicate.

PLS-00412:  	list of values not allowed as argument to this function or procedure

Cause:	A parenthesized list of values separated by commas (that is, an aggregate) was used in the wrong context. For example, the following usage is invalid:

WHERE (col1, col2) > (SELECT col3, col4 FROM my_table ...)

However, an equal sign can take a list of values and a subquery as left- and right-hand-side arguments respectively, so the following usage is valid:

WHERE (col1, col2) = (SELECT col3, col4 FROM my_table ...)

Action:	Rewrite the expression. For example, the clause

WHERE (col1, col2) > (SELECT col3, col4 FROM my_table ...)

can be rewritten as

WHERE col1 > (SELECT col3 FROM my_table ...) AND

   col2 > (SELECT col4 FROM my_table ...)

PLS-00413:  	identifier in CURRENT OF clause is not a cursor name

Cause:	The identifier in a CURRENT OF clause names an object other than a cursor.

Action:	Check your spelling of the identifier. Make sure that it names the cursor in the DELETE or UPDATE statement and that it names the cursor itself, not a FOR-loop variable.

PLS-00414:  	no column 'name' in table

Cause:	A table name or alias was used to qualify a column reference, but the column was not found in that table. Either the column was never defined or the column name is misspelled.

Action:	Confirm that the column was defined and check your spelling of the column name.

PLS-00415:  	'name' is an OUT parameter and cannot appear in a function

Cause:	When declaring the formal arguments of a function, you specified the OUT or IN OUT parameter mode. Procedures can take IN, OUT, and IN OUT parameters, but functions can take only IN arguments.

Action:	Remove the OUT or IN OUT argument from the formal argument list, or redefine the function as a procedure.

PLS-00450:  	a variable of this private type cannot be declared here

Not in Release 2.0.

PLS-00483:  	exception 'name' may appear in at most one exception handler in this block

Cause:	The same exception appears in two different exception handlers within the same EXCEPTION section. That is not allowed.

Action:	Remove one of the duplicate exception handlers.

PLS-00484:  	exceptions 'name' and 'name' have same ORACLE error number and must appear in same exception handler

Cause:	Using PRAGMA EXCEPTION_INIT, you initialized different exceptions to the same ORACLE error number, then referred to them in different exception handlers within the same EXCEPTION section. Such references conflict.

Action:	Remove one of the exceptions or initialize it to a different ORACLE error number.

PLS-00485:  	in exception handler, 'name' must be an exception name

Cause:	An identifier not declared as an exception appears in an exception handler WHEN clause. Only the name of an exception is valid in a WHEN clause.

Action:	Check your spelling of the exception name and make sure the exception was declared properly.

PLS-00486:  	SELECT list cannot be enclosed in parentheses

Cause:	In a SELECT statement, the select list was enclosed in parentheses, as in:

SELECT (deptno, dname, loc) FROM dept INTO ...

This breaks the rules of SQL syntax. Parentheses are not needed because the keywords SELECT and FROM delimit the select list.

Action:	Remove the parentheses enclosing the select list.

PLS-00487:  	invalid reference to variable 'name'

Cause:	A variable was referenced in a way that is inconsistent with its datatype. For example, you might have mistakenly referenced a scalar variable as a record, as follows:

DECLARE

   CURSOR emp_cur IS SELECT empno, ename, sal FROM emp;

   emp_rec  emp_cur%ROWTYPE;

   my_sal   NUMBER(7,2);

BEGIN    ...    total_sal := total_sal + my_sal.sal;  -- invalid

   ...

Action:	Check your spelling of the variable name. Make sure the variable was declared properly and that the declaration and reference are consistent with regard to datatype.

PLS-00488:  	invalid variable declaration:   object 'name' must be a type or subtype

Cause:	The datatype specifier in a variable declaration does not designate a legal type. For example, you might have neglected to add the %TYPE attribute to a declaration, as in

DECLARE

   my_sal    emp.sal%TYPE;

   my_ename  emp.ename;    -- missing %TYPE

   ...

When declaring a constant or variable, to provide the datatype of a column automatically, you must use the %TYPE attribute. Likewise, when declaring a record, to provide the datatypes of a row automatically, you must use the %ROWTYPE attribute.

Action:	Make sure the datatype specifier designates a legal type. Remember to use the %TYPE and %ROWTYPE attributes when necessary.

PLS-00489:  	invalid table reference:   'name' must be a column in this expression

Cause:	In a query, a select-list item refers to a table in the FROM clause but not to a database column.

Action:	Check your spelling of the column names, make sure each column in the select list refers to a table in the FROM clause, then re-execute the query.

PLS-00503:  	RETURN <value> statement required for this return from function

Cause:	In a function body, you used a RETURN statement that contains no expression. In procedures, a RETURN statement contains no expression because the statement simply returns control to the caller. However, in functions, a RETURN statement must contain an expression because its value is assigned to the function identifier.

Action:	Add an expression to the RETURN statement.

PLS-00504:  	type 'name'_BASE may not be used outside of package STANDARD

Cause:	In a declaration, you mistakenly specified (for example) the datatype NUMBER_BASE. The datatypes CHAR_BASE, DATE_BASE, MLSLABEL_BASE, and NUMBER_BASE are for internal use only.

Action:	Specify (for example) the datatype NUMBER instead of NUMBER_BASE.

PLS-00505:  	user-defined types may only be defined as PL/SQL tables or records

Cause:	You tried to define a datatype derived from some base type other than RECORD or TABLE. User-defined types must be derived from the RECORD or TABLE type.

Action:	Remove the faulty type definition, or define a RECORD or TABLE type.

PLS-00506:  	user-defined constrained subtypes are disallowed

Cause:	You tried to define a subtype (a subtype associates a base type with a constraint and so defines a subset of values). User-defined subtypes are not allowed in this release of PL/SQL. For example, the following type definition is illegal:

SUBTYPE Acronym IS VARCHAR2(5);  -- illegal

However, future versions of PL/SQL will allow you to define subtypes.

Action:	Remove the illegal type definition.

PLS-00507:  	PL/SQL tables may not be defined in terms of records or other tables

Cause:	In a TABLE type definition, you mistakenly specified a composite datatype (RECORD or TABLE) for the column. The single, unnamed column must belong to a scalar datatype such as CHAR, DATE, or NUMBER.

Action:	Remove the TABLE type definition, or replace the composite datatype specifier with a scalar datatype specifier.

PLS-00700:  	PRAGMA EXCEPTION_INIT of 'name' must follow declaration of its exception in same block

Cause:	A PRAGMA EXCEPTION_INIT was not declared in the same block as its exception. They must be declared in the proper order in the same block, with the PRAGMA EXCEPTION_INIT declaration following the exception declaration.

Action:	Place the PRAGMA EXCEPTION_INIT declaration directly after the declaration of the exception referenced by the pragma.

PLS-00701:  	illegal ORACLE error number num for PRAGMA EXCEPTION_INIT

Cause:	The error number passed to a PRAGMA EXCEPTION_INIT was out of range. The error number must be in the range -9999 .. -1 (excluding -100) for ORACLE errors or in the range -20000 .. -20999 for user-defined errors.

Action:	Use a valid error number.

PLS-00702:  	second argument to PRAGMA EXCEPTION_INIT must be a numeric literal

Cause:	The second argument passed to a PRAGMA EXCEPTION_INIT was something other than a numeric literal (a variable, for example). The second argument must be a numeric literal in the range -9999 .. -1 (excluding -100) for ORACLE errors or in the range -20000 .. -20999 for user-defined errors.

Action:	Replace the second argument with a valid error number.

PLS-00703:  	multiple instances of named argument in list

Cause:	Two or more actual parameters in a subprogram call refer to the same formal parameter.

Action:	Remove the duplicate actual parameter.

PLS-00704:  	'name' must be declared as an exception

Cause:	The exception_name parameter passed to PRAGMA EXCEPTION_INIT is misspelled or does not refer to a legally declared exception. Or, the pragma is misplaced; it must appear in the same declarative section, somewhere after the exception declaration.

Action:	Check your spelling of the exception_name parameter. Then, check the exception declaration, making sure the exception name and the keyword EXCEPTION are spelled correctly. Also make sure the pragma appears in the same declarative section somewhere after the exception declaration.

PLS-00705:  	exceptions not allowed in an expression

Cause:	You mistakenly referred to an exception within an expression. Exceptions have names but not values and therefore cannot contribute values to an expression. For example, the following RETURN statement is illegal:

FUNCTION credit_limit (cust_no INTEGER) RETURN NUMBER IS

   limit       NUMBER;

   over_limit  EXCEPTION;

   ...

BEGIN

   ...

   RETURN over_limit;  -- illegal

END;

Action:	Check your spelling of the identifiers in the expression, then rewrite the expression so that it does not refer to an exception.

PLS-00900:  	can't find body of unit 'name'

Cause:	At runtime, the body of a program unit could not be found. This happens, for example, if you reference a procedure for which a specification but no body exists. (No compile-time errors were generated because the specification exists.)

Action:	Define a body for the program unit.

PLS-00901:  	the datatype of column 'name' of table 'name' is not supported

Cause:	A column in a database table belongs to a datatype that is not supported by the current release of PL/SQL.

Action:	Remove the offending column from the table or copy the desired columns to another table.

PLS-00902:  	a read-only bind variable used in OUT or IN OUT context

Cause:	A host variable that is protected from update was used in a context that allows an update.

Action:	Check the context and change your use of the host variable, or assign the value of the host variable to a PL/SQL local variable, then use the local variable instead.

PLS-00904:  	insufficient privilege to access object 'name'

Cause:	You tried to operate on a database object without the required privilege. This error occurs, for example, if you try to UPDATE a table for which you have only SELECT privileges.

Action:	Ask your DBA to perform the operation or to grant you the required privilege.

PLS-00905:  	object 'name' is invalid

Cause:	You referenced an invalid package specification or stored subprogram. A package specification or stored subprogram is invalid if its source code or any database object it references has been DROPped, REPLACEd, or ALTERed since it was last compiled.

Action:	Find out what invalidated the package specification or stored subprogram, then make sure that ORACLE can recompile it without errors.

PLS-00995:  	unhandled exception # 'num'

Cause:	An exception was raised for which no handler was found. If it cannot find a handler for a raised exception, PL/SQL returns an unhandled exception to the host environment. The number embedded in the message is an ORACLE error code listed in the ORACLE7 Server Messages and Codes Manual.

Action:	Fix the condition that raised the exception, write an appropriate exception handler, or use the OTHERS handler. If there is an appropriate handler in the current block, the exception was raised in a declaration or exception handler. (An exception raised in a declaration or exception handler propagates immediately to the enclosing block.) You can avoid unhandled exceptions by coding an OTHERS handler at the topmost level of every PL/SQL block and subprogram.

PLS-00996:  	out of memory

Cause:	A request from PL/SQL for more memory failed.

Action:	Make sure that you are not referencing the wrong row in a PL/SQL table and that your program is not recursing too deeply.


PART  III . APPENDIXES


APPENDIX A. NEW FEATURES IN VERSION 2

This appendix surveys the new features in PL/SQL Version 2. These features were designed to help you get the most power, speed, and flexibility out of PL/SQL.

________________________________________

Subprograms (Chapter 6)

PL/SQL has two types of subprograms called procedures and functions, which aid application development by isolating operations. Procedures and functions are named PL/SQL blocks, which can take parameters and be invoked. Generally, you use a procedure to perform an action and a function to compute a value.

A subprogram explicitly CREATEd using an ORACLE tool is called a stored subprogram. Once compiled and stored in the database, it is a database object and can be referenced by any number of applications connected to that database.

Procedures and functions provide extensibility. That is, they let you tailor the PL/SQL language to suit your needs. They also promote reliability, support maintainability, and boost performance.

________________________________________

Packages (Chapter 7)

PL/SQL supports information hiding, modularity, and reusability by letting you bundle related PL/SQL types, objects, and subprograms into a package. For example, a package might contain a collection of procedures, or a pool of type definitions and variable declarations. Only the declarations in the package specification are visible and accessible to applications. Implementation details in the package body are hidden and inaccessible.

Once written, the package is compiled, then stored in an ORACLE database, where its contents can be shared by many applications. When you call a packaged subprogram for the first time, the whole package is loaded into memory. Therefore, subsequent calls to related subprograms in the package require no disk I/O. Thus, packages can enhance productivity and improve performance.

________________________________________

New Predefined Datatypes (Chapter 2)

Every constant and variable has a datatype, which specifies a storage format, constraints, and valid range of values. For added flexibility, PL/SQL predefines a variety of new scalar datatypes.

Base Types

PL/SQL provides several new base types: BINARY_INTEGER, VARCHAR2, RAW, LONG RAW, ROWID, and MLSLABEL. However, the last one is available only with Trusted ORACLE, a specially secured version of ORACLE.

You use the BINARY_INTEGER datatype to store integers of virtually any size. PL/SQL represents BINARY_INTEGER values as signed binary numbers, which, unlike NUMBER values, can be used in calculations without conversion. So, using BINARY_INTEGER variables can boost performance.

You use the VARCHAR2 datatype to store variable-length character data. The maximum length of a VARCHAR2 variable is 32767 bytes. You can assign values to a VARCHAR2 variable, pass it to character functions such as LENGTH and SUBSTR, and manipulate it using the SELECT, INSERT, UPDATE, and DELETE statements.

You use the RAW datatype to store binary data or byte strings. For example, a RAW variable might store a sequence of graphics characters or a digitized picture. RAW data is not interpreted by PL/SQL. The maximum length of a RAW variable is 32767 bytes.

You use the LONG RAW datatype to store binary data or byte strings. The maximum length of a LONG RAW value is 32760 bytes. LONG RAW data is like LONG data, except that LONG RAW data is not interpreted by PL/SQL.

Internally, every table in an ORACLE database has a pseudocolumn named ROWID, which stores binary values called rowids. Rowids are the fastest way to access a particular row in a database table. PL/SQL provides a datatype also named ROWID. You can use variables of type ROWID to store rowids in a readable format. Moreover, you can manipulate ROWID variables with the CHARTOROWID and ROWIDTOCHAR functions.

With Trusted ORACLE, you use the MLSLABEL datatype to store operating system labels. Trusted ORACLE uses labels to control access to data. For more information, see the Trusted ORACLE7 Server Administrator's Guide.

Subtypes

A subtype associates a base type with a constraint and so defines a subset of values. For convenience, PL/SQL predefines the following numeric subtypes: NATURAL, POSITIVE, DEC, DECIMAL, DOUBLE PRECISION, FLOAT, INT, INTEGER, NUMERIC, REAL, and SMALLINT. The first two are subtypes of BINARY_INTEGER; the rest are subtypes of NUMBER.

You can use the NATURAL or POSITIVE subtype when you want to restrict a variable to non-negative integer values. And, you can use the DEC, DECIMAL, DOUBLE PRECISION, FLOAT, INT, INTEGER, NUMERIC, REAL, or SMALLINT subtype for compatibility with ANS/ISO, IBM SQL/DS, and IBM DB2 types or when you want an identifier more descriptive than NUMBER.

________________________________________

PL/SQL Tables (Chapter 2)

PL/SQL provides two composite datatypes: TABLE and RECORD. This section discusses the TABLE type; a later section discusses the RECORD type.

Objects of type TABLE are called PL/SQL tables, which are modelled as (but not the same as) database tables. PL/SQL tables use a primary key to give you array-like access to rows.

Like the size of a database table, the size of a PL/SQL table is unconstrained. That is, the number of rows in a PL/SQL table can increase and decrease dynamically. So, your PL/SQL table grows as new rows are added and shrinks as unwanted rows are removed.

PL/SQL tables can have one column and a primary key, neither of which can be named. The column can belong to any scalar type, but the primary key must belong to type BINARY_INTEGER. (Future versions of PL/SQL will allow PL/SQL tables to have multiple, named columns, and composite primary keys of any type.) Like scalar variables, PL/SQL tables can be declared as the formal parameters of procedures and functions.

________________________________________

Support for Host Arrays (Chapter 8)

In the ORACLE Precompiler environment, you can pass input host arrays and indicator arrays to an embedded PL/SQL block. Like a locally declared PL/SQL table, a host array can be indexed by a PL/SQL variable of type BINARY_INTEGER or by a host variable compatible with that type. Normally, the entire host array is passed to PL/SQL. However, you can use the ARRAYLEN statement to specify a smaller array dimension. Furthermore, you can use a procedure call to assign all the values in a host array to rows in a PL/SQL table.

________________________________________

User-defined Records (Chapter 2)

With PL/SQL Version 1, you could use the %ROWTYPE attribute to declare a record type that represents a row in a table or a row retrieved by a cursor. However, you could not specify the datatypes of fields in the record, nor could you define fields of your own. PL/SQL lifts those restrictions by providing the RECORD datatype.

Objects of type RECORD are called records. Unlike PL/SQL tables, records have uniquely named fields, which can belong to different datatypes. Moreover, records can be declared as the formal parameters of procedures and functions. PL/SQL even lets you declare and reference nested records. That is, a record can be the component of another record.

________________________________________

New Built-in Functions (Chapter 2)

PL/SQL provides several new built-in functions for your use.

Transcendental Functions

The transcendental functions include trigonometric, logarithmic, and exponential functions. The ordinary trigonometric functions are SIN, COS, and TAN; the hyperbolic trigonometric functions are SINH, COSH, and TANH. For example, COS(n) returns the cosine of n,

where n is expressed in radians.

The logarithmic function LN(n) returns the natural logarithm of n, where n is greater than 0. The function LOG(m,n) returns the base-m logarithm of n, where m is greater than 1 and n is greater than 0.

The exponential function EXP(n) returns e raised to the nth power, where e ( 2.71828) is the base of the system of natural logarithms.

Conversion Functions

Conversion functions convert a value from one datatype to another. The new functions in this group are CHARTOROWID, ROWIDTOCHAR, HEXTORAW, RAWTOHEX, and TO_LABEL. For example, CHARTOROWID converts a character value from type CHAR or VARCHAR2 to type ROWID.

________________________________________

Full Support for SQL Operators (Chapter 4)

PL/SQL supports all the SQL comparison, set, and row operators.

Comparison Operators

Comparison operators compare one expression to another. The result is always TRUE, FALSE, or NULL. In addition to the other comparison operators, PL/SQL supports the ANY (or its synonym SOME), ALL, and EXISTS operators. For example, EXISTS returns TRUE if a subquery returns at least one row.

Set Operators

Set operators combine the results of two queries into one result. PL/SQL supports the UNION, UNION ALL, INTERSECT, and MINUS operators. For example, UNION returns all distinct rows selected by either query.

Row Operators

Row operators return or reference particular rows. In addition to the other row operators, PL/SQL supports the ALL, DISTINCT, and PRIOR operators. For example, DISTINCT eliminates duplicate rows from the result of a query or from an aggregate expression.

________________________________________

Remote Access (Chapters 4, 6, and 7)

PL/SQL lets you access remote databases. You can even call subprograms and reference packages stored in a remote database. To provide location transparency for remote database objects, you can create synonyms interactively with SQL*Plus or SQL*DBA.

________________________________________

Support for Optimizer Hints (Chapter 4)

For every SQL statement, the ORACLE optimizer generates an execution plan, which is a series of steps that ORACLE takes to execute the statement. PL/SQL lets you suggest to ORACLE the way to optimize certain SQL statements. These suggestions, called hints, can influence decisions made by the optimizer.

________________________________________

National Language Support (Chapter 4)

The ORACLE national language support (NLS) feature allows the use of 16-bit as well as 7- and 8-bit character sets. Moreover, it automatically converts between character sets. PL/SQL fully supports the NLS feature so that your applications can process multilingual data stored in an ORACLE database.

________________________________________

New Keyword DEFAULT (Chapter 2)

Any PL/SQL variable, parameter, or record field can be initialized in its declaration. In fact, a constant must be initialized in its declaration. PL/SQL lets you use the keyword DEFAULT instead of the assignment operator to initialize constants, variables, parameters, and fields.


APPENDIX B. SAMPLE PROGRAMS

This appendix provides several PL/SQL programs to guide you in writing your own. The sample programs illustrate the following important PL/SQL concepts and features:

•	FOR loops

•	cursors

•	scoping

•	batch transaction processing

•	embedded PL/SQL

•	calling a stored procedure

________________________________________

Running the Samples

The sample programs in this appendix and many others throughout this guide are available online and so are preceded by the following comment:

-- available online in file filename

The table below gives their locations in the guide and the names of the corresponding online files. However, the exact name and storage location of an online file are system-dependent.

Location in Guide	Online File

Chapter 1, page 1 - 2	EXAMP1

Chapter 1, page 1 - 6	EXAMP2

Chapter 1, page 1 - 7	EXAMP3

Chapter 2, page 2 - 22	EXAMP4

Chapter 4, page 4 - 18	EXAMP5

Chapter 4, page 4 - 19	EXAMP6

Chapter 4, page 4 - 24	EXAMP7

Chapter 4, page 4 - 25	EXAMP8

Chapter 8, page 8 - 5	EXAMP9

Chapter 8, page 8 - 7	EXAMP10

Chapter 9, page 9 - 13	EXAMP11

Chapter 9, page 9 - 39	EXAMP12

Chapter 9, page 9 - 63	EXAMP13

Chapter 9, page 9 - 86	EXAMP14

Appendix B, page B - 10	SAMPLE1

Appendix B, page B - 11	SAMPLE2

Appendix B, page B - 12	SAMPLE3

Appendix B, page B - 13	SAMPLE4

Appendix B, page B - 16	SAMPLE5

Appendix B, page B - 20	SAMPLE6

Some samples are run interactively from SQL*Plus; others are run from Pro*C programs. You can experiment with the samples from any ORACLE account. However, the Pro*C examples expect you to use the SCOTT/TIGER account.

Before trying the samples, you must create some database tables, then load the tables with data. You do that by running two SQL*Plus scripts, EXAMPBLD and EXAMPLOD, supplied with PL/SQL. These scripts can be found in the PL/SQL installation library. Check the ORACLE installation or user's guide for your system.

Creating the Tables

Below is a listing of the SQL*Plus script EXAMPBLD. The CREATE statements in this script build the database tables processed by the sample programs. To run the script, invoke SQL*Plus, then issue the following command:

SQL> START EXAMPBLD

 EXAMPBLD Script

set compatibility V6

/

drop table accounts

/

create table accounts(

   account_id  number(4) not null,

   bal         number(11,2))

/

create unique index accounts_index on accounts (account_id)

/

drop table action

/

create table action(

   account_id  number(4) not null,

   oper_type   char(1) not null,

   new_value   number(11,2),

   status      char(45),

   time_tag    date not null)

/

drop table bins

/

create table bins(

   bin_num     number(2) not null,

   part_num    number(4),

   amt_in_bin  number(4))

/

drop table data_table

/

create table data_table(

   exper_num  number(2),

   n1         number(5),

   n2         number(5),

   n3         number(5))

/

drop table emp

/

create table emp(

   empno      number(4) not null,

   ename      char(10),

   job        char(9),

   mgr        number(4),

   hiredate   date,

   sal        number(7,2),

   comm       number(7,2),

   deptno     number(2))

/

drop table inventory

/

create table inventory(

   prod_id     number(5) not null,

   product     char(15),

   quantity    number(5))

/

drop table journal

/

create table journal(

   account_id   number(4) not null,

   action       char(45) not null,

   amount       number(11,2),

   date_tag     date not null)

/

drop table num1_tab

/

create table num1_tab(

   sequence   number(3) not null,

   num        number(4))

/

drop table num2_tab

/

create table num2_tab(

   sequence   number(3) not null,

   num        number(4))

/

drop table purchase_record

/

create table purchase_record(

   mesg        char(45),

   purch_date  date)

/

drop table ratio

/

create table ratio(

   sample_id  number(3) not null,

   ratio      number)

/

drop table result_table

/

create table result_table(

   sample_id  number(3) not null,

   x          number,

   y          number)

/

drop table sum_tab

/

create table sum_tab(

   sequence   number(3) not null,

   sum        number(5))

/

drop table temp

/

create table temp(

   num_col1   number(9,4),

   num_col2   number(9,4),

   char_col   char(55))

/

create or replace package personnel as

   type charArrayTyp is table of varchar2(10)

      index by binary_integer;

   type numArrayTyp is table of float

      index by binary_integer;

   procedure get_employees(

      dept_number in     integer,

      batch_size  in     integer,

      found       in out integer,

      done_fetch  out    integer,

      emp_name    out    charArrayTyp,

      job-title   out    charArrayTyp,

      salary      out    numArrayTyp);

end personnel;

/

create or replace package body personnel as

   cursor get_emp (dept_number integer) is

      select ename, job, sal from emp

         where deptno = dept_number;

   procedure get_employees(

      dept_number in     integer,

      batch_size  in     integer,

      found       in out integer,

      done_fetch  out    integer,

      emp_name    out    charArrayTyp,

      job_title   out    charArrayTyp,

      salary      out    numArrayTyp) is

   begin

      if not get_emp%isopen then

         open get_emp(dept_number);

      end if;

      done_fetch := 0;

      found := 0;

      for i in 1..batch_size loop

         fetch get_emp into emp_name(i),

            job_title(i), salary(i);

         if get_emp%notfound then

            close get_emp;

            done_fetch := 1;

            exit;

         else

            found := found + 1;

         end if;

      end loop;

   end get_employees;

end personnel;

/

Loading the Data

Below is a listing of the SQL*Plus script EXAMPLOD. The INSERT statements in this script load (or reset) the database tables processed by the sample programs. To run the script, invoke SQL*Plus in the same ORACLE account from which you ran EXAMPBLD, then issue the following command:

SQL> START EXAMPLOD

 EXAMPLOD Script

delete from accounts

/

insert into accounts values (1,1000.00)

/

insert into accounts values (2,2000.00)

/

insert into accounts values (3,1500.00)

/

insert into accounts values (4,6500.00)

/

insert into accounts values (5,500.00)

/

delete from action

/

insert into action values

   (3,'u',599,null,sysdate)

/

insert into action values

   (6,'i',20099,null,sysdate)

/

insert into action values

   (5,'d',null,null,sysdate)

/

insert into action values

   (7,'u',1599,null,sysdate)

/

insert into action values

   (1,'i',399,null,sysdate)

/

insert into action values

   (9,'d',null,null,sysdate)

/

insert into action values

   (10,'x',null,null,sysdate)

/

delete from bins

/

insert into bins values (1, 5469, 650)

/

insert into bins values (2, 7243, 450)

/

insert into bins values (3, 5469, 120)

/

insert into bins values (4, 5469, 300)

/

insert into bins values (5, 6085, 415)

/

insert into bins values (6, 5469, 280)

/

insert into bins values (7, 8159, 619)

/

delete from data_table

/

insert into data_table values

   (1, 10, 167, 17)

/

insert into data_table values

   (1, 16, 223, 35)

/

insert into data_table values

   (2, 34, 547, 2)

/

insert into data_table values

   (3, 23, 318, 11)

/

insert into data_table values

   (1, 17, 266, 15)

/

insert into data_table values

   (1, 20, 117, 9)

/

delete from emp

/

insert into emp values

   (7369,'SMITH','CLERK',7902,TO_DATE('12-17-80','MM-DD-YY'),

    800,NULL,20)

/

insert into emp values

   (7499,'ALLEN','SALESMAN',7698,TO_DATE('02-20-81','MM-DD-YY'),

    1600,300,30)

/

insert into emp values

   (7521,'WARD','SALESMAN',7698,TO_DATE('02-22-81','MM-DD-YY'),

    1250,500,30)

/

insert into emp values

   (7566,'JONES','MANAGER',7839,TO_DATE('04-02-81','MM-DD-YY'),

    2975,NULL,20)

/

insert into emp values

(7654,'MARTIN','SALESMAN',7698,TO_DATE('09-28-81','MM-DD-YY'),

    1250,1400,30)

/

insert into emp values

   (7698,'BLAKE','MANAGER',7839,TO_DATE('05-1-81','MM-DD-YY'),

    2850,NULL,30)

/

insert into emp values

   (7782,'CLARK','MANAGER',7839,TO_DATE('06-9-81','MM-DD-YY'),

    2450,NULL,10)

/

insert into emp values

   (7788,'SCOTT','ANALYST',7566,SYSDATE-85,3000,NULL,20)

/

insert into emp values

   (7839,'KING','PRESIDENT',NULL,TO_DATE('11-17-81','MM-DD-YY'),

    5000,NULL,10)

/

insert into emp values

   (7844,'TURNER','SALESMAN',7698,TO_DATE('09-8-81','MM-DD-YY'),

    1500,0,30)

/

insert into emp values

   (7876,'ADAMS','CLERK',7788,SYSDATE-51,1100,NULL,20)

/

insert into emp values

   (7900,'JAMES','CLERK',7698,TO_DATE('12-3-81','MM-DD-YY'),

    950,NULL,30)

/

insert into emp values

   (7902,'FORD','ANALYST',7566,TO_DATE('12-3-81','MM-DD-YY'),

    3000,NULL,20)

/

insert into emp values

   (7934,'MILLER','CLERK',7782,TO_DATE('01-23-82','MM-DD-YY'),

    1300,NULL,10)

/

delete from inventory

/

insert into inventory values

   ('TENNIS RACKET', 3)

/

insert into inventory values

   ('GOLF CLUB', 4)

/

insert into inventory values

   ('SOCCER BALL', 2)

/

delete from journal

/

delete from num1_tab

/

insert into num1_tab values (1, 5)

/

insert into num1_tab values (2, 7)

/

insert into num1_tab values (3, 4)

/

insert into num1_tab values (4, 9)

/

delete from num2_tab

/

insert into num2_tab values (1, 15)

/

insert into num2_tab values (2, 19)

/

insert into num2_tab values (3, 27)

/

delete from purchase_record

/

delete from ratio

/

delete from result_table

/

insert into result_table values (130, 70, 87)

/

insert into result_table values (131, 77, 194)

/

insert into result_table values (132, 73, 0)

/

insert into result_table values (133, 81, 98)

/

delete from sum_tab

/

delete from temp

/

commit

________________________________________

Sample 1. FOR Loop

The following example uses a simple FOR loop to insert ten rows into a database table. The values of a loop index, counter variable, and either of two character strings are inserted. Which string is inserted depends on the value of the loop index.

Input Table

Not applicable.

PL/SQL Block

-- available online in file SAMPLE1

DECLARE

   x  NUMBER := 100;

BEGIN

   FOR i IN 1..10 LOOP

      IF MOD(i,2) = 0 THEN     -- i is even

         INSERT INTO temp VALUES (i, x, 'i is even');

      ELSE

         INSERT INTO temp VALUES (i, x, 'i is odd');

      END IF;

      x := x + 100;

   END LOOP;

   COMMIT;

END;

Output Table

 SQL> SELECT * FROM temp ORDER BY col1;

 COL1    COL2    MESSAGE

 ----- -------    ---------

     1     100    i is odd

     2     200    i is even

     3     300    i is odd

     4     400    i is even

     5     500    i is odd

     6     600    i is even

     7     700    i is odd

     8     800    i is even

     9     900    i is odd

    10    1000    i is even

 10 records selected.

________________________________________

Sample 2. Cursors

The next example uses a cursor to select the five highest paid employees from the emp table.

Input Table

SQL> SELECT ename, empno, sal FROM emp ORDER BY sal DESC;

ENAME            EMPNO      SAL

---------- ----------- --------

KING              7839     5000

SCOTT             7788     3000

FORD              7902     3000

JONES             7566     2975

BLAKE             7698     2850

CLARK             7782     2450

ALLEN             7499     1600

TURNER            7844     1500

MILLER            7934     1300

WARD              7521     1250

MARTIN            7654     1250

ADAMS             7876     1100

JAMES             7900      950

SMITH             7369      800

14 records selected.

PL/SQL Block

-- available online in file SAMPLE2

DECLARE

   CURSOR c1 is

      SELECT ename, empno, sal FROM emp

      ORDER BY sal DESC;   -- start with highest paid employee

   my_ename  CHAR(10);

   my_empno  NUMBER(4);

   my_sal    NUMBER(7,2);

BEGIN

   OPEN c1;

   FOR i IN 1..5 LOOP

      FETCH c1 INTO my_ename, my_empno, my_sal;

      EXIT WHEN c1%NOTFOUND;    /* in case the number requested */

                                /* is more than the total       */

                                /* number of employees          */

      INSERT INTO temp VALUES (my_sal, my_empno, my_ename);

      COMMIT;

   END LOOP;

   CLOSE c1;

END;

Output Table

SQL> SELECT * FROM temp ORDER BY col1 DESC;

     COL1     COL2    MESSAGE

--------- --------    -------

     5000     7839    KING

     3000     7902    FORD

     3000     7788    SCOTT

     2975     7566    JONES

     2850     7698    BLAKE

________________________________________

Sample 3. Scoping

The following example illustrates block structure and scope rules. An outer block declares two variables named x and counter and loops four times. Inside this loop is a sub-block that also declares a variable named x. The values inserted into the temp table show that the two x's are indeed different.

Input Table

Not applicable.

PL/SQL Block

-- available online in file SAMPLE3

DECLARE

   x        NUMBER := 0;

   counter  NUMBER := 0;

BEGIN

   FOR i IN 1..4 LOOP

      x := x + 1000;

      counter := counter + 1;

      INSERT INTO temp VALUES (x, counter, 'outer loop');

      /* start an inner block */

      DECLARE

         x  NUMBER := 0;  -- this is a local version of x

      BEGIN

         FOR i IN 1..4 LOOP

            x := x + 1;  -- this increments the local x

            counter := counter + 1;

            INSERT INTO temp VALUES (x, counter, 'inner loop');

         END LOOP;

      END;

   END LOOP;

   COMMIT;

END;

Output Table

SQL> SELECT * FROM temp ORDER BY col2;

   COL1          COL2    MESSAGE

-------      --------    -------------

   1000             1    OUTER loop

      1             2    inner loop

      2             3    inner loop

      3             4    inner loop

      4             5    inner loop

   2000             6    OUTER loop

      1             7    inner loop

      2             8    inner loop

      3             9    inner loop

      4            10    inner loop

   3000            11    OUTER loop

      1            12    inner loop

      2            13    inner loop

      3            14    inner loop

      4            15    inner loop

   4000            16    OUTER loop

      1            17    inner loop

      2            18    inner loop

      3            19    inner loop

      4            20    inner loop

20 records selected.

________________________________________

Sample 4. Batch Transaction Processing

In the next example the accounts table is modified according to instructions stored in the action table. Each row in the action table contains an account number, an action to be taken (I, U, or D for insert, update, or delete), an amount by which to update the account, and a time tag used to sequence the transactions.

On an insert, if the account already exists, an update is done instead. On an update, if the account does not exist, it is created by an insert. On a delete, if the row does not exist, no action is taken.

Input Tables

SQL> SELECT * FROM accounts ORDER BY account_id;

ACCOUNT_ID         BAL

----------   ---------

         1        1000

         2        2000

         3        1500

         4        6500

         5         500

SQL> SELECT * FROM action ORDER BY time_tag;

ACCOUNT_ID  O  NEW_VALUE STATUS                   TIME_TAG

----------  - ---------- ------------------------ ---------

         3  u        599                          18-NOV-88

         6  i      20099                          18-NOV-88

         5  d                                     18-NOV-88

         7  u       1599                          18-NOV-88

         1  i        399                          18-NOV-88

         9  d                                     18-NOV-88

        10  x                                     18-NOV-88

7 records selected.

PL/SQL Block

-- available online in file SAMPLE4

DECLARE

   CURSOR c1 IS

      SELECT account_id, oper_type, new_value FROM action

      ORDER BY time_tag

      FOR UPDATE OF status;

BEGIN

   FOR acct IN c1 LOOP        -- process each row one at a time

   acct.oper_type := upper(acct.oper_type);

   /*----------------------------------------*/

   /* Process an UPDATE.  If the account to  */

   /* be updated doesn't exist, create a new */

   /* account.                               */

   /*----------------------------------------*/

   IF acct.oper_type = 'U' THEN

      UPDATE accounts SET bal = acct.new_value

         WHERE account_id = acct.account_id;

      IF SQL%NOTFOUND THEN  -- account didn't exist. Create it.

         INSERT INTO accounts

            VALUES (acct.account_id, acct.new_value);

         UPDATE action SET status =

            'Update: ID not found. Value inserted.'

            WHERE CURRENT OF c1;

      ELSE

         UPDATE action SET status = 'Update: Success.'

            WHERE CURRENT OF c1;

      END IF;

   /*--------------------------------------------*/

   /* Process an INSERT.  If the account already */

   /* exists, do an update of the account        */

   /* instead.                                   */

   /*--------------------------------------------*/

   ELSIF acct.oper_type = 'I' THEN

      BEGIN

         INSERT INTO accounts

            VALUES (acct.account_id, acct.new_value);

         UPDATE action set status = 'Insert: Success.'

            WHERE CURRENT OF c1;

         EXCEPTION

            WHEN DUP_VAL_ON_INDEX THEN   -- account already exists

               UPDATE accounts SET bal = acct.new_value

                  WHERE account_id = acct.account_id;

               UPDATE action SET status =

                  'Insert: Acct exists. Updated instead.'

                  WHERE CURRENT OF c1;

       END;

   /*--------------------------------------------*/

   /* Process a DELETE.  If the account doesn't  */

   /* exist, set the status field to say that    */

   /* the account wasn't found.                  */

   /*--------------------------------------------*/

   ELSIF acct.oper_type = 'D' THEN

      DELETE FROM accounts

         WHERE account_id = acct.account_id;

      IF SQL%NOTFOUND THEN   -- account didn't exist.

         UPDATE action SET status = 'Delete: ID not found.'

            WHERE CURRENT OF c1;

      ELSE

         UPDATE action SET status = 'Delete: Success.'

            WHERE CURRENT OF c1;

      END IF;

   /*--------------------------------------------*/

   /* The requested operation is invalid.        */

   /*--------------------------------------------*/

   ELSE  -- oper_type is invalid

      UPDATE action SET status =

         'Invalid operation. No action taken.'

         WHERE CURRENT OF c1;

   END IF;

   END LOOP;

   COMMIT;

END;

Output Tables

SQL> SELECT * FROM accounts ORDER BY account_id;

ACCOUNT_ID         BAL

----------   ---------

         1         399

         2        2000

         3         599

         4        6500

         6       20099

         7        1599

6 records selected.

SQL> SELECT * FROM action ORDER BY time_tag;

ACCOUNT_ID  O  NEW_VALUE STATUS                    TIME_TAG

----------  - ---------- ------------------------  ---------

         3  u        599 Update: Success.          18-NOV-88

         6  i      20099 Insert: Success.          18-NOV-88

         5  d            Delete: Success.          18-NOV-88

         7  u       1599 Update: ID not found.     18-NOV-88

                         Value inserted.

         1  i        399 Insert: Acct exists.      18-NOV-88

                         Updated instead.

         9  d            Delete: ID not found.     18-NOV-88

        10  x            Invalid operation.        18-NOV-88

                         No action taken.

7 records selected.

________________________________________

Sample 5. Embedded PL/SQL

The following example shows how you can embed PL/SQL in a high-level host language such as C and demonstrates how a banking debit transaction might be done.

Input Table

SQL> SELECT * FROM accounts ORDER BY account_id;

ACCOUNT_ID         BAL

----------   ---------

         1        1000

         2        2000

         3        1500

         4        6500

         5         500

PL/SQL Block in a C Program

/* available online in file SAMPLE5 */

#include <stdio.h>

   char     buf[20];

EXEC SQL BEGIN DECLARE SECTION;

   int      acct;

   double   debit;

   double   new_bal;

   VARCHAR  status[65];

   VARCHAR  uid[20];

   VARCHAR  pwd[20];

EXEC SQL END DECLARE SECTION;

EXEC SQL INCLUDE SQLCA;

main()

{

   extern double atof();

   strcpy (uid.arr,"scott");

   uid.len=strlen(uid.arr);

   strcpy (pwd.arr,"tiger");

   pwd.len=strlen(pwd.arr);

   printf("\n\n\tEmbedded PL/SQL Debit Transaction Demo\n\n");

   printf("Trying to connect...");

   EXEC SQL WHENEVER SQLERROR GOTO errprint;

   EXEC SQL CONNECT :uid IDENTIFIED BY :pwd;

   printf(" connected.\n");

for (;;)       /*  Loop infinitely */

{

   printf("\n** Debit which account number? (-1 to end) ");

   gets(buf);

   acct = atoi(buf);

   if (acct == -1)     /* Need to disconnect from ORACLE */

   {                   /* and exit loop if account is -1 */

       EXEC SQL COMMIT RELEASE;

       exit(0);

   }

   printf("   What is the debit amount? ");

   gets(buf);

   debit = atof(buf);

   /* ---------------------------------- */

   /* ----- Begin the PL/SQL block ----- */

   /* ---------------------------------- */

   EXEC SQL EXECUTE

   DECLARE

      insufficient_funds    EXCEPTION;

      old_bal               NUMBER;

      min_bal               NUMBER := 500;

   BEGIN

      SELECT bal INTO old_bal FROM accounts

         WHERE account_id = :acct;

         -- If the account doesn't exist, the NO_DATA_FOUND

         -- exception will be automatically raised.

      :new_bal := old_bal - :debit;

      IF :new_bal >= min_bal THEN

         UPDATE accounts SET bal = :new_bal

            WHERE account_id = :acct;

         INSERT INTO journal

            VALUES (:acct, 'Debit', :debit, SYSDATE);

         :status := 'Transaction completed.';

      ELSE

         RAISE insufficient_funds;

      END IF;

   COMMIT;

   EXCEPTION

      WHEN NO_DATA_FOUND THEN

         :status := 'Account not found.';

         :new_bal := -1;

      WHEN insufficient_funds THEN

         :status := 'Insufficient funds.';

         :new_bal := old_bal;

      WHEN OTHERS THEN

         ROLLBACK;

         :status := 'Error: ' || SQLERRM(SQLCODE);

         :new_bal := -1;

   END;

   END-EXEC;

   /* -------------------------------- */

   /* ----- End the PL/SQL block ----- */

   /* -------------------------------- */

   status.arr[status.len] = '\0';  /* null-terminate */

                                   /* the string     */

   printf("\n\n   Status:  %s\n", status.arr);

   if (new_bal >= 0)

      printf("   Balance is now:  $%.2f\n", new_bal);

}  /* End of loop */

errprint:

   EXEC SQL WHENEVER SQLERROR CONTINUE;

   printf("\n\n>>>>> Error during execution:\n");

   printf("%s\n",sqlca.sqlerrm.sqlerrmc);

   EXEC SQL ROLLBACK RELEASE;

   exit(1);

}

Interactive Session

Embedded PL/SQL Debit Transaction Demo

Trying to connect... connected.

** Debit which account number? (-1 to end) 1

   What is the debit amount? 300

   Status:  Transaction completed.

   Balance is now:  $700.00

** Debit which account number? (-1 to end) 1

   What is the debit amount? 900

   Status:  Insufficient funds.

   Balance is now:  $700.00

** Debit which account number? (-1 to end) 2

   What is the debit amount? 500

   Status:  Transaction completed.

   Balance is now:  $1500.00

** Debit which account number? (-1 to end) 2

   What is the debit amount? 100

   Status:  Transaction completed.

   Balance is now:  $1400.00

** Debit which account number? (-1 to end) 99

   What is the debit amount? 100

   Status:  Account not found.

** Debit which account number? (-1 to end) -1

Output Tables

SQL> SELECT * FROM accounts ORDER BY account_id;

ACCOUNT_ID   BAL

---------- -----

         1   700

         2  1400

         3  1500

         4  6500

         5   500

SQL> SELECT * FROM journal ORDER BY date_tag;

ACCOUNT_ID  ACTION                           AMOUNT  DATE_TAG

----------  --------------------------   ----------  ---------

         1  Debit                               300  28-NOV-88

         2  Debit                               500  28-NOV-88

         2  Debit                               100  28-NOV-88

________________________________________

Sample 6. Calling a Stored Procedure

This Pro*C program connects to ORACLE, prompts the user for a department number, then calls a stored procedure named get_employees, which is stored in a package named personnel. The procedure declares three PL/SQL tables as OUT formal parameters, then fetches a batch of employee data into the PL/SQL tables. The matching actual parameters are host arrays. When the procedure finishes, it automatically assigns all row values in the PL/SQL tables to corresponding elements in the host arrays. The program calls the procedure repeatedly, displaying each batch of employee data, until no more data is found.

Input Table

SQL> SELECT ename, empno, sal FROM emp ORDER BY sal DESC;

ENAME            EMPNO      SAL

---------- ----------- --------

KING              7839     5000

SCOTT             7788     3000

FORD              7902     3000

JONES             7566     2975

BLAKE             7698     2850

CLARK             7782     2450

ALLEN             7499     1600

TURNER            7844     1500

MILLER            7934     1300

WARD              7521     1250

MARTIN            7654     1250

ADAMS             7876     1100

JAMES             7900      950

SMITH             7369      800

14 records selected.

Stored Procedure

/* available online in file SAMPLE6 */

#include <stdio.h>

#include <string.h>

typedef char asciz;

EXEC SQL BEGIN DECLARE SECTION;

   /* Define type for null-terminated strings. */

   EXEC SQL TYPE asciz IS STRING(20);

   asciz   username[20];

   asciz   password[20];

   int     dept_no;    /* which department to query */

   char    emp_name[10][21];

   char    job[10][21];

   float   salary[10];

   int     done_flag;

   int     array_size;

   int     num_ret;    /* number of rows returned */

   int     SQLCODE;

EXEC SQL END DECLARE SECTION;

EXEC SQL INCLUDE sqlca;

int print_rows();       /* produces program output      */

int sqlerror();         /* handles unrecoverable errors */

main()

{

   int i;

   /* Connect to ORACLE. */

   strcpy(username, "SCOTT");

   strcpy(password, "TIGER");

   EXEC SQL WHENEVER SQLERROR DO sqlerror();

   EXEC SQL CONNECT :username IDENTIFIED BY :password;

   printf("\nConnected to ORACLE as user: %s\n\n", username);

   printf("Enter department number: ");

   scanf("%d", &dept_no);

   fflush(stdin);

   /* Print column headers. */

   printf("\n\n");

   printf("%-10.10s%-10.10s%s\n", "Employee", "Job", "Salary");

   printf("%-10.10s%-10.10s%s\n", "--------", "---", "------");

   /* Set the array size. */

   array_size = 10;

   done_flag = 0;

   num_ret = 0;

   /* Array fetch loop - ends when NOT FOUND becomes true. */

   for (;;)

   {

      EXEC SQL EXECUTE

         BEGIN personnel.get_employees

            (:dept_no, :array_size, :num_ret, :done_flag,

            :emp_name, :job, :salary);

         END;

      END-EXEC;

      print_rows(num_ret);

      if (done_flag)

         break;

   }

   /* Disconnect from ORACLE. */

   EXEC SQL COMMIT WORK RELEASE;

   exit(0);

}

print_rows(n)

int n;

{

   int i;

   if (n == 0)

   {

      printf("No rows retrieved.\n");

      return;

   }

   for (i = 0; i < n; i++)

      printf("%10.10s%10.10s%6.2f\n",

         emp_name[i], job[i], salary[i]);

}

sqlerror()

{

   EXEC SQL WHENEVER SQLERROR CONTINUE;

   printf("\nORACLE error detected:");

   printf("\n% .70s \n", sqlca.sqlerrm.sqlerrmc);

   EXEC SQL ROLLBACK WORK RELEASE;

   exit(1);

}

Interactive Session

Connected to ORACLE as user: SCOTT

Enter department number: 20

Employee  Job       Salary

--------  ---       ------

SMITH     CLERK     800.00

JONES     MANAGER   2975.00

SCOTT     ANALYST   3000.00

ADAMS     CLERK     1100.00

FORD      ANALYST   3000.00


APPENDIX C. STRING COMPARISON AND ASSIGNMENT SEMANTICS

This appendix explains the semantic differences between the CHAR and VARCHAR2 base types. With ORACLE7 and PL/SQL Version 2, CHAR semantics have changed slightly to comply with the current ANSI/ISO SQL standard. The changes come into play when you assign, compare, INSERT, UPDATE, SELECT, or FETCH character values.

________________________________________

Assigning Character Values

When you assign a character value to a CHAR variable, if the value is shorter than the declared length of the variable, PL/SQL blank-pads the value to the declared length. So, information about trailing blanks is lost. For example, given the declarations

name1  CHAR(10);

name2  CHAR(10);

after the assignments

name1 := 'Tom & ';  -- note trailing blank

name2 := 'Jerry';

the values of name1 and name2 include five trailing blanks.

If the character value is longer than the declared length of the CHAR variable, PL/SQL aborts the assignment and raises the predefined exception VALUE_ERROR. PL/SQL neither truncates the value nor tries to trim trailing blanks. For example, given the declaration

acronym  CHAR(4);

the following assignment raises VALUE_ERROR:

acronym := 'SPCA ';  -- note trailing blank

When you assign a character value to a VARCHAR2 variable, if the value is shorter than the declared length of the variable, PL/SQL neither blank-pads the value nor strips trailing blanks. Character values are assigned intact, so no information is lost. If the character value is longer than the declared length of the VARCHAR2 variable, PL/SQL aborts the assignment and raises VALUE_ERROR. PL/SQL neither truncates the value nor tries to trim trailing blanks.

________________________________________

Comparing Character Values

You can use the relational operators to compare character values for equality or inequality. Comparisons are based on the collating sequence used for the database character set. One character value is greater than another if it follows it in the collating sequence. For example, the following IF condition is TRUE:

name1 := 'COLES';

name2 := 'COLEMAN';

IF (name1 > name2) THEN ...

ANSI/ISO SQL requires that two character values being compared have equal lengths. So, if both values in a comparison belong to type CHAR, blank-padding semantics are used. That is, before comparing character values of unequal length, PL/SQL blank-pads the shorter value to the length of the longer value. For example, given the declarations

name1  CHAR(4) := 'BELL';

name2  CHAR(6) := 'BELL  ';  -- note trailing blanks

the following IF condition is TRUE:

IF (name1 = name2) THEN ...

If either or both values in a comparison belong to type VARCHAR2, non-blank-padding semantics are used. That is, when comparing character values of unequal length, PL/SQL makes no adjustments and uses the exact lengths. For example, given the declarations

name1  VARCHAR2(10) := 'DOW';

name2  CHAR(10)     := 'DOW   ';  -- note trailing blanks

the following IF condition is FALSE:

IF (name1 = name2) THEN ...

Recall from Chapter 2 that all string literals belong to type CHAR. So, if both values in a comparison are literals, blank-padding semantics are used. If one value is a literal, blank-padding semantics are used only if the other value belongs to type CHAR.

________________________________________

INSERTing Character Values

When you INSERT the values of a PL/SQL character variable into an ORACLE database column, whether they are blank-padded or not depends on the column type, not on the variable type.

When you INSERT a character value into a CHAR database column, ORACLE does not strip trailing blanks. If the value is shorter than the defined width of the column, ORACLE blank-pads the value to the defined width. As a result, information about trailing blanks is lost. If the character value is longer than the defined width of the CHAR column, ORACLE aborts the insert and generates an error.

When you INSERT a character value into a VARCHAR2 database column, ORACLE does not strip trailing blanks. If the value is shorter than the defined width of the column, ORACLE does not blank-pad the value. Character values are stored intact, so no information is lost. If the character value is longer than the defined width of the VARCHAR2 column, ORACLE aborts the insert and generates an error.

The same rules apply when UPDATEing.

________________________________________

SELECTing Character Values

When you SELECT values from an ORACLE database column into a PL/SQL character variable, whether they are blank-padded or not depends on the variable type, not on the column type.

When you SELECT a column value into a CHAR variable, if the value is shorter than the declared length of the variable, PL/SQL blank-pads the value to the declared length. As a result, information about trailing blanks is lost. If the character value is longer than the declared length of the CHAR variable, PL/SQL aborts the assignment and raises VALUE_ERROR.

When you SELECT a column value into a VARCHAR2 variable, if the value is shorter than the declared length of the variable, PL/SQL neither blank-pads the value nor strips trailing blanks. Character values are stored intact, so no information is lost. If the character value is longer than the declared length of the VARCHAR2 variable, PL/SQL aborts the assignment and raises VALUE_ERROR.

The same rules apply when FETCHing.

________________________________________

Guidelines

In a given execution environment, whether CHAR is equivalent to VARCHAR2 or not is determined by a command or option that sets ORACLE Version 6 or ORACLE7 compatibility. For example, in the SQL*Plus environment, you issue the SET COMPATIBILITY command, specifying the value V6 or V7 (the default), as follows:

SQL> SET COMPATIBILITY V6

For another example, in the ORACLE Precompiler environment, you specify the runtime option DBMS on the command line, as follows:

... DBMS=V6 ...

The default value is NATIVE, which specifies the version of ORACLE resident on your system, which must be Version 6 or later.

When INSERTing character values, you can ensure that no trailing blanks are stored by using the RTRIM function, which trims trailing blanks. An example follows:

my_empno := 7471;

my_ename := 'LEE    ';  -- note trailing blanks

...

INSERT INTO emp

   VALUES (my_empno, RTRIM(my_ename), ...);  -- inserts 'LEE'


APPENDIX D. THE WITH INTERFACE CLAUSE

This appendix shows you how to use the WITH INTERFACE clause to define an interface between a packaged procedure and a third-generation language (3GL) program. With SQL*Module, the interface allows your 3GL program to call PL/SQL procedures stored in an ORACLE database.

________________________________________

Declaring the Interface

The optional WITH INTERFACE clause can follow a procedure specification, but not a function specification. The procedure must be a public (global) packaged procedure. You code the WITH INTERFACE clause in the package specification using the syntax

PROCEDURE procedure_name [ (formal_parameters) ]

   [ WITH INTERFACE PROCEDURE interface_name

      [ (interface_parameters) ] ];

where interface-parameters stands for the following syntax:

parameter_name  datatype [INDICATOR indicator_name],

parameter_name  datatype [INDICATOR indicator_name],

...

The following rules apply:

•	The procedure name and interface name can be the same.

•	Each formal parameter and indicator parameter must appear as an interface parameter.

•	One of the interface parameters can be a variable named sqlcode of type INTEGER with no indicator.

•	All datatypes must be ANSI/ISO SQL types.

The WITH INTERFACE clause maps each PL/SQL formal parameter to an interface parameter, provides optional indicators, and specifies the order of the interface parameters. In the following example, the packaged procedure stored_proc has an interface named external_proc, which takes five parameters:

PROCEDURE stored_proc (num NUMBER, ch CHAR)

   WITH INTERFACE PROCEDURE external_proc(

      num      INTEGER INDICATOR num_ind,

      num_ind  SMALLINT,

      ch       CHAR(10) INDICATOR ch_ind,

      ch_ind   SMALLINT,

      sqlcode  INTEGER);

The formal parameters num and ch are mapped by repeating them in the WITH INTERFACE clause. Notice that num and ch are associated with indicators num_ind and ch_ind, respectively.

________________________________________

Calling a Stored Procedure

SQL*Module allows a 3GL program to call a stored procedure if two requirements are met: the procedure must be declared using the WITH INTERFACE clause, and one of the interface parameters must be named sqlcode.

SQL*Module uses the contents of the WITH INTERFACE clause to generate a 3GL stub, which links the PL/SQL procedure specification to the calling routine. In effect, the WITH INTERFACE clause provides a prototype to 3GL programs so they can call the associated PL/SQL subprogram. The following example is a C function prototype for a typical 32-bit architecture:

extern void external_proc(long num, short num_ind,

   char *ch, short ch_ind, long sqlcode);

To execute the packaged procedure stored_proc, your 3GL program calls external_proc, passing it five parameters. SQL*Module will have generated the procedure call to stored_proc.


APPENDIX E. RESERVED WORDS

The words listed in this appendix are reserved by PL/SQL. That is, they have a special syntactic meaning to PL/SQL and so cannot be used as identifiers for constants, variables, cursors, types, PL/SQL tables, records, subprograms, or packages.

________________________________________

PL/SQL Reserved Words