Dark Mode
Image

PL/SQL Exit Loop

PL/SQL Exit Loop (Basic Loop)

PL/SQL exit loop is used when a set of statements is to be executed at least once before the termination of the loop. There must be an EXIT condition specified in the loop, otherwise the loop will get into an infinite number of iterations. After the occurrence of EXIT condition, the process exits the loop.

Syntax of basic loop:

LOOP  
  Sequence of statements;  
END LOOP;  

Syntax of exit loop:

LOOP   
   statements;   
   EXIT;   
   {or EXIT WHEN condition;}  
END LOOP;  

Example of PL/SQL EXIT Loop

Let's take a simple example to explain it well

 

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

After the execution of the above code, you will get the following result:

1
2
3
4
5
6
7
8
9
10

Note: You must follow these steps while using PL/SQL Exit Loop.

  • Initialize a variable before the loop body
  • Increment the variable in the loop.
  • You should use EXIT WHEN statement to exit from the Loop. Otherwise the EXIT statement without WHEN condition, the statements in the Loop is executed only once.

Comment / Reply From