Sub topic 1
Recap: the PL/SQL block as the building unit
A stored procedure or function is a PL/SQL block with a name, saved in the database. If you understand the block, you understand the body of every subprogram in this tutorial. This chapter reviews the block, shows how an anonymous block turns into a named one, and covers the edge cases that cause trouble later.
Prerequisites
This chapter assumes you already have the following:
- Basic SQL: SELECT, INSERT, UPDATE, and DELETE.
- Experience with simple PL/SQL anonymous blocks (DECLARE, BEGIN, EXCEPTION, END).
- Familiarity with Oracle data types such as NUMBER, VARCHAR2, and DATE.
- Access to an Oracle schema with the CREATE PROCEDURE privilege. The examples use the HR sample schema (the
employeestable). - A client such as SQLPlus, SQLcl, or SQL Developer. In SQLPlus and SQLcl, run
SET SERVEROUTPUT ONto seeDBMS_OUTPUTtext.
The four parts of a block
A PL/SQL block has up to four parts. Only BEGIN and END are required.
| Part | Keyword | Required | Purpose |
|---|---|---|---|
| Header | `CREATE ... AS/IS` (named blocks only) | Only for stored code | Gives the block a name and parameters |
| Declaration | `DECLARE` (anonymous) or after `AS`/`IS` | No | Variables, constants, cursors, local subprograms |
| Executable | `BEGIN ... ` | Yes | Statements that do the work |
| Exception | `EXCEPTION` | No | Handlers for errors raised in the executable part |
The block ends with END;. A forward slash (/) on its own line tells SQL*Plus-style clients to send the block to the database.
An anonymous block
An anonymous block has no name. The database compiles and runs it, then discards it. Nothing is stored.
SET SERVEROUTPUT ON
DECLARE
v_name employees.last_name%TYPE;
BEGIN
SELECT last_name
INTO v_name
FROM employees
WHERE employee_id = 100;
DBMS_OUTPUT.PUT_LINE('Employee 100: ' || v_name);
EXCEPTION
WHEN NO_DATA_FOUND THEN
DBMS_OUTPUT.PUT_LINE('No such employee');
END;
/The %TYPE attribute anchors the variable to the column's data type. If the column changes from VARCHAR2(25) to VARCHAR2(50), the variable follows automatically. You will use anchored types throughout this tutorial.
From anonymous block to named block
To store the block, replace DECLARE with a CREATE OR REPLACE header. The declaration part now follows AS (or IS, which is equivalent). There is no DECLARE keyword in a stored subprogram.
CREATE OR REPLACE PROCEDURE show_employee_name (
p_employee_id IN employees.employee_id%TYPE
) AS
v_name employees.last_name%TYPE;
BEGIN
SELECT last_name
INTO v_name
FROM employees
WHERE employee_id = p_employee_id;
DBMS_OUTPUT.PUT_LINE('Employee ' || p_employee_id || ': ' || v_name);
EXCEPTION
WHEN NO_DATA_FOUND THEN
DBMS_OUTPUT.PUT_LINE('No such employee');
END show_employee_name;
/Three things changed:
- The header names the procedure and declares a parameter,
p_employee_id, in place of the hard-coded100. ASreplacesDECLARE.- The closing
ENDmay repeat the subprogram name. This is optional but helps readability in long bodies.
Call it from an anonymous block:
BEGIN
show_employee_name(100);
END;
/The stored procedure survives the session. The anonymous block that calls it does not.
Scope and nesting
Blocks can nest. A variable declared in an outer block is visible in inner blocks. A variable declared in an inner block is not visible outside it. If an inner block declares a name that already exists in the outer block, the inner one shadows the outer one.
DECLARE
v_label VARCHAR2(10) := 'outer';
BEGIN
DECLARE
v_label VARCHAR2(10) := 'inner';
BEGIN
DBMS_OUTPUT.PUT_LINE(v_label); -- prints inner
END;
DBMS_OUTPUT.PUT_LINE(v_label); -- prints outer
END;
/Nesting is useful for one reason in particular: it lets you wrap a single statement in its own exception handler so that an error does not abort the whole block.
DECLARE
v_bonus NUMBER;
BEGIN
BEGIN
SELECT commission_pct
INTO v_bonus
FROM employees
WHERE employee_id = 9999;
EXCEPTION
WHEN NO_DATA_FOUND THEN
v_bonus := 0;
END;
DBMS_OUTPUT.PUT_LINE('Bonus: ' || v_bonus);
END;
/Without the inner block, the NO_DATA_FOUND error would leave the outer block and the PUT_LINE call would never run.
How the exception part behaves
The exception part catches errors raised in the executable part of the same block. It has three properties that surprise people.
- Errors in the declaration part are not caught by the same block. If
v_name VARCHAR2(2) := 'Smith';fails with a value error, the handler in that block does not run. The error goes to the enclosing block or the caller. - Errors in a handler are not caught by sibling handlers. An error raised inside
WHEN ... THENcode propagates outward. - Handled errors do not undo earlier work. If a handler catches an error, the statements that already ran stay in effect. The exception is a failed single SQL statement, which Oracle rolls back to the statement's start before control reaches the handler.
An unhandled error leaves the block, and the caller receives it. In a stored subprogram called from SQL*Plus, you see an ORA- message followed by an ORA-06512 line that gives the line number of the failing statement.
Why the block matters for stored code
Four facts about blocks carry over to stored subprograms.
- Compilation. An anonymous block is compiled each time it is sent. A stored subprogram is compiled once, when you run
CREATE OR REPLACE, and the result is kept in the data dictionary. Calls then skip the compile step. - Privileges. Stored code runs with the privileges of its owner by default. An anonymous block runs with the privileges of the session user. The chapter on
AUTHIDexplains this difference. - Reuse. A named block can be called by name, from other PL/SQL, from SQL (for functions), and from client programs. An anonymous block cannot be called from elsewhere.
- Dependencies. A stored subprogram records the objects it references, such as the
employeestable. If one of them changes, the subprogram can become invalid and must be recompiled.
Common errors when moving to named blocks
| Symptom | Likely cause | Fix |
|---|---|---|
| `Warning: Procedure created with compilation errors.` | A syntax error or a reference to an unknown object | Run `SHOW ERRORS`, or query `USER_ERRORS` |
| `PLS-00103: Encountered the symbol "DECLARE"` | `DECLARE` used after `CREATE ... AS` | Delete `DECLARE`; put declarations right after `AS` |
| The block text shows but nothing runs | The closing `/` is missing | Add `/` alone on the line after `END;` |
| `ORA-00942: table or view does not exist` inside a stored procedure | The owner has the table only through a role, not a direct grant | Grant the privilege directly to the owner |
| No output appears | `SERVEROUTPUT` is off | Run `SET SERVEROUTPUT ON` |
Check your understanding
Exercise
You convert an anonymous block that starts with DECLARE v_total NUMBER; into a stored procedure named calc_total. Write the first lines of the new header and declaration part, and say which keyword you remove.
Show answer
Remove DECLARE. The new text is CREATE OR REPLACE PROCEDURE calc_total AS followed by v_total NUMBER; and then BEGIN. A stored subprogram uses AS or IS in place of DECLARE.
Exercise
In the block below, does the handler run when the declaration fails? Explain what the caller sees. DECLARE vcode VARCHAR2(2) := 'ABC'; BEGIN NULL; EXCEPTION WHEN OTHERS THEN DBMSOUTPUT.PUT_LINE('Handled'); END;
Show answer
No. The assignment in the declaration part fails with ORA-06502 (character string buffer too small). The exception part of the same block only covers the executable part, so "Handled" is not printed. The error goes to the caller, which sees ORA-06502 followed by ORA-06512.
Exercise
A procedure runs an UPDATE, then a later SELECT INTO raises NODATAFOUND, and a handler in the same block catches it without calling ROLLBACK. Is the UPDATE undone?
Show answer
No. The handler caught the error, so the block continues normally and the UPDATE stays part of the session's open transaction. It is only undone if the code, or the caller, later issues a ROLLBACK.