Sub topic 2
Anonymous blocks and named blocks
Every piece of PL/SQL code lives in a block. Blocks come in two kinds: those with a name that the database stores, and those without a name that run once. This chapter explains the difference, shows how to write and run both, and covers the edge cases that trip people up.
This chapter assumes you can run SQL statements in SQL*Plus, SQL Developer, or SQLcl, and that you know the basic block layout (DECLARE, BEGIN, EXCEPTION, END) from the earlier chapter on block anatomy. Some examples use the HR sample schema.
Two kinds of blocks
A PL/SQL block is a unit of code with an optional declaration section, a required executable section, and an optional exception section. What differs between block kinds is how the block is identified and where it lives.
- An anonymous block has no name. You send it to the database, the database compiles and runs it, and nothing is kept afterward.
- A named block has a name and is stored in the database as a schema object. You create it once and call it by name any number of times. Procedures, functions, packages, and triggers are named blocks.
Anonymous blocks
An anonymous block begins with DECLARE (or directly with BEGIN if it needs no declarations) and ends with END;. In SQL*Plus and SQLcl, a line containing only / after the block tells the client to send it to the database.
SET SERVEROUTPUT ON
DECLARE
v_count NUMBER;
BEGIN
SELECT COUNT(*) INTO v_count FROM employees;
DBMS_OUTPUT.PUT_LINE('Employees: ' || v_count);
END;
/Anonymous blocks suit one-off work: testing a snippet, running a data fix, or calling stored programs in a script. They also act as the driver for stored code, since you can only call a procedure from PL/SQL or from a few client commands.
Three rules apply to any anonymous block.
- The executable section must contain at least one statement. If you need a placeholder, use the
NULL;statement. - The declaration and exception sections are optional. A block can be as small as
BEGIN NULL; END;. - Each
DECLARE ... END;ends with a semicolon. The/is a client command, not part of PL/SQL.
BEGIN
NULL;
END;
/Limits of anonymous blocks
Because nothing is stored, an anonymous block cannot be called from another block, from a SQL statement, or by another user. The database parses it each time you submit it, so the text is not available later from the data dictionary. If you want to reuse one, save the text in a script file and run it with @filename in SQL*Plus or SQLcl.
Another consequence is that an anonymous block cannot return a value to a caller the way a function does. It can print output, change data, or set bind variables, but it has no return value of its own.
Named blocks
A named block starts with a header that gives its kind and name. The CREATE statement stores it in your schema. A header replaces the DECLARE keyword: the declaration section starts right after IS or AS.
A procedure
A procedure performs an action. It can take parameters but does not return a value through its name.
SET SERVEROUTPUT ON
CREATE OR REPLACE PROCEDURE greet (p_name IN VARCHAR2) IS
v_message VARCHAR2(100);
BEGIN
v_message := 'Hello, ' || p_name;
DBMS_OUTPUT.PUT_LINE(v_message);
END greet;
/Here p_name is a parameter. IN means the caller supplies the value and the procedure cannot change it. The IS keyword marks the start of the declaration section, where v_message is declared. Writing the name after END (END greet;) is optional, but it helps readers match the end to the beginning in long programs.
You call a procedure from an anonymous block:
BEGIN
greet('Ada');
END;
/In SQL*Plus and SQLcl you can also use the EXECUTE command, which wraps your call in an anonymous block for you:
EXECUTE greet('Ada')A function
A function computes and returns exactly one value. Because of that, you can use it inside an expression, and often inside a SQL statement.
CREATE OR REPLACE FUNCTION price_with_tax (
p_price IN NUMBER,
p_rate IN NUMBER DEFAULT 0.075
) RETURN NUMBER IS
BEGIN
RETURN ROUND(p_price * (1 + p_rate), 2);
END price_with_tax;
/
SELECT price_with_tax(100) AS total FROM dual;The query returns 107.5. The DEFAULT clause on p_rate lets callers leave that argument out. Every path through a function body must end in a RETURN, or the function raises an error at run time.
Packages and triggers
Two other named blocks matter later in the course.
- A package groups related procedures, functions, and variables under one name. It has a specification (the public interface) and a body (the code).
- A trigger is a named block that the database runs automatically when a table event happens, such as an
INSERT.
Both use the same section layout you already know. Only the header differs.
How the database treats each kind
When you run CREATE OR REPLACE PROCEDURE, the database checks the syntax, resolves the names it refers to, and stores both the source text and the compiled form. You can inspect what is stored:
SELECT object_name, object_type, status
FROM user_objects
WHERE object_name IN ('GREET', 'PRICE_WITH_TAX');
SELECT line, text
FROM user_source
WHERE name = 'GREET'
ORDER BY line;USER_OBJECTS shows the object type and a STATUS of VALID or INVALID. USER_SOURCE holds the text, one row per line. Anonymous blocks never appear in either view.
The table summarizes the practical differences.
| Feature | Anonymous block | Named block |
|---|---|---|
| Has a name | No | Yes |
| Stored in the database | No | Yes, as a schema object |
| Compiled | Each time it is submitted | When created or replaced |
| Can take parameters | No (use bind variables) | Yes |
| Can be called from other code | No | Yes |
| Can return a value | No | Functions only |
| Section opens with | `DECLARE` | `IS` or `AS` after the header |
| Privileges | Runs with your own rights | Granted with `GRANT EXECUTE` |
Compile errors
If a named block has a syntax error, CREATE still succeeds in most client tools but reports "created with compilation errors", and the object is INVALID. Calling an invalid object fails. In SQL*Plus and SQLcl, run SHOW ERRORS right after the CREATE statement to see the line and message. In other tools, query USER_ERRORS:
SELECT line, position, text
FROM user_errors
WHERE name = 'GREET'
ORDER BY sequence;An anonymous block reports its errors immediately when you submit it, since it is compiled on the spot.
Blocks inside blocks
Named blocks can appear inside other blocks. A procedure or function declared in the declaration section of an anonymous block is a local subprogram. It has a name, but it exists only while the enclosing block runs.
SET SERVEROUTPUT ON
DECLARE
PROCEDURE say (p_text IN VARCHAR2) IS
BEGIN
DBMS_OUTPUT.PUT_LINE('>> ' || p_text);
END say;
BEGIN
say('first');
say('second');
END;
/The output is >> first and >> second. After the block ends, say is gone. Local subprograms are useful for repeated logic in a one-off script. They go at the end of the declaration section, after all variables.
A block can also carry a label in double angle brackets, such as <<main>> placed before DECLARE or BEGIN. A label is a way to refer to a block by name, for example to qualify a variable in a nested block. It does not make the block named in the stored sense. The block is still anonymous. Labels return in the chapter on nested scope.
Choosing between them
Use an anonymous block when the code runs once, when you are experimenting, or when you need a small driver to call stored code. Use a named block when the logic will be reused, called by applications, secured with GRANT EXECUTE, or tested and versioned as part of the schema.
A common development pattern is to prototype in an anonymous block, then move the working code into a procedure by replacing DECLARE with a header and IS. Local variables carry over unchanged. Values you hard-coded in the declarations usually become parameters.
Common mistakes
- Putting
DECLAREin a procedure body. A named block usesISorASinstead. Writing both causes a compile error. - Leaving out the
/after a block in a script, so the following statements are swallowed into the block text. - Forgetting
SET SERVEROUTPUT ON. The block runs, butDBMS_OUTPUTtext is not shown. - Giving a parameter the same name as a column. Inside a SQL statement in the block, the column wins, which produces silent wrong results such as
WHERE employee_id = employee_id. Ap_prefix on parameters avoids this. - Declaring a local subprogram before the variables. Variables and constants must come first.
Exercise
You run a block that starts with DECLARE and ends with END; followed by a line containing /. A colleague asks you to run the same logic again tomorrow without retyping it, and to let another schema owner run it. Which kind of block should you convert it to, and what do you change in the first lines?
Show answer
Convert it to a named block, for example a procedure. Replace DECLARE with a header such as CREATE OR REPLACE PROCEDURE dowork IS, keep the declarations after IS, and keep BEGIN ... END dowork; followed by / on its own line. Values you hard-coded can become parameters. The colleague then runs it with GRANT EXECUTE ON dowork TO theiruser, and calls it with dowork; inside a block or EXECUTE dowork.
Exercise
After running CREATE OR REPLACE FUNCTION with a typo, the client says "created with compilation errors". Name two ways to find the error and say what STATUS the function has in USER_OBJECTS.
Show answer
Run SHOW ERRORS immediately in SQL*Plus or SQLcl, or query USERERRORS (WHERE name = 'FUNCTIONNAME' ORDER BY sequence) from any tool. The function exists in USER_OBJECTS with STATUS = 'INVALID', and calling it fails until you fix the code and recreate it.