IF/THEN/ELSE Statements
The IF/THEN
statement checks a Boolean
value or expression and if
true, executes the statements in the THEN clause
. If the condition is false, the statements in the THEN clause
are skipped and execution jumps to the END IF, and
the expression that is checked must return a true or false. It
can be a simple Boolean variable or a compound expression joined
with AND/OR clauses, and the expression can even be a PL/SQL
function that returns a Boolean value.
There is no requirement to surround the
expression with parenthesis but most developers use parentheses
for clarity. The THEN clause can
contain a single or multiple statements, or a nested PL/SQL
block. Here is an example of a basic IF/THEN
statement with a THEN clause.
if
v_numb > 5 then
v_numb := 5;
v_other := 10;
end if;
In the statements above, the Boolean
condition (v_numb > 5) must be true before the THEN
clause is executed. If v_numb is equal to or less
than 5, or if it evaluates to NULL, the program control jumps to
the statement after the END IF clause.
Note that the THEN clause can contain any number of valid PL/SQL
statements. The variable v_other and v_numb will
not change unless the condition is true.
: All the
IF/THEN statements must end with an END IF
clause. The PL/SQL engine will continue to include
statements in the THEN clause until
it encounters an END IF. If you get a compile error that
states: “found xxxx when expecting IF”, the compiler
encountered an END statement before it encountered the END
IF. Simply find the end of you IF statement and close it with
an END IF to correct the problem.
Sometimes the program flow will want to
branch one direction if the condition is true and another
direction if the condition is false, and this is handled within
the IF/THEN/ELSE statement.
Like the IF/THEN
statement, the THEN clausestatements will only be executed if the
condition is true. However if the condition is false, the
statements in the ELSE clause are executed. This is an
either-or situation.
if
n_numb > 5 then
v_status := ‘large’;
else
v _status := ‘small’;
end if;
After executing the example, the variable
v_status will be defined as either large or small. Note
that the above statement could also be written as two separate
IF statements.
if
n_numb > 5 then v_status := ‘large’; end if;
if n_numb <=5 then v_status := ‘small’; end if;
Programmatically, the results are the same,
however the two IF statements required two evaluations, while
the IF/THEN/ELSE statement requires only one evaluation. But
what if there are multiple IF statements checking for multiple
conditions? Let’s see an example.