Share via


Using BEGIN...END

The BEGIN and END statements are used to group multiple Transact-SQL statements into a logical block. Use the BEGIN and END statements anywhere a control-of-flow statement must execute a block of two or more Transact-SQL statements.

For example, when an IF statement controls the execution of only one Transact-SQL statement, no BEGIN or END statement is needed:

IF (@@ERROR <> 0)
   SET @ErrorSaveVariable = @@ERROR

If @@ERROR is 0, only the single SET statement is jumped.

Use BEGIN and END statements to make the IF statement skip a block of statements when it evaluates to FALSE:

IF (@@ERROR <> 0)
BEGIN
   SET @ErrorSaveVariable = @@ERROR
   PRINT 'Error encountered, ' + 
         CAST(@ErrorSaveVariable AS VARCHAR(10))
END

The BEGIN and END statements must be used as a pair: one cannot be used without the other. The BEGIN statement appears on a line by itself followed by the block of Transact-SQL statements. Finally, the END statement appears on a line by itself to indicate the end of the block.

Note

A BEGIN and END statement block must contain at least one Transact-SQL statement.

The BEGIN and END statements are used when:

  • A WHILE loop needs to include a block of statements.

  • An element of a CASE expression needs to include a block of statements.

  • An IF or ELSE clause needs to include a block of statements.