Bagikan melalui


Using IF...ELSE

The IF statement is used to test for a condition. The resulting flow of control depends on whether the optional ELSE statement is specified:

  • IF specified without ELSE

    When the IF statement evaluates to TRUE, the statement or block of statements following the IF statement are executed. When the IF statement evaluates to FALSE, the statement, or block of statements, following the IF statement is skipped.

  • IF specified with ELSE

    When the IF statement evaluates to TRUE, the statement, or block of statements, following the IF statement, is executed. Then control jumps to the point after the statement, or block of statements, following the ELSE statement. When the IF statement evaluates to FALSE, the statement, or block of statements, following the IF statement is skipped and the statement, or block of statements, following the optional ELSE statement is executed.

For example, if a stored procedure has been saving any error codes returned by @@ERROR during a transaction, it might have an IF statement similar to the following at the end of the procedure:

IF (@ErrorSaveVariable <> 0)
BEGIN
   PRINT 'Errors encountered, rolling back.'
   PRINT 'Last error encountered: ' +
      CAST(@ErrorSaveVariable AS VARCHAR(10))
   ROLLBACK
END
ELSE
BEGIN
   PRINT 'No Errors encountered, committing.'
   COMMIT
END
RETURN @ErrorSaveVariable

For more examples, see ELSE (IF...ELSE) (Transact-SQL).

See Also

Reference