PL/SQL Anonymous Block 🏗️
Mentor's Note: A PL/SQL "Block" is the basic unit of code. It's like a container. An Anonymous Block is a one-time script that isn't saved in the database. It's perfect for testing or simple automation. 💡
🌟 The Scenario: The Recipe Card 📝
Imagine you are writing a recipe on a sticky note.
- Header: You list your ingredients (DECLARE). 🥣
- Body: You write the step-by-step cooking instructions (BEGIN). 🍳
- Footer: You write what to do if the cake burns (EXCEPTION). 🧯
- End: You mark the card as finished.
🎨 Visual Logic: The Block Blueprint
💻 1. The Structure
| Section | Keyword | Purpose |
|---|---|---|
| Declaration | DECLARE | Define variables and constants. |
| Execution | BEGIN | The actual logic and SQL commands. |
| Exception | EXCEPTION | Handle errors gracefully. |
| End | END; | Marks the end of the block. |
💻 2. Basic Example
SET SERVEROUTPUT ON; -- 💡 MANDATORY to see output!
DECLARE
v_message VARCHAR2(50) := 'Hello PL/SQL';
BEGIN
DBMS_OUTPUT.PUT_LINE(v_message);
EXCEPTION
WHEN OTHERS THEN
DBMS_OUTPUT.PUT_LINE('Something went wrong!');
END;
/
🗝️ Key Syntax Notes:
- Semicolons: Every statement inside the block must end with a
;. - The Forward Slash
/: In tools like SQL*Plus or SQL Developer, you must put a/on a new line afterEND;to tell Oracle to "Execute this block now."
🏗️ Architect's Note: Scope & Nesting 🛡️
You can nest blocks inside other blocks!
- Scope: Variables declared in the outer block are visible to the inner block.
- Isolation: Variables in the inner block are hidden from the outer block.
- Tip: Use nesting to isolate risky logic inside its own EXCEPTION handler without stopping the main program.