Sub topic 12
Skipping Iterations and Leaving Nested Loops: CONTINUE and Labels
This chapter assumes you can declare variables, write anonymous PL/SQL blocks, and use IF, LOOP, and numeric FOR loops. The key distinction is that CONTINUE skips work in the current iteration, while EXIT ends a loop.
Skipping the Rest of an Iteration
CONTINUE stops the current iteration and starts the next iteration of the same loop. Statements after CONTINUE do not run during that iteration.
Use CONTINUE WHEN when the skip condition is simple:
BEGIN
FOR i IN 1..5 LOOP
CONTINUE WHEN MOD(i, 2) = 0;
DBMS_OUTPUT.PUT_LINE('Odd number: ' || i);
END LOOP;
END;
/The loop reaches CONTINUE for 2 and 4, so it prints only 1, 3, and 5.
A common error is using CONTINUE when you need to stop the loop completely. Use EXIT for that:
CONTINUEskips the rest of one iteration.EXITleaves the current loop.EXIT WHENleaves the loop only when its condition is true.
Labels and Nested Loops
A loop label is an identifier written before a loop and enclosed in double angle brackets. Repeat the label after END LOOP:
<<outer_loop>>
FOR i IN 1..3 LOOP
-- loop body
END LOOP outer_loop;Labels make nested-loop control explicit. Without a label, EXIT and CONTINUE apply to the innermost loop containing the statement. With a label, they can target an enclosing loop.
BEGIN
<<day_loop>>
FOR day_no IN 1..3 LOOP
FOR shift_no IN 1..3 LOOP
CONTINUE WHEN shift_no = 2;
-- Skip the remaining shifts for day 2.
CONTINUE day_loop WHEN day_no = 2 AND shift_no = 1;
-- Leave both loops at the end of day 3.
EXIT day_loop WHEN day_no = 3 AND shift_no = 3;
DBMS_OUTPUT.PUT_LINE(
'Day ' || day_no || ', shift ' || shift_no
);
END LOOP;
END LOOP day_loop;
END;
/The unlabeled CONTINUE WHEN shift_no = 2 affects only the inner loop. The labeled CONTINUE day_loop abandons the inner loop and starts the next iteration of the outer loop. The labeled EXIT day_loop leaves both loops.
A label must identify a loop in the current block. Keep labels descriptive, especially when several loops are nested.
Exercise
In a nested loop, which statement skips the remaining inner-loop work and starts the next iteration of the outer loop?
Show answer
Use CONTINUE outerloop, where outerloop is the label of the enclosing loop.