8. SQL Statements : IF - THEN - ELSE : Description : If...Then...Elseif Statement
 
Share this page                  
If...Then...Elseif Statement
The third IF variant includes the ELSEIF clause. The ELSEIF clause allows the application to test a series of conditions in a prescribed order. The statement list corresponding to the first true condition found is executed and all other statement lists connected to conditions are skipped. The ELSEIF construct can be used with or without an ELSE clause, which must follow all the ELSEIF clauses. If an ELSE clause is included, one statement list is guaranteed to be executed, because the statement list connected to the ELSE is executed if all the specified conditions evaluate to false.
The simplest form of this variant is:
IF boolean_expr THEN
       statement; {statement;}
ELSEIF boolean_expr THEN
       statement; {statement;}
ENDIF
If the first Boolean expression evaluates to true, the statements immediately following the first THEN keyword are executed. In such a case, the value of the second Boolean expression is irrelevant. If the first Boolean expression proves false, however, the next Boolean expression is tested. If the second expression is true, the statements under it are executed. If both Boolean expressions test false, neither statement list is executed.
A more complex example of the ELSEIF construct is:
IF boolean_expr THEN
       statement; {statement;}
ELSEIF boolean_expr THEN
       statement; {statement;}
ELSEIF boolean_expr THEN
       statement; {statement;}
ELSE
       statement; {statement;}
ENDIF
In this case, the first statement list is executed if the first Boolean expression evaluates to true. The second statement list is executed if the first Boolean expression is false and the second true. The third statement list is executed only if the first and second Boolean expressions are false and the third evaluates to true. Finally, if none of the Boolean expressions is true, the fourth statement list is executed. After any of the statement lists is executed, control passes to the statement following the ENDIF.