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¶
graph TD
A[DECLARE: Set up tools π οΈ <br/>Optional] --> B[BEGIN: Start work βοΈ <br/>Mandatory]
B --> C{Success?}
C -- Yes --> D[END: Finished! β
<br/>Mandatory]
C -- No --> E[EXCEPTION: Handle Error πΈοΈ <br/>Optional]
E --> D
π» 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.