PROCEDURE Name ( (Parameter (, Parameter, ... ) ) ) IS (Local Declarations) Begin Executable Statements (Exception Exception Handlers) END (Name)
PROCEDURE Name ( (Parameter (, Parameter, ... ) ) ) IS (Local Declarations) Begin Executable Statements (Exception Exception Handlers) END (Name)
where :-
1)parameter stands for the following syntax:
parameter_name [IN | OUT | IN OUT] datatype [{:= |
DEFAULT} expr]
2)You cannot impose the NOT NULL constraint on a
parameter.
3)you cannot specify a constraint on the datatype. For
example, the following declaration of emp_id is illegal:
PROCEDURE ... (emp_id NUMBER(4)) IS -- illegal; should
be NUMBER
BEGIN ... END;
4)A procedure has two parts:
- the specification.
- the body.
5)The procedure specification :-
-begins with the keyword PROCEDURE .
Procedure Names
-Since a procedure is stored in the database, it must be
named:-
1- to distinguish it from other stored procedures.
2- to make it possible for applications to call it.
-Each publicly-visible procedure in a schema must have a
unique name.
- The name must be a legal PL/SQL identifier.
BEGIN
OPEN c1(dept_num);
LOOP
FETCH c1 INTO emp_name;
EXIT WHEN c1%NOTFOUND;
DBMS_OUTPUT.PUT_LINE(emp_name);
END LOOP;
CLOSE c1;
END;
In the stored procedure example, the department number is
an input parameter, which is used when the parameterized
cursor C1 is opened.
-The formal parameters of a procedure have three major
parts:
1)name :
The name of the parameter, which must be a legal PL/SQL
identifier.
2)mode :
The parameter mode, which indicates whether the parameter
is an input-only parameter (IN), an output-only parameter
(OUT), or is both an input and an output parameter (IN
OUT). If the mode is not specified, IN is assumed.
3)datatype :
The parameter datatype is a standard PL/SQL datatype.
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.
Table 7 - 1 summarizes the information about parameter
modes. Parameter modes are explained in detail in the
PL/SQL User's Guide and Reference.
IN OUT IN OUT
the default must be specified must be specified
passes values to a returns values to passes initial
subprogram the caller values to a
subprogram; returns
updated values to
the caller
formal parameter formal parameter formal parameter
acts like a acts like an acts like an
constant uninitialized initialized
variable variable
formal parameter formal parameter formal parameter
cannot be assigned cannot be used in an should be assigned
a value expression; must be a value
assigned a value
actual parameter actual parameter actual parameter
can be a constant, must be a variable must be a variable
initialized
variable, literal,
or expression
Parameter Datatypes
The datatype of a formal parameter consists of one of the
following:
• an unconstrained type name, such as NUMBER or
VARCHAR2.
• a type that is constrained using the %TYPE or
%ROWTYPE attributes.
Attention: Numerically constrained types such as
NUMBER(2) or VARCHAR2(20) are not allowed in a parameter
list.
%TYPE and %ROWTYPE Attributes
DECLARE
emp_row emp%ROWTYPE; -- declare a record
matching a
-- row in the EMP table
BEGIN
get_emp_rec(7499, emp_row); -- call for emp# 7499
DBMS_OUTPUT.PUT(emp_row.ename || ' ' || emp_row.empno);
DBMS_OUTPUT.PUT(' ' || emp_row.job || ' ' ||
emp_row.mgr);
DBMS_OUTPUT.PUT(' ' || emp_row.hiredate || ' ' ||
emp_row.sal);
DBMS_OUTPUT.PUT(' ' || emp_row.comm || ' ' ||
emp_row.deptno);
DBMS_OUTPUT.NEW_LINE;
END;
- Stored functions can also return values that are
declared using %ROWTYPE. For example:
FUNCTION get_emp_rec (dept_num IN emp.deptno%TYPE)
RETURN emp%ROWTYPE IS ...
Tables and Records
- You can pass PL/SQL tables as parameters to stored
procedures and functions.
- You can also pass tables of records as parameters.
Default Parameter Values
- Parameters can take default values. You use the
DEFAULT keyword or the assignment operator to give
a parameter a default value. For example, the
specification for the GET_EMP_NAMES procedure
could be written as
PROCEDURE get_emp_names (dept_num IN NUMBER DEFAULT 20)
IS ...
or as
PROCEDURE get_emp_names (dept_num IN NUMBER := 20) IS ...
- When a parameter takes a default value, it can be
omitted from the actual parameter list when you
call the procedure.
old_balance NUMBER;
new_balance NUMBER;
BEGIN
SELECT balance INTO old_balance FROM accounts
WHERE acct_id = acct
FOR UPDATE OF balance;
new_balance := old_balance + credit;
UPDATE accounts SET balance = new_balance
WHERE acct_id = acct;
COMMIT;
EXCEPTION
WHEN NO_DATA_FOUND THEN
INSERT INTO accounts (acct_id, balance)
VALUES(acct, credit);
WHEN OTHERS THEN
ROLLBACK;
END credit_account;
- Notice that both SQL and PL/SQL statements are
included in the CREDIT_ACCOUNT procedure.
BEGIN
INSERT INTO journal
VALUES (acct, kind, sysdate);
IF kind = 'D' THEN
new_status := 'Debit applied';
ELSIF kind = 'C' THEN
new_status := 'Credit applied';
ELSE
new_status := 'New account';
END IF;
END do_journal_entry;
old_balance NUMBER;
new_balance NUMBER;
BEGIN
SELECT balance INTO old_balance FROM accounts
WHERE acct_id = acct
FOR UPDATE OF balance; /* Locks account for
credit update */
new_balance := old_balance + credit;
UPDATE accounts SET balance = new_balance
WHERE acct_id = acct;
do_journal_entry(acct, 'C');
EXCEPTION
WHEN NO_DATA_FOUND THEN /* Create new account if
not found */
INSERT INTO accounts (acct_id, balance)
VALUES(acct, credit);
do_journal_entry(acct, 'N');
WHEN OTHERS THEN /* Return other errors to
application */
new_status := 'Error: ' || SQLERRM(SQLCODE);
END credit_account;
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;
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');
ELSE
RAISE insufficient_funds;
END IF;
(continued next page)
EXCEPTION
WHEN NO_DATA_FOUND THEN
new_status := 'Nonexistent account';
WHEN insufficient_funds THEN
new_status := 'Insufficient funds';
WHEN OTHERS THEN /* Returns other errors to
application */
new_status := 'Error: ' || SQLERRM(SQLCODE);
END debit_account;
PROCEDURE apply_transactions IS
CURSOR trans_cursor IS
SELECT acct_id, kind, amount FROM transactions
WHERE status = 'Pending'
ORDER BY time_tag
FOR UPDATE OF status;
BEGIN
FOR trans IN trans_cursor LOOP /* implicit open
and fetch */
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 table to return result of
applying
this transaction. */
UPDATE transactions SET status = new_status
WHERE CURRENT OF trans_cursor;
END LOOP;
COMMIT; /* Release row locks in TRANSACTIONS table. */
END apply_transactions;
(continued next page)
PROCEDURE enter_transaction (acct NUMBER,
kind CHAR,
amount NUMBER) IS
BEGIN
INSERT INTO transactions
VALUES (acct, kind, amount, 'Pending', sysdate);
COMMIT;
END enter_transaction;
END bank_transactions;
- While packages allow the database administrator or
application developer to organize similar
routines, they also offer increased functionality
and database performance.
Applications for Packages
Packages are used to define related procedures,
variables, and cursors and are often implemented to
provide advantages in the following areas:
• encapsulation of related procedures and variables
• declaration of public and private procedures,
variables, constants, and cursors
• separation of the package specification and package
body
• better performance
Encapsulation
- Stored packages allow you to encapsulate, or
group, related stored procedures, variables,
datatypes, etc. in a single named, stored unit
in the database. This provides for better
organization during the development process.
- Encapsulation of procedural constructs in a
package also makes privilege management easier.
- Granting the privilege to use a package makes
all constructs of the package accessible to the
grantee.
Public and Private Data and Procedures
- The methods of package definition allow you to
specify which variables, cursors, and procedures
are
public
Directly accessible to the user of a package.
private
Hidden from the user of a package.
procedure
is the name of the procedure to be created.
argument
pl/sql_subprogram_body
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
"Procedures" .
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: an optional
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
procedure_specification ::=
PROCEDURE procedure_name (parameter_declaration[,
parameter_declaration]...)];
procedure_body ::=
PROCEDURE procedure_name [(parameter_declaration[,
parameter_declaration]...)] IS
[[object_declaration [object_declaration] ...]
[subprogram_declaration [subprogram_declaration]
...]]
BEGIN
seq_of_statements
[EXCEPTION
exception_handler [exception_handler] ...]
END [procedure_name];
parameter_declaration ::=
parameter_name [IN | OUT | IN OUT]
{ cursor_name%ROWTYPE
| cursor_variable_name%TYPE
| plsql_table_name%TYPE
| record_name%TYPE
| scalar_type_name
| table_name%ROWTYPE
| table_name.column_name%TYPE
| variable_name%TYPE} [{:= | DEFAULT} expression]
object_declaration ::=
{ constant_declaration
| cursor_declaration
| cursor_variable_declaration
| exception_declaration
| plsql_table_declaration
| record_declaration
| variable_declaration}
subprogram_declaration ::=
{function_declaration | procedure_declaration}
procedure_name
This identifies a user-defined procedure. For naming
conventions, see "Identifiers" .
parameter_name
This identifies a formal parameter, which is a variable
declared in a procedure specification and referenced in
the procedure body.
IN, OUT, IN OUT
These parameter modes define the behavior of formal
parameters. An IN parameter 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
This operator or keyword allows you to initialize IN
parameters to default values.
expression
This is an arbitrarily complex combination of variables,
constants, literals, operators, and function calls. The
simplest expression consists of a single variable. For
the syntax of expression, see "Expressions" on page 10 -
41. When the declaration is elaborated, the value of
expression is assigned to the parameter. The value and
the parameter must have compatible datatypes.
DROP PROCEDURE
Purpose
To remove a stand-alone stored procedure from the database.
Prerequisites
The procedure must be in your own schema or you must have DROP ANY PROCEDURE system
privilege.
If you are using Trusted Oracle7 in DBMS MAC mode, your DBMS label must match
the cluster's creation label or you must satisfy one of the following criteria:
• If the procedure's creation label is higher than your DBMS label, you must have READUP and
WRITEUP system privileges
• If the procedure's creation label is lower than your DBMS label, you must have
WRITEDOWN system privilege.
• If the procedure's creation label and your DBMS label are not comparable, you must have
READUP, WRITEUP, and WRITEDOWN system privileges.
Syntax
Keywords and Parameters
schema
is the schema containing the procedure. If you omit schema, Oracle7 assumes the
procedure is in your own schema.
procedure
is the name of the procedure to be dropped.
Usage Notes
When you drop a procedure, Oracle7 invalidates any local objects that depend upon the dropped
procedure. If you subsequently reference one of these objects, Oracle7 tries to recompile the object and
returns an error message if you have not recreated the dropped procedure.
For information on how Oracle7 maintains dependencies among schema objects,
including remote objects.
You can only use this command to drop a stand-alone procedure. To remove a
procedure that is part of a package, use one of the following methods:
• Drop the entire package using the DROP PACKAGE command.
• Redefine the package without the procedure using the CREATE PACKAGE command with
the OR REPLACE option.
Example
The following statement drops the procedure TRANSFER owned by the user
KERNER:
DROP PROCEDURE kerner.transfer
When you drop the TRANSFER procedure, Oracle7 invalidates all objects that
depend upon TRANSFER.