PL/SQL Basic LOOP πΒΆ
Prerequisites: PL/SQL Basics
Mentor's Note: A loop is like a Hamster Wheel. You keep running until you've reached your goal. The "Basic Loop" is the simplest type: it runs forever until you explicitly tell it to STOP. π‘
π The Scenario: The Repetitive Task π οΈΒΆ
Imagine you are stamping 100 letters. - Action: Pick a letter -> Stamp it -> Check if you are done. - Loop: Keep repeating the action. - Exit: Stop once you have stamped the 100th letter. β
π» 1. The Basic SyntaxΒΆ
A basic loop starts with LOOP and ends with END LOOP;.
DECLARE
v_counter NUMBER := 1;
BEGIN
LOOP
DBMS_OUTPUT.PUT_LINE('Iteration: ' || v_counter);
v_counter := v_counter + 1;
-- π The Exit Strategy (Mandatory to avoid infinite loop!)
IF v_counter > 5 THEN
EXIT;
END IF;
END LOOP;
END;
π» 2. The EXIT WHEN Clause (Shorthand)ΒΆ
A cleaner way to write the exit condition.
DECLARE
v_counter NUMBER := 1;
BEGIN
LOOP
DBMS_OUTPUT.PUT_LINE('Counter: ' || v_counter);
v_counter := v_counter + 1;
EXIT WHEN v_counter > 5; -- β
Much more readable!
END LOOP;
END;
ποΈ Architect's Note: The Infinite Loop Danger π‘οΈΒΆ
If you forget to increment your counter or provide an EXIT condition, the loop will run until it crashes the session or uses up all the CPU.
- Tip: Always double-check your exit condition. If your program seems to "hang" when you run it, you probably have an infinite loop!
π¨ Visual Logic: The Loop CycleΒΆ
graph TD
A[Start Loop] --> B[Execute Task]
B --> C{Exit Condition Met?}
C -- No --> B
C -- Yes --> D[End Loop]