Loops
The LOOP construct allows you to execute a sequence of statements repeatedly. There are three types of loops: simple (infinite), FOR, and WHILE.
You can use the EXIT statement to break out of the LOOP and pass control to the statement following the END LOOP. Use the CONTINUE statement (Oracle Database 11g), described later, to break out of the current loope iteration and pass control to the next loop iteration.
Simple Loop
LOOP
executable_statement(s)
END LOOP;
The simple loop should contain an EXIT or EXIT WHEN unless you want it 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;
Numeric FOR Loop
FORloop_index
IN [REVERSE]lowest_number..highest_number
LOOPexecutable_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, this code:
BEGIN FOR counter IN 1 .. 4 LOOP DBMS_OUTPUT.PUT(counter); END LOOP; DBMS_OUTPUT.NEW_LINE; FOR counter IN REVERSE 1 .. 4 LOOP DBMS_OUTPUT.PUT(counter); END LOOP; DBMS_OUTPUT.NEW_LINE; END;
yields the following ...
Get Oracle PL/SQL Language Pocket Reference, 4th Edition 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.