0% found this document useful (0 votes)
18 views

Loops Examples

The document contains examples of using loops in PL/SQL including for loops, while loops, and using exit clauses. It shows how to iterate from 1 to 5 in ascending and descending order and examples of calculating sums of digits in a number using loops.

Uploaded by

Venu D
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
18 views

Loops Examples

The document contains examples of using loops in PL/SQL including for loops, while loops, and using exit clauses. It shows how to iterate from 1 to 5 in ascending and descending order and examples of calculating sums of digits in a number using loops.

Uploaded by

Venu D
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
You are on page 1/ 3

set serveroutput on

DECLARE --example of simple loop with exit when clause


no NUMBER := 1;
BEGIN
LOOP
DBMS_OUTPUT.PUT_LINE ( no);
no := no +1;
EXIT WHEN no>=10;
END LOOP;
END;
/

SQL> DECLARE
2 no NUMBER := 1;
3 BEGIN
4 LOOP
5 DBMS_OUTPUT.PUT_LINE ( no);
6 no := no +1;
7 IF no = 10 THEN --example of simple loop with exit clause
8 EXIT;
9 END IF;
10 END LOOP;
11 END;
12 /

/print 1 to 5 nos in asc


BEGIN
FOR no IN 1 .. 5 LOOP
DBMS_OUTPUT.PUT_LINE(no);
END LOOP;
END;
/

//print 1 to 5 nos in desc


BEGIN
FOR no IN reverse 1 .. 5 LOOP
DBMS_OUTPUT.PUT_LINE(no);
END LOOP;
END;

set serveroutput on
DECLARE
i NUMBER := 1;
n number:=&n;
BEGIN
LOOP
DBMS_OUTPUT.PUT_LINE (n||'*'||i||'='||n*i );
i := i +1;
EXIT WHEN i>10;
END LOOP;
END;
/
//print 1 to 5 nos
set serveroutput on
declare
i number:=1;
BEGIN
while i<=5 loop
DBMS_OUTPUT.PUT_LINE(i);
i:=i+1;
exit when i>5;
END LOOP;
END;

set serveroutput on
declare
n integer:=123;
r integer;
sum integer;
BEGIN
sum:=0;
while n<>0 loop
r:=mod(n,10);
sum:=sum + r;
n:=trunc(n/10);
END LOOP;
DBMS_OUTPUT.PUT_LINE('the sum='||sum);
END;

set serveroutput on
DECLARE
n INTEGER;
sum INTEGER;
r INTEGER;
temp_sum integer;
BEGIN
n := &n;
temp_sum := 0;
WHILE n <> 0 LOOP
r := MOD(n, 10);
temp_sum := temp_sum + r;
n := Trunc(n / 10);
END LOOP;
dbms_output.Put_line('sum of digits = '|| temp_sum);
END;
/
Enter value for n: 123
old 7: n := &n;
new 7: n := 123;
sum of digits = 6

PL/SQL procedure successfully completed.

to run with notepad use as follows

SQL> ed sample

SQL> @ F:\plsql_sample\sample.sql
welcome to first pl/sql programe

PL/SQL procedure successfully completed.

You might also like