PLSQL Loops

Loops

Loops:- Like other programming language we can use loops in PLSQL programming. There are 3 types of loop in PLSQL.

1) Simple Loop
2) While Loop
3) For Loop

Simple Loop:-

Syntax :-

loop
executable statement;
exit when ;
end loop;
 
loop
executable statement;
if then
exit;
end if;
end loop;
Note:- Exit condition is mandatory in Simple Loop otherwise program will run in infinite loop.

Example:-

declare
i number:=1;
begin
loop
dbms_output.put_line(i);
i:=i+1;
exit when i>10;
end loop;
end;
/

While Loop:-
 
Syntax:-
 
while (condition)
loop
executable statement;
end loop;
 
Example:-

declare
i number:=1;
begin
while (i<=10)
loop
dbms_output.put_line(i);
i:=i+1;
end loop;
end;
/

For Loop:- It is most popular loop in PLSQL as variable used for "for loop" that does not need to declare and there is no need to do manual increment.
 
Syntax :-
 
for i in start_number..end_number
loop
executable statement;
end loop;
 
Note:- Start_number should be less than end_number otherwise program will never print any result.
 
Example :-
begin
for i in 1..10 loop
dbms_output.put_line(i);
end loop;
end;
/

Reverse For Loop:- For decrement we use "reverse" keyword.

begin
for i in REVERSE 1..10 loop
dbms_output.put_line(i);
end loop;
end;
/

No comments:

Post a Comment