All for Joomla All for Webmasters

PL/SQL While Loop

PL/SQL while loop is used when a set of statements has to be executed as long as a condition is true, the While loop is used. The condition is decided at the beginning of each iteration and continues until the condition becomes false.

Syntax of while loop:

  1. WHILE <condition>
  2.  LOOP statements;
  3. END LOOP;

Example of PL/SQL While Loop

Let’s see a simple example of PL/SQL WHILE loop.

  1. DECLARE
  2. INTEGER := 1;
  3. BEGIN
  4. WHILE i <= 10 LOOP
  5. DBMS_OUTPUT.PUT_LINE(i);
  6. i := i+1;
  7. END LOOP;
  8. 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 WHILE Loop.

  • Initialize a variable before the loop body.
  • Increment the variable in the loop.
  • You can use EXIT WHEN statements and EXIT statements in While loop but it is not done often.

PL/SQL WHILE Loop Example 2

  1. DECLARE
  2. VAR1 NUMBER;
  3. VAR2 NUMBER;
  4. BEGIN
  5. VAR1:=200;
  6. VAR2:=1;
  7. WHILE (VAR2<=10)
  8. LOOP
  9. DBMS_OUTPUT.PUT_LINE (VAR1*VAR2);
  10. VAR2:=VAR2+1;
  11. END LOOP;
  12. END;

Output:

200
400
600
800
1000
1200
1400
1600
1800
2000
PinIt
submit to reddit

Leave a Reply

Top