0% found this document useful (0 votes)
8 views11 pages

Unit 2 LECTURE 3.2 (Iterative Control Structure)

This document discusses iterative control structures in PL/SQL, specifically focusing on LOOP, WHILE-LOOP, and FOR-LOOP statements. It explains the syntax and usage of these loops, including how to use EXIT and EXIT-WHEN statements to control loop execution. Additionally, it provides examples to illustrate the concepts and their applications in programming.

Uploaded by

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

Unit 2 LECTURE 3.2 (Iterative Control Structure)

This document discusses iterative control structures in PL/SQL, specifically focusing on LOOP, WHILE-LOOP, and FOR-LOOP statements. It explains the syntax and usage of these loops, including how to use EXIT and EXIT-WHEN statements to control loop execution. Additionally, it provides examples to illustrate the concepts and their applications in programming.

Uploaded by

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

UNIT 2

CHAPTER 2.3
LECTURE 3.2( Iterative Control Structure)

Iterative Control: LOOPING Statements

LOOP statements let you execute a sequence of statements multiple times. There are three
forms of LOOP statements: LOOP, WHILE-LOOP, and FOR-LOOP.

LOOP

The simplest form of LOOP statement is the basic (or infinite) loop, which encloses a
sequence of statements between the keywords LOOP and END LOOP, as follows:

LOOP

sequence_of_statements

END LOOP;

With each iteration of the loop, the sequence of statements is executed, then control resumes
at the top of the loop. If further processing is undesirable or impossible, you can use
an EXIT statement to complete the loop. You can place one or more EXIT statements
anywhere inside a loop, but nowhere outside a loop. There are two forms
of EXIT statements: EXIT and EXIT-WHEN.

EXIT

The EXIT statement forces a loop to complete unconditionally. When an EXIT statement is
encountered, the loop completes immediately and control passes to the next statement. An
example follows:

LOOP

...

IF credit_rating < 3 THEN

...

EXIT; -- exit loop immediately

END IF;
END LOOP;

-- control resumes here

The next example shows that you cannot use the EXIT statement to complete a PL/SQL
block:

BEGIN

...

IF credit_rating < 3 THEN

...

EXIT; -- not allowed

END IF;

END;

Remember, the EXIT statement must be placed inside a loop. To complete a PL/SQL block
before its normal end is reached, you can use the RETURN statement.

EXIT-WHEN

The EXIT-WHEN statement lets a loop complete conditionally. When the EXIT statement is
encountered, the condition in the WHEN clause is evaluated. If the condition is true, the loop
completes and control passes to the next statement after the loop. An example follows:

LOOP

FETCH c1 INTO ...

EXIT WHEN c1%NOTFOUND; -- exit loop if condition is true

...

END LOOP;

CLOSE c1;

Until the condition is true, the loop cannot complete. So, a statement inside the loop must
change the value of the condition. In the last example, if the FETCH statement returns a row,
the condition is false. When the FETCH statement fails to return a row, the condition is true,
the loop completes, and control passes to the CLOSE statement.
The EXIT-WHEN statement replaces a simple IF statement. For example, compare the
following statements:

IF count > 100 THEN | EXIT WHEN count > 100;

EXIT;

END IF;

These statements are logically equivalent, but the EXIT-WHEN statement is easier to read
and understand.

Loop Labels

Like PL/SQL blocks, loops can be labeled. The label, an undeclared identifier enclosed by
double angle brackets, must appear at the beginning of the LOOP statement, as follows:

<<label_name>>

LOOP

sequence_of_statements

END LOOP;

Optionally, the label name can also appear at the end of the LOOP statement, as the following
example shows:

<<my_loop>>

LOOP

...

END LOOP my_loop;

When you nest labeled loops, use ending label names to improve readability.

With either form of EXIT statement, you can complete not only the current loop, but any
enclosing loop. Simply label the enclosing loop that you want to complete. Then, use the
label in an EXIT statement, as follows:

<<outer>>

LOOP

...
LOOP

...

EXIT outer WHEN ... -- exit both loops

END LOOP;

...

END LOOP outer;

Every enclosing loop up to and including the labeled loop is exited.

WHILE-LOOP

The WHILE-LOOP statement associates a condition with a sequence of statements enclosed


by the keywords LOOP and END LOOP, as follows:

WHILE condition LOOP

sequence_of_statements

END LOOP;

Before each iteration of the loop, the condition is evaluated. If the condition is true, the
sequence of statements is executed, then control resumes at the top of the loop. If the
condition is false or null, the loop is bypassed and control passes to the next statement. An
example follows:

WHILE total <= 25000 LOOP

...

SELECT sal INTO salary FROM emp WHERE ...

total := total + salary;

END LOOP;

The number of iterations depends on the condition and is unknown until the loop completes.
The condition is tested at the top of the loop, so the sequence might execute zero times. In the
last example, if the initial value of total is larger than 25000, the condition is false and the
loop is bypassed.

Some languages have a LOOP UNTIL or REPEAT UNTIL structure, which tests the
condition at the bottom of the loop instead of at the top. Therefore, the sequence of
statements is executed at least once. PL/SQL has no such structure, but you can easily build
one, as follows:

LOOP

sequence_of_statements

EXIT WHEN boolean_expression;

END LOOP;

To ensure that a WHILE loop executes at least once, use an initialized Boolean variable in
the condition, as follows:

done := FALSE;

WHILE NOT done LOOP

sequence_of_statements

done := boolean_expression;

END LOOP;

