Добавил:
Опубликованный материал нарушает ваши авторские права? Сообщите нам.
Вуз: Предмет: Файл:
Скачиваний:
51
Добавлен:
16.04.2013
Размер:
5.97 Mб
Скачать

Understanding the Main Features of PL/SQL

END LOOP;

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

COMMIT;

EXCEPTION

WHEN NO_DATA_FOUND THEN

INSERT INTO temp VALUES (NULL, NULL, 'Not found');

COMMIT;

END;

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

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 amount := commission * 0.25;

ELSE

amount := salary * 0.10; END IF;

Writing Reusable PL/SQL Code

PL/SQL lets you break an application down into manageable, well-defined modules. PL/SQL meets this need with program units, which include blocks, subprograms, and packages. You can reuse program units by loading them into the database as triggers, stored procedures, and stored functions.

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 -- executable part starts here

SELECT comm * 0.15 INTO bonus FROM emp WHERE empno = emp_id; IF bonus IS NULL THEN

Overview of PL/SQL 1-9

Understanding the Main Features of PL/SQL

RAISE comm_missing; ELSE

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

EXCEPTION -- exception-handling part starts here WHEN comm_missing THEN

...

END award_bonus;

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

Packages

PL/SQL lets you bundle logically related types, variables, cursors, and subprograms into a package, a database object that is a step above regular stored procedures. The packages defines a simple, clear, interface to a set of related procedures and types.

Packages usually have two parts: a specification and a body. The specification defines the application programming interface; it declares the types, constants, variables, exceptions, cursors, and subprograms. The body fills in the SQL queries for cursors and the code for subprograms.

The following example packages two employment procedures:

CREATE PACKAGE emp_actions AS -- package specification

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

PROCEDURE fire_employee (emp_id NUMBER);

END emp_actions;

CREATE PACKAGE BODY emp_actions AS -- 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;

Applications that call these procedures only need to know the names and parameters from the package spec. You can change the implementation details inside the package body without affecting the calling applications.

Packages are stored in the database, where they can be shared by many applications. Calling a packaged subprogram for the first time loads the whole package and caches it in memory, saving on disk I/O for subsequent calls. Thus, packages enhance reuse and improve performance in a multi-user, multi-application environment.

Data Abstraction

Data abstraction lets you work with the essential properties of data without being too involved with details. Once you design a data structure, you can focus on designing algorithms that manipulate the data structure.

1-10 PL/SQL User's Guide and Reference

Understanding the Main Features of PL/SQL

Collections

PL/SQL collection types let you declare high-level datatypes similar to arrays, sets, and hash tables found in other languages. In PL/SQL, array types are known as varrays (short for variable-size arrays), set types are known as nested tables, and hash table types are known as associative arrays. Each kind of collection is an ordered group of elements, all of the same type. Each element has a unique subscript that determines its position in the collection.

To reference an element, use subscript notation with parentheses. For example, the following call references the fifth element in the nested table (of type Staff) returned by function new_hires:

DECLARE

TYPE Staff IS TABLE OF Employee; staffer Employee;

FUNCTION new_hires (hiredate DATE) RETURN Staff IS BEGIN ... END;

BEGIN

staffer := new_hires('10-NOV-98')(5); END;

Collections can be passed as parameters, so that subprograms can process arbitrary numbers of elements.You can use collections to move data into and out of database tables using high-performance language features known as bulk SQL.

Records

Records are composite data structures whose fields can have different datatypes. You can use records to hold related items and pass them to subprograms with a single parameter.

You can use the %ROWTYPE attribute to declare a record that represents a row in a table or a row from a query result set, without specifying the names and types for the fields.

Consider the following example:

DECLARE

TYPE TimeRec IS RECORD (hours SMALLINT, minutes SMALLINT); TYPE MeetingTyp IS RECORD (

date_held DATE,

duration TimeRec, -- nested record location VARCHAR2(20),

purpose VARCHAR2(50));

Object Types

PL/SQL supports object-oriented programming through object types. An object type encapsulates a data structure along with the functions and procedures needed to manipulate the data. The variables that form the data structure are known as attributes. The functions and procedures that manipulate the attributes are known as methods.

Object types reduce complexity by breaking down a large system into logical entities. This lets you create software components that are modular, maintainable, and reusable.

Object-type definitions, and the code for the methods, are stored in the database. Instances of these object types can be stored in tables or used as variables inside PL/SQL code.

Overview of PL/SQL 1-11

Соседние файлы в папке Oracle 10g