In Oracle PL/SQL, a WHILE LOOP is used to execute a block of code repeatedly as long as a certain condition is true. The syntax for a WHILE LOOP is as follows:
WHILE condition LOOP -- code to be executed END LOOP;
The condition is a Boolean expression that is evaluated before each iteration of the loop. If the condition is true, the code inside the loop is executed; if the condition is false, the loop is terminated and control is passed to the next statement after the loop.
For example, the following code uses a WHILE LOOP to print the numbers from 1 to 10:
DECLARE i INTEGER := 1; BEGIN WHILE i <= 10 LOOP DBMS_OUTPUT.PUT_LINE(i); i := i + 1; END LOOP; END;
In this example, the variable i is initialized to 1, and the loop continues to execute as long as the value of i is less than or equal to 10. The value of i is incremented by 1 on each iteration of the loop.
It's important to take care when using a WHILE LOOP, since if the condition is never false, the loop will continue indefinitely and may cause the program to hang. It's always a good practice to include a way to exit the loop, for example, by incrementing or decrementing a variable in the body of the loop, or by using an EXIT WHEN statement.
It's also important to keep in mind that the condition is evaluated before the code inside the loop is executed, so if the condition is false to begin with, the loop will not execute at all.
WHILE LOOP example
DECLARE v_num NUMBER:=0; BEGIN WHILE v_num < 3 LOOP v_num:=v_num+1; DBMS_OUTPUT.put_line(v_num); END LOOP; END;
Output:
1
2
3