The IF statement is used to test for a condition. The resulting flow of control depends on whether the optional ELSE statement is specified:
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 are skipped.
When the IF statement evaluates to TRUE, the statement or block of statements following the IF statement are executed, and 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 are skipped and the statement or block of statements following the optional ELSE statement are 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
ELSE (IF...ELSE) | IF...ELSE |