Show TOC

IF Statement [T-SQL]Locate this document in the navigation structure

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

Syntax
 IF <expression>
   ... <statement>
   ... [ ELSEIF <expression> ] <statement> ]...
Examples

(back to top)

  • Example 1 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 use of the Transact-SQL ELSEIF statement:
    BEGIN
     DECLARE @X INT
     SET @X = 1
     IF @X = 1
      PRINT '1'
      ELSEIF @X = 2
       PRINT '2'
      ELSE
       PRINT 'something else'
    END
Usage

(back to top)

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 SAP IQ IF statement, the Transact-SQL IF statement has no THEN. The Transact-SQL version also has no ELSEIF 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.

Note You cannot nest the IF statement.
Standards

(back to top)

  • SQL—Transact-SQL extension to ISO/ANSI SQL grammar.
  • SAP Database products—SAP ASE supports the Transact-SQL IF statement.
Permissions