Loops
The LOOP construct allows you to repeatedly execute a sequence of statements. There are three kind of loops: simple, WHILE, and FOR.
Use the EXIT statement to break out of LOOP and pass control to the statement following the END LOOP.
The Simple Loop
The syntax for a simple loop is:
LOOP executable_statement(s) END LOOP;
The simple loop should contain an EXIT or EXIT WHEN statement so as not to execute infinitely. Use the simple loop when you want the body of the loop to execute at least once.
For example:
LOOP FETCH company_cur INTO company_rec; EXIT WHEN company_cur%ROWCOUNT > 5 OR company_cur%NOTFOUND; process_company(company_cur); END LOOP;
The Numeric FOR Loop
The syntax for a numeric FOR loop is:
FOR loop_index IN [REVERSE] lowest_number.. highest_number LOOP executable_statement(s) END LOOP;
The PL/SQL runtime engine automatically declares the loop index a PLS_INTEGER variable; never declare a variable with that name yourself. The lowest_number and highest_number ranges can be variables, but are evaluated only once—on initial entry into the loop. The REVERSE keyword causes PL/SQL to start with the highest_number and decrement down to the lowest_number. For example:
BEGIN DBMS_OUTPUT.PUT_LINE('Beginning Forward'); FOR counter IN 1 .. 4 LOOP DBMS_OUTPUT.PUT_LINE('counter='||counter); END LOOP; DBMS_OUTPUT.PUT_LINE('Beginning REVERSE'); FOR counter IN REVERSE 1 .. 4 LOOP DBMS_OUTPUT.PUT_LINE('counter='||counter); END LOOP; END;
The Cursor FOR Loop
The syntax for a cursor FOR loop ...
Get Oracle PL/SQL Language Pocket Reference now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.