In Oracle PL/SQL, the EXIT statement can be used to exit a loop early, before it completes its normal iteration. The EXIT statement can be used with a WHEN clause, which specifies a condition under which the loop should exit. The syntax for using the EXIT statement with a WHEN clause is as follows:
EXIT [WHEN boolean_expression];
EXIT WHEN example
For example, the following code uses a WHILE loop to iterate through a set of numbers, and exits the loop early if the number is equal to 5:
DECLARE v_num NUMBER:=0; BEGIN LOOP v_num:=v_num+1; DBMS_OUTPUT.put_line(v_num); EXIT WHEN v_num = 5 ; END LOOP; END;
In this example, the loop will only iterate 5 times and exit when i=5.
Output:
1
2
3
4
5
Similarly, you can use EXIT with FOR loop as well.
BEGIN FOR i in 1..10 LOOP EXIT WHEN i=5; DBMS_OUTPUT.PUT_LINE(i); END LOOP; END;
In this example, the loop will iterate from 1 to 4 and exit when i=5