IF...ELSE (TSQL Statement)

is a conditional branch statement.

Syntax

IF condition
    <statement>
[ ELSE 
    <statement>
]

Arguments

condition
is a condition expression of type bool.
<statement>
any valid TSQL statement or BEGIN...END block of statements.

Remarks

The ELSE clause can be omitted.

IF statements can be nested.

Example

DECLARE @i INT = 0;

WHILE @i < 5
  BEGIN
  IF @i % 2 = 0
    PRINT 'The number ' + CAST(@i AS VARCHAR) + ' is even.';
  ELSE
    PRINT 'The number ' + CAST(@i AS VARCHAR) + ' is odd.';

  SET @i += 1;
  END

The result is:

The number 0 is even.
The number 1 is odd.
The number 2 is even.
The number 3 is odd.
The number 4 is even.