pl-sql
  1. pl-sql-exit-loop

Exit Loop - (PL/SQL Control Statements)

In PL/SQL, the EXIT statement is used to exit a loop statement, such as a FOR loop or a WHILE loop. The EXIT statement can be used to exit a loop prematurely, based on a specified condition.

Syntax

The syntax for using the EXIT statement to exit a loop in PL/SQL is as follows:

EXIT [WHEN condition];

Here, condition is an optional condition that determines when the loop should be exited.

Example

Here is an example of using the EXIT statement to exit a FOR loop when a specific value is found in an array:

DECLARE
  TYPE myArray IS VARRAY(4) OF NUMBER;
  v_numbers myArray := myArray(1, 2, 3, 4);
  v_found BOOLEAN := FALSE;
BEGIN
  FOR i IN v_numbers.FIRST..v_numbers.LAST LOOP
    IF v_numbers(i) = 3 THEN
      v_found := TRUE;
      EXIT;
    END IF;
  END LOOP;

  IF v_found THEN
    DBMS_OUTPUT.PUT_LINE('Value 3 found in array.');
  ELSE
    DBMS_OUTPUT.PUT_LINE('Value 3 not found in array.');
  END IF;
END;

Output

The output of the above example will be:

Value 3 found in array.

Explanation

In the above example, we have defined an array called v_numbers and initialized it with four numbers. We then used a FOR loop to iterate through the array and check if the value 3 is present. If the value 3 is found in the array, we set the variable v_found to TRUE and use the EXIT statement to exit the loop. We then check the value of v_found to determine if the value 3 was found.

Use

The EXIT statement is useful in situations where you want to exit a loop prematurely, based on a specific condition. This can help to simplify code and make it more efficient.

Important Points

  • The EXIT statement is used in PL/SQL to exit a loop statement prematurely.
  • The EXIT statement can be used with a condition, which determines when the loop should be exited.
  • The EXIT statement is useful in simplifying code and improving performance.

Summary

In summary, the EXIT statement is a PL/SQL control statement that is used to exit a loop statement prematurely. It can be used with a condition, which determines when the loop should be exited. The EXIT statement is a useful tool in simplifying code and improving performance.

Published on: