IF...ELSE (TSQL Statement)
is a conditional branch statement.
- If condition is True, the statement (or block of statements) following the condition is executed.
- Else, the statement (or block of statements) following the ELSE clause is executed.
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.