Ticker

6/recent/ticker-posts

PL/SQL Control Statements: Iterative Control Statements in PL/SQL

Iterative Control Statements

 Iterative Control Statements

Iterative control statements enable you to execute sequence statements multiple times. The simplest form of an iterative statement in the loop.

The iterative control statements are as follows:

1) Loop Statements: The syntax of the loop statement is as shown below.

Syntax:

LOOP

statements(s)

END LOOP;

Each time the loop is processed, control is always resumed at the top of the loop structure and statements are executed. The EXIT statement provides a way to stop the iterative loop. The EXIT statement must be placed inside the loop.

For example,

BEGIN

LOOP

count = count +1

IF count >=14 THEN

EXIT;

END IF;

END LOOP;

END;  

2) F0R LOOP Statements: The FOR LOOP is a mechanism to cycle through a loop fixed number of times. A FOR LOOP iterates over and over for a specified number of times.

Syntax:

FOR counter IN lower bound .. upper bound LOOP

statement(s)

END LOOP;

The range of valid integers for the counter is evaluated when the loop is first entered and is never re-evaluated. After each iteration, the counter is implicitly incremented. Also the counter is implicitly declared, so you do not have to declare it. If the upper bound value is less than the lower bound value the loop is never executed.

For example, following loop the statements will be executed 30 times:

FOR k IN 1..30

LOOP

Statements

END LOOP;

3) LOOP Labels: In PUSQL, you may attach a label name to a loop. This label, which is an undeclared identifier, must appear at the beginning of the loop and must De enC IUS Optionally this label may be placed at the without angle brackets.

For example, using labels to clearly mark the beginning and of the looping structure:

« salary_loop>> -- loop label

FOR k IN 1..u_counter LOOP

UPDATE employee

SET salary = salary * 1.1;

END LOOP inventory_loop;

4) WHILE Statements: The WHILE-LOOP structure repeats a statement until a condition is no longer true.

Syntax:

WHILE condition LOOP

statement(s)

END LOOP;

Before each iteration the condition is evaluated. If the condition is True, the statements are executed. Otherwise the statements are skipped and not executed.

For example,

DECLARE

counter NUMBER(2) : =1;

BEGIN

WHILE counter >20 LOOP

SELECT name INTO guest_name

FROM register

counter = counter +1 ;

END LOOP:

END: