| title | BEGIN...END (Transact-SQL) | Microsoft Docs | |||||||
|---|---|---|---|---|---|---|---|---|
| ms.custom | ||||||||
| ms.date | 03/15/2017 | |||||||
| ms.prod | sql | |||||||
| ms.prod_service | database-engine, sql-database, sql-data-warehouse, pdw | |||||||
| ms.reviewer | ||||||||
| ms.technology | t-sql | |||||||
| ms.topic | language-reference | |||||||
| f1_keywords |
|
|||||||
| dev_langs |
|
|||||||
| helpviewer_keywords |
|
|||||||
| ms.assetid | fc2c7f76-f1f9-4f91-beef-bc8ef0da2feb | |||||||
| author | rothja | |||||||
| ms.author | jroth | |||||||
| monikerRange | >=aps-pdw-2016||=azuresqldb-current||=azure-sqldw-latest||>=sql-server-2016||=sqlallproducts-allversions||>=sql-server-linux-2017||=azuresqldb-mi-current |
[!INCLUDEtsql-appliesto-ss2008-all-md]
Encloses a series of [!INCLUDEtsql] statements so that a group of [!INCLUDEtsql] statements can be executed. BEGIN and END are control-of-flow language keywords.
Transact-SQL Syntax Conventions
BEGIN
{ sql_statement | statement_block }
END
{ sql_statement | statement_block }
Is any valid [!INCLUDEtsql] statement or statement grouping as defined by using a statement block.
BEGIN...END blocks can be nested.
Although all [!INCLUDEtsql] statements are valid within a BEGIN...END block, certain [!INCLUDEtsql] statements should not be grouped together within the same batch, or statement block.
In the following example, BEGIN and END define a series of [!INCLUDEtsql] statements that execute together. If the BEGIN...END block were not included, both ROLLBACK TRANSACTION statements would execute and both PRINT messages would be returned.
USE AdventureWorks2012;
GO
BEGIN TRANSACTION;
GO
IF @@TRANCOUNT = 0
BEGIN
SELECT FirstName, MiddleName
FROM Person.Person WHERE LastName = 'Adams';
ROLLBACK TRANSACTION;
PRINT N'Rolling back the transaction two times would cause an error.';
END;
ROLLBACK TRANSACTION;
PRINT N'Rolled back the transaction.';
GO
/*
Rolled back the transaction.
*/
In the following example, BEGIN and END define a series of [!INCLUDEDWsql] statements that run together. If the BEGIN...END block are not included, the following example will be in a continuous loop.
-- Uses AdventureWorks
DECLARE @Iteration Integer = 0
WHILE @Iteration <10
BEGIN
SELECT FirstName, MiddleName
FROM dbo.DimCustomer WHERE LastName = 'Adams';
SET @Iteration += 1
END;
ALTER TRIGGER (Transact-SQL)
Control-of-Flow Language (Transact-SQL)
CREATE TRIGGER (Transact-SQL)
END (BEGIN...END) (Transact-SQL)