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:
1. No Jumping In: You cannot jump from outside into an IF statement or a LOOP.
2. No Jumping Out: You cannot jump from an EXCEPTION handler back into the main BEGIN block.
3. 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: GOTO makes it hard to track the flow of data. If you have 10 labels jumping around, debugging becomes a nightmare.
- Tip: Only use GOTO if it significantly simplifies a very complex piece of logic that nothing else can solve.