Thursday 6 September 2007

Control Flow in PL/SQL

PL/SQL allows you to branch and create loops in a fairly familiar way.
An IF statement looks like:

IF THEN ELSE END IF;

The ELSE part is optional. If you want a multiway branch, use:

IF THEN ...

ELSIF THEN ...
... ...
ELSIF THEN ...

ELSE ...

END IF;

Loops are created with the following:

LOOP
/* A list of statements. */
END LOOP;

At least one of the statements in should be an EXIT statement of the form

EXIT WHEN ;

The loop breaks if is true.
Some other useful loop-forming statements are:

  • EXIT by itself is an unconditional loop break. Use it inside a conditional if you like.
  • A WHILE loop can be formed with
    WHILE LOOP

    END LOOP;
  • A simple FOR loop can be formed with:
    FOR IN .. LOOP

    END LOOP;
    Here, can be any variable; it is local to the for-loop and need not be declared. Also, and are constants.