A statement inside the loop must assign a new value to the Boolean variable. Otherwise, you
have an infinite loop. For example, the following LOOP statements are logically equivalent:

WHILE TRUE LOOP | LOOP

... | ...

END LOOP; | END LOOP;

WHILE loop

The while loop executes commands in its body as long as the condtion remains true

Syntax :

WHILE < condition >

LOOP

< Action >

END LOOP

Example 1 : Find reverse of given number using while loop

DECLARE
num Number(3) :=123;

ans Number(3) :=0;

i Number(3) :=0;

BEGIN

WHILE num != 0

LOOP

i:=mod(num,10);

ans:=(ans * 10 ) + i;

num:=floor(num/10);

END LOOP;

dbms_output.put_line('reverse of given number is: ' || ans);

END;

Output :

Run SQL Command Line

SQL>set serveroutput on

SQL>start d://rev.sql

reverse of given number is: 321

PL/SQL successfully completed.

Example 2:Write a program in PL/SQL to print the value of a variable inside and
outside a loop using LOOP EXIT statement.

DECLARE

n NUMBER := 0;
BEGIN

LOOP

DBMS_OUTPUT.PUT_LINE ('The value of n inside the loop is: ' || TO_CHAR(n));

n := n + 1;

IF n > 5 THEN

EXIT;

END IF;

END LOOP;

DBMS_OUTPUT.PUT_LINE('The value of n outside the loop is: ' || TO_CHAR(n));

END;

Sample Output:

SQL> /

The value of n inside the loop is: 0

The value of n inside the loop is: 1

The value of n inside the loop is: 2

The value of n inside the loop is: 3

The value of n inside the loop is: 4

The value of n inside the loop is: 5

The value of n outside the loop is: 6

PL/SQL procedure successfully completed.

FOR-LOOP

Whereas the number of iterations through a WHILE loop is unknown until the loop
completes, the number of iterations through a FOR loop is known before the loop is
entered. FOR loops iterate over a specified range of integers. The range is part of an iteration
scheme, which is enclosed by the keywords FOR and LOOP. A double dot (..) serves as the
range operator. The syntax follows:

FOR counter IN [REVERSE] lower_bound..higher_bound LOOP

sequence_of_statements

END LOOP;

The range is evaluated when the FOR loop is first entered and is never re-evaluated.

As the next example shows, the sequence of statements is executed once for each integer in
the range. After each iteration, the loop counter is incremented.

FOR i IN 1..3 LOOP -- assign the values 1,2,3 to i

sequence_of_statements -- executes three times

END LOOP;

The following example shows that if the lower bound equals the higher bound, the sequence
of statements is executed once:

FOR i IN 3..3 LOOP -- assign the value 3 to i

sequence_of_statements -- executes one time

END LOOP;

By default, iteration proceeds upward from the lower bound to the higher bound. However, as
the example below shows, if you use the keyword REVERSE, iteration proceeds downward
from the higher bound to the lower bound. After each iteration, the loop counter is
decremented. Nevertheless, you write the range bounds in ascending (not descending) order.

FOR i IN REVERSE 1..3 LOOP -- assign the values 3,2,1 to i

sequence_of_statements -- executes three times

END LOOP;

Inside a FOR loop, the loop counter can be referenced like a constant but cannot be assigned
values, as the following example shows:

FOR ctr IN 1..10 LOOP

IF NOT finished THEN


INSERT INTO ... VALUES (ctr, ...); -- legal

factor := ctr * 2; -- legal

ELSE

ctr := 10; -- not allowed

END IF;

END LOOP;

Using the FOR-LOOP Statement

Simple FOR loops iterate over a specified range of integers. The number of iterations is
known before the loop is entered. A double dot (..) serves as the range operator. The range is
evaluated when the FOR loop is first entered and is never re-evaluated. If the lower bound
equals the higher bound, the loop body is executed once.

Example 1: Using a Simple FOR LOOP Statement

DECLARE

p NUMBER := 0;

BEGIN

FOR k IN 1..500 LOOP -- calculate pi with 500 terms

p := p + ( ( (-1) ** (k + 1) ) / ((2 * k) - 1) );

END LOOP;

p := 4 * p;

DBMS_OUTPUT.PUT_LINE( 'pi is approximately : ' || p ); -- print result

END;

Example 2: Write a program in PL/SQL to print 1st n numbers with a difference of 3


and starting from 1.

DECLARE

n number:= &first_n_number;

i number:=1;
m number:=1;

BEGIN

DBMS_OUTPUT.PUT_LINE ('The first '||n||' numbers are: ');

DBMS_OUTPUT.PUT (i||' ');

for i in 1..n-1 loop

m:=m+3;

dbms_output.put(m||' ');

END LOOP;

dbms_output.new_line;

END;

Sample Output:

Enter value for first_n_number: 10

old 2: n number:= &first_n_number;

new 2: n number:= 10;

The first 10 numbers are:

1 4 7 10 13 16 19 22 25 28

PL/SQL procedure successfully completed.


Other References

• PL/SQL Control Statement Exercises with Solution - w3resource

• Control Structures | DBMS | Tutorialink.com

• PL/SQL Control Structures - Oracle PL/SQL Tutorial | Intellipaat.com

Suggested References

 C.J.Date, “An Introduction to DatabaseSystems”, Addison Wesley.

 Thomas M. Connolly, Carolyn & E.Begg,“Database Systems: A Practical Approach


to Design, Implementationand Management”, 5/E, University of Paisley, Addison-
Wesley.

 Rob,”Database Principal Fundamental Design, Cengage Learning.

You might also like