Skip to content

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:

  1. Semicolons: Every statement inside the block must end with a ;.
  2. The Forward Slash /: In tools like SQL*Plus or SQL Developer, you must put a / on a new line after END; 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.


πŸ“ˆ Learning Path