title | description | author | ms.author | ms.date | ms.service | ms.subservice | ms.topic | ms.custom | f1_keywords | helpviewer_keywords | dev_langs | monikerRange | |||||||||||
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
BEGIN...END (Transact-SQL) |
BEGIN...END allows the execution of a group of Transact-SQL statements in a control of flow. |
rwestMSFT |
randolphwest |
05/18/2024 |
sql |
t-sql |
reference |
|
|
|
|
>=aps-pdw-2016 || =azuresqldb-current || =azure-sqldw-latest || >=sql-server-2016 || >=sql-server-linux-2017 || =azuresqldb-mi-current || =fabric |
[!INCLUDE sql-asdb-asdbmi-asa-pdw-fabricse-fabricdw-fabricsqldb]
Encloses a series of [!INCLUDE tsql] statements so that a group of [!INCLUDE tsql] statements can be executed in a logical block of code. BEGIN
and END
are control-of-flow language keywords.
:::image type="icon" source="../../includes/media/topic-link-icon.svg" border="false"::: Transact-SQL syntax conventions
BEGIN
{ sql_statement | statement_block }
END
Any valid [!INCLUDE tsql] statement or statement grouping as defined by using a statement block.
BEGIN...END
blocks can be nested.
Although all [!INCLUDE tsql] statements are valid within a BEGIN...END
block, certain [!INCLUDE tsql] statements shouldn't be grouped together within the same batch, or statement block.
In the following example, BEGIN
and END
define a series of [!INCLUDE tsql] statements that execute together. If the BEGIN...END
block isn't included, both ROLLBACK TRANSACTION
statements would execute, and both PRINT
messages would be returned.
USE AdventureWorks2022;
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
Examples: [!INCLUDE ssazuresynapse-md] and [!INCLUDE ssPDW]
In the following example, BEGIN
and END
define a series of [!INCLUDE DWsql] statements that run together. If the BEGIN...END
block isn't included, the following example runs in a continuous loop.
-- Uses AdventureWorksDW
DECLARE @Iteration INT = 0;
WHILE @Iteration < 10
BEGIN
SELECT FirstName,
MiddleName
FROM dbo.DimCustomer
WHERE LastName = 'Adams';
SET @Iteration += 1;
END;