Skip to content

Latest commit

 

History

History
93 lines (79 loc) · 3.71 KB

File metadata and controls

93 lines (79 loc) · 3.71 KB
title BEGIN...END (Transact-SQL)
description BEGIN...END (Transact-SQL)
author rwestMSFT
ms.author randolphwest
ms.date 03/15/2017
ms.service sql
ms.subservice t-sql
ms.topic reference
f1_keywords
BEGIN
BEGIN_TSQL
helpviewer_keywords
enclosing statements [SQL Server]
BEGIN statement
control-of-flow language [SQL Server], BEGIN...END statement
BEGIN...END keyword
grouping statements, BEGIN...END statement
executing Transact-SQL statements together [SQL Server]
statements [SQL Server], grouping
dev_langs
TSQL
monikerRange >= aps-pdw-2016 || = azuresqldb-current || = azure-sqldw-latest || >= sql-server-2016 || >= sql-server-linux-2017 || = azuresqldb-mi-current||=fabric

BEGIN...END (Transact-SQL)

[!INCLUDE sql-asdb-asdbmi-asa-pdw-fabricse-fabricdw]

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.

:::image type="icon" source="../../includes/media/topic-link-icon.svg" border="false"::: Transact-SQL syntax conventions

Syntax

BEGIN  
    { sql_statement | statement_block }   
END  

[!INCLUDEsql-server-tsql-previous-offline-documentation]

Arguments

{ sql_statement | statement_block }
Is any valid [!INCLUDEtsql] statement or statement grouping as defined by using a statement block.

Remarks

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.

Examples

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 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  
/*  
Rolled back the transaction.  
*/  

Examples: [!INCLUDEssazuresynapse-md] and [!INCLUDEssPDW]

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;

See Also

ALTER TRIGGER (Transact-SQL)
Control-of-Flow Language (Transact-SQL)
CREATE TRIGGER (Transact-SQL)
END (BEGIN...END) (Transact-SQL)