totn Oracle / PLSQL

Oracle / PLSQL: WHILE LOOP

This Oracle tutorial explains how to use the WHILE LOOP in Oracle with syntax and examples.

Description

In Oracle, you use a WHILE LOOP when you are not sure how many times you will execute the loop body and the loop body may not execute even once.

Syntax

The syntax for the WHILE Loop in Oracle/PLSQL is:

WHILE condition
LOOP
   {...statements...}
END LOOP;

Parameters or Arguments

condition
The condition is tested each pass through the loop. If condition evaluates to TRUE, the loop body is executed. If condition evaluates to FALSE, the loop is terminated.
statements
The statements of code to execute each pass through the loop.

Note

  • You would use a WHILE LOOP statement when you are unsure of how many times you want the loop body to execute.
  • Since the WHILE condition is evaluated before entering the loop, it is possible that the loop body may not execute even once.

Example

Let's look at a WHILE LOOP example in Oracle:

WHILE monthly_value <= 4000
LOOP
   monthly_value := daily_value * 31;
END LOOP;

In this WHILE LOOP example, the loop would terminate once the monthly_value exceeded 4000 as specified by:

WHILE monthly_value <= 4000

The WHILE LOOP will continue while monthly_value <= 4000. And once monthly_value is > 4000, the loop will terminate.