IF...ELSE Block

Imposes conditions on the execution of an SQL statement. The SQL statement following an IF keyword and its condition is executed if the condition is satisfied (when the Boolean expression returns true). The optional ELSE keyword introduces an alternate SQL statement that is executed when the IF condition is not satisfied (when the Boolean expression returns false).

Syntax

IF Boolean_expression
    {sql_statement | statement_block}
[ELSE [Boolean_expression]
    {sql_statement | statement_block}]

where

Boolean_expression
Is an expression that returns true or false. If the Boolean expression contains a SELECT statement, the SELECT statement must be enclosed in parentheses.
sql_statement | statement_block
Is any SQL statement or statement grouping as defined with a statement block. The IF or ELSE condition can affect the performance of only a single SQL statement unless a statement block is used. To define a statement block, use the control-of-flow keywords BEGIN and END.

Remarks

IF...ELSE constructs can be used in batches, in stored procedures (where these constructs are often used to test for the existence of some parameter), and in ad hoc queries.

IF tests can be nested, either after another IF or following an ELSE. There is no limit to the number of levels of nesting.