IF-THEN-ELSIF:
The third form of IF statement uses the keyword ELSIF (not ELSIF) to introduce further conditions. There are multiple IF conditions are clubbed and written using the ELSIF clause.
Syntax:
IF CONDITION1 THEN
SEQUENCE_OF_STATEMENTS1;
ELSIF CONDITION2 THEN
SEQUENCE_OF_STATEMENTS2;
ELSE
SEQUENCE_OF_STATEMENTS3;
END IF;
If the first condition becomes FALSE or NULL then the ELSIF clause tests another condition. IF statement could have any number of ELSIF clause; the last ELSE clause is optional. These Conditions is evaluated one by one from top to bottom. If any condition becomes TRUE, its related sequence of statements is executed and control passes to the next statement following ENDIF. If all the conditions become FALSE or NULL and the sequence in the ELSE clause is executed. The given instance searches the greater of two numbers using IF-THEN-ELSIF.
Example 7.8
DECLARE
A NUMBER:=&A;
B NUMBER:=&B;
BEGIN
IF A>B THEN
DBMS_OUTPUT.PUT_LINE('THE GREATEST NUMBER IS '||A);
ELSIF B> A THEN
DBMS_OUTPUT.PUT_LINE('THE GREATEST NUMBER IS '||B);
ELSE
DBMS_OUTPUT.PUT_LINE('BOTH ARE EQUAL'); END IF;
END;
The given example accepts two numbers and the conditions are checked and depending on the condition which evaluates to TRUE, the message under that condition is displayed.
When possible, use the ELSIF clause in the other words of nested IF statements. This will make the code simpler to understand and read. Compare the subsequent IF statements.
IF condition1 THEN | IF condition1 THEN
statement1; | statement1;
ELSE | ELSIF condition2 THEN
IF condition2 THEN | statement2;
statement2; | ELSIF condition3 THEN
ELSE | statement3;
IF condition3 THEN | END IF;
statement3; |
END IF; |
END IF; |
END IF; |
These given statements are logically equivalent. Although the statement on the left obscures the flow of logic and the statement on the right reveals it.