PL/SQL Basic Exit Loop

Sharing is Caring

In PL/SQL Basic Exit Loop all statements inside the block are executed at least once before loop termination, Basic loop encloses statement between LOOP and END LOOP and there must be an EXIT or EXIT-WHEN condition to terminate the loop. Loops are very important and most used part of any programming language as they are used to perform a recursive task efficiently. Next, In this post, you’ll learn about the basic syntax and usage of Pl-SQL exit loop.

The syntax of Basic Exit loop is like this, a set of statements are put in a loop (LOOP and END LOOP block and at each iteration those set of statements are executed) and a condition is set for terminating the loop statements.

LOOP

statements to execute

EXIT; or EXIT-WHEN

END LOOP;

See these examples for the better understanding of PL- SQL exit loop

PL-SQL EXIT Loop

DECLARE
--Counter Variable
i int:=0;
BEGIN
-- Start loop
LOOP
dbms_output.put_line('Value in loop is: '||i);
-- Increment Counter
i:=i+1;
-- Check condition
IF i>5 THEN
-- If true then exit
EXIT;
END IF;
END LOOP;
END;

and output is

PL/SQL Basic Exit Loop

 

PL/SQL EXIT WHEN Loop

An EXIT keyword is a sign of that control is coming out of the loop and EXIT WHEN keyword is used to break a LOOP on a certain condition. See an example below about using it

DECLARE
--Counter Variable
i int:=10;
BEGIN
-- Start loop
LOOP
dbms_output.put_line('Value in loop is: '||i);
-- Increment Counter
i:=i+1;
-- Check condition and exit
EXIT WHEN i>15;
END LOOP;
END;

and output on SQL Developer console is like this


Cheers 🙂 Happy Learning

Related Posts

Leave a Reply

Your email address will not be published. Required fields are marked *