PL/SQL GOTO & Labels ‴οΈ
Mentor's Note:
GOTOis the "Teleportation" command of PL/SQL. It lets you jump from one part of the code directly to another. But be warned: too much teleporting makes your code very confusingβthis is known as "Spaghetti Code". π π‘
π The Scenario: The Emergency Exit πͺβ
Imagine you are walking through a maze.
- Usually, you follow the paths (IF, Loops).
- GOTO: You see an "Emergency Exit" sign and jump straight out of the maze to the finish line, skipping everything else.
π» 1. Basic Syntaxβ
You must define a Label using double angle brackets << >>.
DECLARE
v_num NUMBER := 1;
BEGIN
IF v_num = 1 THEN
GOTO my_shortcut; -- π Jump to label
END IF;
DBMS_OUTPUT.PUT_LINE('This line will be skipped!');
<<my_shortcut>> -- π The target label
DBMS_OUTPUT.PUT_LINE('We arrived at the shortcut!');
END;
π 2. Important Restrictions (Architect's Note)β
You cannot jump anywhere you want. There are strict rules:
- No Jumping In: You cannot jump from outside into an
IFstatement or aLOOP. - No Jumping Out: You cannot jump from an
EXCEPTIONhandler back into the mainBEGINblock. - Labels need code: A label must be followed by at least one executable statement (like
NULL;).
ποΈ Architect's Advice: Avoid GOTO π‘οΈβ
In 99% of cases, you can use IF, CASE, or LOOP instead of GOTO.
- The Problem:
GOTOmakes it hard to track the flow of data. If you have 10 labels jumping around, debugging becomes a nightmare. - Tip: Only use
GOTOif it significantly simplifies a very complex piece of logic that nothing else can solve.