3-9. Iterating a Fixed Number of Times

Problem

You are interested in executing the contents of a loop a specified number of times. For example, you are interested in executing a loop ten times, and you need to number each line of output in the range by the current loop index.

Solution

Write a FOR loop. Use a variable to store the current index of the loop while looping through a range of numbers from one to ten in ascending order. The following lines of code will iterate ten times through a loop and print out the current index in each pass:

BEGIN   FOR idx IN 1..10 LOOP     DBMS_OUTPUT.PUT_LINE('The current index is: ' || idx);   END LOOP; END;

Here is the result:

The current index is: 1 The current index is: 2 The current index is: 3 The ...

Get Oracle and PL/SQL Recipes: A Problem-Solution Approach 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.