IF statement [T-SQL]

Description

Provides conditional execution of a Transact-SQL statement, as an alternative to the Sybase IQ IF statement.

Syntax

 IF expression
... statement
... [ ELSEIF expression ] statement ]...

Examples

Example 1

This example illustrates the use of the Transact-SQL IF statement:

IF (SELECT max(id) FROM sysobjects) < 100
  RETURN
ELSE
  BEGIN
    PRINT 'These are the user-created objects'
    SELECT name, type, id
    FROM sysobjects
    WHERE id < 100
END

Example 2

The following two statement blocks illustrate Transact-SQL and Sybase IQ compatibility:

/* Transact-SQL IF statement */
IF @v1 = 0
  PRINT '0'
ELSE IF @v1 = 1
  PRINT '1'
ELSE
  PRINT 'other'
/* IQ IF statement */
IF v1 = 0 THEN
  PRINT '0'
ELSEIF v1 = 1 THEN
  PRINT '1'
ELSE
  PRINT 'other'
END IF

Usage

The Transact-SQL IF conditional and the ELSE conditional each control the performance of only a single SQL statement or compound statement (between the keywords BEGIN and END).

In contrast to the Sybase IQ IF statement, the Transact-SQL IF statement has no THEN. The Transact-SQL version also has no ELSE IF or END IF keywords.

When comparing variables to the single value returned by a SELECT statement inside an IF statement, you must first assign the result of the SELECT to another variable.


Side effects

None

Standards

Permissions

None