While loop Oracle

While loop is an another looping structure. It is also called conditional loop. It evaluates the condition before each iteration executes. While loop is effective when how number of iterations are not known prior to the execution.

Syntax:-

while condition
loop
—- your code here
end loop;

Examples :-

1) Print all odd numbers less than 10

SQL> set serveroutput on
SQL> declare
2 n integer;
3 begin
4 n := 1;
5 while n <= 10 loop
6 dbms_output.put_line(n);
7 n := n + 2;
8 end loop;
9 end;
10 /
1
3
5
7
9

PL/SQL procedure successfully completed.

Note that if we omit the condition n := n + 2 then while loop will fall in infinite loop.

So always be cautious when constructing a while loop.

Read also – For loop , goto statement

Advertisements