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

Understanding The Package Body

You can reference package contents from database triggers, stored subprograms, 3GL application programs, and various Oracle tools. For example, you might call the packaged procedure hire_employee from SQL*Plus, as follows:

CALL emp_actions.hire_employee('TATE', 'CLERK', ...);

The following example calls the same procedure from an anonymous block in a Pro*C program. The actual parameters emp_name and job_title are host variables.

EXEC SQL EXECUTE BEGIN

emp_actions.hire_employee(:emp_name, :job_title, ...);

Restrictions

You cannot reference remote packaged variables, either directly or indirectly. For example, you cannot call the a procedure through a database link if the procedure refers to a packaged variable.

Inside a package, you cannot reference host variables.

Understanding The Package Body

The package body contains the implementation of every cursor and subprogram declared in the package spec. Subprograms defined in a package body are accessible outside the package only if their specs also appear in the package spec. If a subprogram spec is not included in the package spec, that subprogram can only be called by other subprograms in the same package.

To match subprogram specs and bodies, PL/SQL does a token-by-token comparison of their headers. Except for white space, the headers must match word for word. Otherwise, PL/SQL raises an exception, as the following example shows:

CREATE PACKAGE emp_actions AS

...

PROCEDURE calc_bonus (date_hired emp.hiredate%TYPE, ...); END emp_actions;

/

CREATE PACKAGE BODY emp_actions AS

...

PROCEDURE calc_bonus (date_hired DATE, ...) IS

--parameter declaration raises an exception because 'DATE'

--does not match 'emp.hiredate%TYPE' word for word

BEGIN ... END; END emp_actions;

/

The package body can also contain private declarations, which define types and items necessary for the internal workings of the package. The scope of these declarations is local to the package body. Therefore, the declared types and items are inaccessible except from within the package body. Unlike a package spec, 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.

9-6 PL/SQL User's Guide and Reference

Some Examples of Package Features

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.

Remember, if a package spec declares only types, constants, variables, exceptions, and call specs, the package body is unnecessary. However, the body can still be used to initialize items declared in the package spec.

Some Examples of Package Features

Consider the following package, named emp_actions. The package spec declares the following types, items, and subprograms:

Types EmpRecTyp and DeptRecTyp

Cursor desc_salary

Exception invalid_salary

Functions hire_employee and nth_highest_salary

Procedures fire_employee and raise_salary

After writing the package, you can develop applications that reference its types, call its subprograms, use its cursor, and raise its exception. When you create the package, it is stored in an Oracle database for use by any application that has execute privilege on the package.

CREATE PACKAGE emp_actions AS

/* Declare externally visible types, cursor, exception. */ TYPE EmpRecTyp IS RECORD (emp_id INT, salary REAL);

TYPE DeptRecTyp IS RECORD (dept_id INT, location VARCHAR2); CURSOR desc_salary RETURN EmpRecTyp;

invalid_salary EXCEPTION;

/* Declare externally callable subprograms. */ FUNCTION hire_employee (

ename VARCHAR2, job VARCHAR2, mgr REAL, sal REAL, comm REAL,

deptno REAL) RETURN INT; PROCEDURE fire_employee (emp_id INT);

PROCEDURE raise_salary (emp_id INT, grade INT, amount REAL); FUNCTION nth_highest_salary (n INT) RETURN EmpRecTyp;

END emp_actions;

/

CREATE PACKAGE BODY emp_actions AS

number_hired INT; -- 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 VARCHAR2, job VARCHAR2, mgr REAL, sal REAL,

Using PL/SQL Packages 9-7

Some Examples of Package Features

comm REAL,

deptno REAL) RETURN INT IS new_empno INT;

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 INT) IS

BEGIN

DELETE FROM emp WHERE empno = emp_id;

END fire_employee;

/* Define local function, available only inside package. */ FUNCTION sal_ok (rank INT, salary REAL) RETURN BOOLEAN IS

min_sal REAL; max_sal REAL;

BEGIN

SELECT losal, hisal INTO min_sal, max_sal FROM salgrade WHERE grade = rank;

RETURN (salary >= min_sal) AND (salary <= max_sal); END sal_ok;

PROCEDURE raise_salary (emp_id INT, grade INT, amount REAL) IS salary REAL;

BEGIN

SELECT sal INTO salary FROM emp WHERE empno = emp_id; IF sal_ok(grade, salary + amount) THEN

UPDATE emp SET sal = sal + amount WHERE empno = emp_id; ELSE

RAISE invalid_salary; END IF;

END raise_salary;

FUNCTION nth_highest_salary (n INT) RETURN EmpRecTyp IS emp_rec EmpRecTyp;

BEGIN

OPEN desc_salary; FOR i IN 1..n LOOP

FETCH desc_salary INTO emp_rec; END LOOP;

CLOSE desc_salary; RETURN emp_rec;

END nth_highest_salary;

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. In the last example, only one row is inserted into the database table emp_audit, and 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

9-8 PL/SQL User's Guide and Reference

Some Examples of Package Features

count reflects the number of new employees processed by one user, not the number processed by all users.

The following example is a package that handles typical bank transactions. Assume that debit and credit transactions are entered after business hours through automatic teller machines, then applied to accounts the next morning.

CREATE PACKAGE bank_transactions AS

/* Declare externally visible constant. */ minimum_balance CONSTANT REAL := 100.00;

/* Declare externally callable procedures. */ PROCEDURE apply_transactions;

PROCEDURE enter_transaction ( acct INT,

kind CHAR, amount REAL);

END bank_transactions;

/

CREATE PACKAGE BODY bank_transactions AS

/* 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 INT, credit REAL); PROCEDURE debit_account (acct INT, 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 INT,

kind CHAR, amount REAL) IS

BEGIN

INSERT INTO transactions

VALUES (acct, kind, amount, 'Pending', SYSDATE); END enter_transaction;

Using PL/SQL Packages 9-9

Some Examples of Package Features

/* Define local procedures, available only in package. */ PROCEDURE do_journal_entry (

/* Record transaction in journal. */ acct INT,

kind CHAR, new_bal REAL) 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 INT, credit REAL) IS /* Credit account unless account number is bad. */

old_balance REAL; new_balance REAL;

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 INT, debit REAL) IS /* Debit account unless account number is bad or

account has insufficient funds. */ old_balance REAL;

new_balance REAL; 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

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

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