Tài liệu Oracle PL/SQL Language Pocket Reference- P17 - Pdf 87

Database trigger Record or column of table The body of the trigger is coded in PL/
SQL. While the trigger has a name, the
PL/SQL code itself is unnamed, hence
anonymous.
Script SQL*Plus and SQL*DBA Ad hoc programs and batch processing
scripts written in SQL*Plus are always
anonymous blocks (which may then
call procedures or functions).
Embedded PL/SQL programs Pro* embedded languages Embed PL/SQL blocks to execute
statements inside the database server.
Whenever you attach PL/SQL code to a trigger or field in a tool, that code forms an anonymous PL/
SQL block. When you write this code you can enter a fully specified PL/SQL block (declaration,
execution, and exception sections), or you can enter only the executable section.
15.3.4 Nested Blocks
PL/SQL allows you to nest or embed anonymous blocks within another PL/SQL block. You can also
nest anonymous blocks within anonymous blocks for more than one level, as shown in
Figure 15.6.
Figure 15.6: Anonymous blocks nested three levels deep
15.3.4.1 Nested block terminology
A PL/SQL block nested within another PL/SQL block may be called by any of the following: nested
Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark.
block, enclosed block, child block or sub-block.
A PL/SQL block that calls another PL/SQL block (anonymous or named) may be referred to as either
the enclosing block or the parent block.
15.3.4.2 Nested blocks provide scope
The general advantage of a nested block is that you create a scope for all the declared objects and
executable statements in that block. You can use this scope to improve your control over activity in
your program. For a discussion, see
Section 15.3.5, "Scope and Visibility" later in this chapter.
Consider the following procedure, in which the president and vice-president of the specified company
request their salaries be cut in half if their current salaries are more than ten times the average salary

Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark.
UPDATE employee SET salary := salary * .50
WHERE company_id = company_id_in
AND title = `PRESIDENT';
ELSE
DBMS_OUTPUT.PUT_LINE ('The Prez is a pal!');
END IF;
EXCEPTION
WHEN NO_DATA_FOUND THEN NULL;
END;
END;
Each of the two SELECT-UPDATE combinations is embedded in its own anonymous PL/SQL block.
Each block has its own exception section. Why go to all this trouble? Why couldn't the programmer
just create a little script that will update the salary for a specified title? The following statement,
saved to the updemp.sql file, would "do the trick" (&N is the syntax used to supply arguments to a
SQL*Plus script):
UPDATE employee SET salary := salary * .50
WHERE company_id = &1
AND title = '&2'
AND salary > &3 * 10;
and then execute the SQL script in SQL*Plus using the START command:
SQL> start updemp 1100 VICE-PRESIDENT
SQL> start updemp 1100 PRESIDENT
The programmer who was assigned this task took several things into account:

The executives might decide they will want to take such actions repeatedly in the coming
years; better to package the steps into a reusable chunk of code like a procedure than simply
execute a series of SELECT-UPDATEs in SQL*Plus.

Executives come and go frequently at the company. There is no guarantee that there will be a

AND title = 'PRESIDENT';
ELSE
DBMS_OUTPUT.PUT_LINE ('The Prez is a pal!');
END IF;
END;
If there is a record in the employee table with the title of "VICE-PRESIDENT" (for the appropriate
company_id) and if there is a record in the employee table with the title of "PRESIDENT," then this
procedure works just fine. But what if there is no record with a title of "VICE-PRESIDENT"? What
if the Vice-President did not want to take a 50% cut in pay and instead quit in disgust?
When the WHERE clause of an implict SELECT statement does not identify any records, PL/SQL
raises the NO_DATA_FOUND exception (for more details on this phenomenon see
Chapter 6,
Database Interaction and Cursors, and pay particular attention to the sections concerning implicit
cursors). There is no exception handler section in this procedure. As a result, when there is no Vice-
President in sight, the procedure will immediately complete (well, abort, actually) and transfer
control to the calling block's exception section to see if the NO_DATA_FOUND exception is
handled there. The SELECT-UPDATE for the President's salary is therefore not executed at all.
NOTE: You don't actually need a BEGIN-END block around the second SELECT-
UPDATE. This is the last statement, and if it fails nothing will be skipped. It is good
practice, however, to include an exception statement for the procedure as a whole to
trap errors and handle them gracefully.
Our programmer would hate to see an executive's wish go unfulfilled, so we need a mechanism to
trap the failure of the first SELECT and allow PL/SQL procedure execution to continue on to the next
SELECT-UPDATE. The embedded anonymous block offers this protection. By placing the first
Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark.
SELECT within a BEGIN-END envelope, you can also define an exception section just for the
SELECT. Then, when the SELECT fails, control is passed to the exception handler for that specific
block, not to the exception handler for the procedure as a whole (see
Figure 15.7). If you then code an
exception to handle NO_DATA_FOUND which allows for continued processing, the next SELECT-

UPDATE employee SET salary := salary * decr_in
WHERE company_id = company_id_in
AND title = title_in;
END IF;
CLOSE salcur;
END;
BEGIN
update_exec ('VICE-PRESIDENT');
update_exec ('PRESIDENT');
END;
This final version also offers the advantage of consolidating the two SELECTs into a single explicit
cursor, and the two UPDATEs into a single statement, thereby reducing the amount of code one
would have to test and maintain. Whether you go with named or anonymous blocks, the basic
concept of program (and therefore exception) scope remains the same. Use the scoping and visibility
rules to your advantage by isolating areas of code and cleaning up the program flow.
15.3.5 Scope and Visibility
Two of the most important concepts related to a PL/SQL block are those of the scope and visibility of
identifiers. An identifier is the name of a PL/SQL object, which could be anything from a variable to
a program name. In order to manipulate a PL/SQL identifier (assign a value to it, pass it as a
parameter, or call it in a module), you have to be able to reference that identifier in such a way that
the code will compile.
The scope of an identifier is the part of a program in which you can make a reference to the identifier
and have that reference resolved by the compiler. An identifier is visible in a program when it can be
referenced using an unqualified name.
Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark.
15.3.5.1 Qualified identifiers
A qualifier for an identifier can be a package name, module name (procedure or function), or loop
label. You qualify the name of an identifer with dot notation, the same way you would qualify a
column name with the name of its table.
The names of the following identifiers are qualified:

blocks defined within the first, enclosing block. For example, in the following anonymous block, the
variable last_date can be referenced anywhere inside the block:
/* The enclosing or outer anonymous block. */
DECLARE
last_date DATE;
BEGIN
last_date := LAST_DAY (SYSDATE);
/* The inner anonymous block. */
BEGIN
IF last_date > :employee.hire_date
THEN
...
END IF;
END;
...
END;
Even though last_date is not defined in the inner block, it can still be referenced there without
qualification because the inner block is defined inside the outer block. The last_date variable is
therefore considered a global variable in the inner block.
Figure 15.8 shows additional examples illustrating the concept of scope in PL/SQL blocks.
Figure 15.8: Scope of identifiers in PL/SQL blocks
15.3.5.3 Qualifying identifier names with module names
When necessary, PL/SQL offers many ways to qualify an identifier so that a reference to the
Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark.
identifier can be resolved. Suppose I create a package called company_pkg and declare a variable
named last_company_id in that package's specification, as follows:
PACKAGE company_pkg
IS
last_company_id NUMBER;
...

Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark.
To use a cursor, you must declare it. But you cannot refer to that cursor -- whether to OPEN, CLOSE,
or FETCH from it -- unless that cursor is accessible in your current PL/SQL block. The scope of a
cursor is that part of a PL/SQL program in which you can refer to the cursor.
You can refer to a cursor in the code block in which it was declared and in all blocks defined within
that declaring block. You cannot refer to the cursor outside of the declaring block unless the cursor is
declared in a package (see
Chapter 16, Packages, for more information on global variables and
cursors). For example, if a cursor is declared in the get_employees procedure (see below) and within
get_employees a second PL/SQL block is defined to calculate total compensation for each employee,
the cursor and its attributes may still be referenced in that calculation block:
PROCEDURE get_employees
IS
CURSOR emp_cur IS
SELECT employee_id, sal + bonus FROM employee;
BEGIN
OPEN emp_cur;
DECLARE
empid NUMBER;
total_comp NUMBER;
BEGIN
FETCH emp_cur INTO empid, total_comp;
IF total_comp < 5000
THEN
MESSAGE (' I need a raise!');
END IF;
END;
END;
If, on the other hand, the cursor is declared within an inner block, then that cursor cannot be
referenced in an outer block. In the next procedure, the outer block declares the variables that receive

that code. You also clarify your own thinking about what that code is supposed to do,
sometimes ferreting out errors in the process.

Qualify the names of elements declared in the block to distinguish between references to
elements with a different scope, but the same name.
A PL/SQL label has this format:
<<identifer>>
where identifier is a valid PL/SQL identifier (up to 30 characters in length, starting with a letter; see
Section 2.2, "Identifiers" in Chapter 2 in Chapter 2, PL/SQL Language Fundamentals, for a complete
list of rules).
Let's look at a couple of examples of applying block labels. In the first example, I place a label in
front of my block simply to give it a name and document its purpose:
<<calc_dependencies>>
DECLARE
v_senator VARCHAR2(100) := 'THURMOND, JESSE';
BEGIN
IF total_contributions (v_senator, 'TOBACCO') > 25000
THEN
DBMS_OUTPUT.PUT_LINE ('We''re smokin''!');
END IF;
Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark.
END;
In the next example, I use my block labels to allow me to reference all variables declared in my outer
and inner blocks:
<<tobacco_dependency>>
DECLARE
v_senator VARCHAR2(100) := 'THURMOND, JESSE';
BEGIN
IF total_contributions (v_senator, 'TOBACCO') > 25000
THEN

Copyright (c) 2000 O'Reilly & Associates. All rights reserved.
Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark.
Previous: 15.3 The
Anonymous PL/SQL Block
Chapter 15
Procedures and Functions
Next: 15.5 Functions

15.4 Procedures
A procedure is a module performing one or more actions. Because a procedure is a standalone
executable statement in PL/SQL, a PL/SQL block could consist of nothing more than a single call to
a procedure. Procedures are key building blocks of modular code, allowing you to both consolidate
and reuse your program logic.
The general format of a PL/SQL procedure is as follows:
PROCEDURE name [ ( parameter [, parameter ... ] ) ]
IS
[declaration statements]
BEGIN
executable-statements
[ EXCEPTION
exception handler statements]
END [ name ];
where each component is used in the following ways:
name
The name of the procedure comes directly after the keyword PROCEDURE.
parameters
An optional list of parameters that you define to both pass information into the procedure and
send information out of the procedure, back to the calling program.
declaration statements
The declarations of local identifiers for that procedure. If you do not have any declarations,

The header for the apply_discount procedure discussed above is:
PROCEDURE apply_discount
(company_id_in IN company.company_id%TYPE,
discount_in IN NUMBER)
It consists of the module type, the name, and a list of two parameters.
15.4.3 Procedure Body
The body of the procedure is the code required to implement the procedure. It consists of the
declaration, execution, and exception sections of the function. Everything after the IS keyword in the
procedure makes up that procedure's body.
Once again, the declaration and exception sections are optional. If you have no exception handlers,
you will leave off the EXCEPTION keyword and simply enter the END statement to terminate the
procedure.
If you do not have any declarations, the BEGIN statement simply follows immediately after the IS
keyword (see the do_nothing procedure below for an example of this structure.).
You must supply at least one executable statement in a procedure. Here is my candidate for the
Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark.
procedure in PL/SQL with the smallest possible body:
PROCEDURE do_nothing IS
BEGIN
NULL;
END;
Does the do_nothing procedure seem silly? A procedure that doesn't do anything can, in fact, be very
useful when you are creating stubs for modules in a top-down design effort. I have also used this kind
of procedure when building templates. My do_nothing procedure acts initially as a placeholder in my
code, but then also provides a mechanism for customization of the templates.
15.4.4 The END Label
You can append the name of the procedure directly after the END keyword when you complete your
procedure, as shown below:
PROCEDURE display_stores (region_in IN VARCHAR2) IS
BEGIN

Appendix C, Built-In Packages, describes the built-in functions that PL/SQL provides to help you
write your programs. You can also write your own functions -- numeric functions, VARCHAR2
functions, and even functions that return a PL/SQL table or record. The programmer-defined
function, a powerful addition to your toolchest, will aid greatly in making your code more flexible
and easier to understand.
15.5.1 Structure of a Function
The structure of a function is the same as that of a procedure, except that the function also has a
RETURN clause. The general format of a function follows:
FUNCTION name [ ( parameter [, parameter ... ] ) ]
RETURN return_datatype
IS
[ declaration statements ]
BEGIN
executable statements
[ EXCEPTION
exception handler statements ]
END [ name ];
where each component is used in the following ways:
Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark.
name
The name of the procedure comes directly after the keyword FUNCTION.
parameters
An optional list of parameters that you define to both pass information into the procedure and
send information out of the procedure, back to the calling program.
return_datatype
The datatype of the value returned by the function. This is required in the function header and
is explained in more detail in the next section.
declaration statements
The declarations of local identifiers for that function. If you do not have any declarations, then
there will not be any statements between the IS and BEGIN statements.


Object type (PL/SQL8)

Large objects (LOBs) such as BFILEs and CLOBs (PL/SQL8)
The datatype of a function cannot be either of the following:
Named exception
Once you declare an exception, you can reference that exception only in a RAISE statement
and in the exception handler itself.
Cursor name
You cannot return a cursor from a function. (Note that PL/SQL Release 2.2 and beyond
provides a REF CURSOR TYPE declaration that will allow you to return a cursor and even
declare a parameter as a cursor.)
15.5.3 The END Label
You can append the name of the function directly after the END keyword when you complete your
function, as shown below:
FUNCTION tot_sales (company_in IN INTEGER) RETURN NUMBER
IS
BEGIN
...
END tot_sales;
This name serves as a label that explicitly links up the end of the program with its beginning. You
should as a matter of habit use an END label. It is especially important to do so when you have a
function that spans more than a single page, or is one in a series of functions and procedures in a
package body.
15.5.4 Calling a Function
A function is called as part of an executable PL/SQL statement, wherever an expression can be used.
The following examples illustrate the different ways that the tot_sales function demonstrated in
Figure 15.10 might be called:

Call tot_sales to assign a value to a local PL/SQL variable:


Nhờ tải bản gốc

Tài liệu, ebook tham khảo khác

Music ♫

Copyright: Tài liệu đại học © DMCA.com Protection Status