Was this page helpful?
Your feedback about this content is important. Let us know what you think.
Additional feedback?
1500 characters remaining
Export (0) Print
Expand All

Using BEGIN...END

SQL Server 2000

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.

The BEGIN and END statements are used when:

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

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

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

See Also

BEGIN...END

END (BEGIN...END)

Control-of-Flow Language

Show:
© 2015 Microsoft