EXIT-WHEN statement in PL SQL
The EXIT-WHEN statement allows a loop to complete conditionally. When the EXIT statement is encountered, the condition in the WHEN clause is evaluated.
If the condition yields TRUE, the loop completes and control passes to the next statement after the loop.
An Example follows:
LOOP
FETCH cursor_c1 INTO …
EXIT WHEN cursor_c1%NOTFOUND;
— exit loop if condition is true
…
END LOOP;
CLOSE cursor_c1
Until the condition yields TRUE, the loop cannot complete. So, statements within the loop must change the value of the condition. In the last example, if the FETCH statement returns a row, the condition yields FALSE.
When the FETCH statement fails to return a row, the condition yields TRUE, the loop completes, and control passes to the CLOSE statement.
The EXIT-WHEN statement replaces a simple IF statement. For example, compare the following statements:
IF sal > 10000 THEN
END IF;
EXIT WHEN sal > 10000;
These statements are logically equivalent, but the EXIT-WHEN statement is easier to read and understand.