pl-sql
  1. pl-sql-while-loop

While Loop - ( PL/SQL Control Statements )

A while loop in PL/SQL is a control statement that allows a block of code to be executed repeatedly while a certain condition is true. The loop will continue to execute until the condition is no longer true.

Syntax

The syntax for a while loop in PL/SQL is as follows:

WHILE condition LOOP
   -- Statement or block of statements to be executed
END LOOP;

Here, condition is the condition that is checked before each iteration of the loop. If the condition is true, the statements within the loop are executed. If the condition is false, the loop is exited.

Example

Here is an example of a while loop in PL/SQL that prints the numbers from 1 to 5:

DECLARE
   i NUMBER := 1;

BEGIN
   WHILE i <= 5 LOOP
      DBMS_OUTPUT.PUT_LINE(i);
      i := i + 1;
   END LOOP;
END;

Output

1
2
3
4
5

Explanation

In the above example, we have defined a variable i and initialized it to 1. Inside the while loop, the DBMS_OUTPUT.PUT_LINE() procedure is used to print the value of i. We then increment i by 1 and the loop continues until i becomes greater than 5.

Uses

While loops are used when a block of code needs to be executed repeatedly while a certain condition is true. They provide a way to automate repetitive tasks and can be used in a variety of applications.

Important Points

  • A while loop in PL/SQL allows a block of code to be executed repeatedly while a certain condition is true.
  • The condition is evaluated before each iteration of the loop.
  • While loops are useful for automating repetitive tasks.

Summary

In summary, a while loop in PL/SQL is a control statement that allows a block of code to be executed repeatedly while a certain condition is true. They are useful for automating repetitive tasks and can be used in a variety of applications. While loops are evaluated before each iteration of the loop and continue to execute until the condition is no longer true.

Published on: