Loop statement In PL SQL

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,

Syntax of basic LOOP statement 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.

An Example using simple LOOP statement is given below

SET SERVEROUTPUT ON

BEGIN

LOOP

DBMS_OUTPUT.PUT_LINE(‘This is an infinite Loop!’);

END LOOP;

END;
/

This is an infinite loop. At no point did we tell the loop if/when/how to exit. While the syntax is valid, the logic is not.
To resolve this dilemma, PL/SQL uses EXIT statement.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.

Read more about EXIT Statement in PL SQL

EXIT-WHEN

The EXIT-WHEN statement allows a loop to complete conditionally. When the EXIT statement is encountered, the condition in the WHEN clause is evaluated. If the condition yields TRUE, the loop completes and control passes to the next statement after the loop.

Read more about EXIT-WHEN Statement in PL SQL

No comments

There are still no comments on this article.

Leave your comment...

If you want to leave your comment on this article, simply fill out the next form:




CAPTCHA Image CAPTCHA Audio
Refresh Image

You can use these XHTML tags: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong> .