A WHILE loop in Oracle PL/SQL is used to repeatedly execute a block of statements as long as a given condition is true. The syntax for a WHILE loop is as follows:
The condition is a boolean expression that is evaluated before each iteration of the loop. If the condition is true, the statements inside the loop are executed and the condition is evaluated again. If the condition is false, the loop exits and execution continues with the next statement after the loop.
It is important to include a way to change the value of the condition within the loop, otherwise, the loop will run indefinitely.
WHILE … LOOP syntax
WHILE condition LOOP --pl/sql statements END LOOP;
WHILE … LOOP example
This loop will execute the statements inside the loop as long as the value of i is less than 7. The loop will print the current value of i and then increment i by 1 each iteration until i is no longer less than 7.
DECLARE i NUMBER:=0; BEGIN DBMS_OUTPUT.PUT_LINE('Start'); WHILE i < 7 LOOP i:=i+1; DBMS_OUTPUT.PUT_LINE(' i: ' || i); END LOOP; DBMS_OUTPUT.PUT_LINE('End'); END;
Output
Start i: 1 i: 2 i: 3 i: 4 i: 5 i: 6 i: 7 End