| title | GOTO (Transact-SQL) | Microsoft Docs | |||||
|---|---|---|---|---|---|---|
| ms.custom | ||||||
| ms.date | 03/15/2017 | |||||
| ms.prod | sql | |||||
| ms.prod_service | database-engine, sql-database | |||||
| ms.service | ||||||
| ms.component | t-sql|language-elements | |||||
| ms.reviewer | ||||||
| ms.suite | sql | |||||
| ms.technology |
|
|||||
| ms.tgt_pltfrm | ||||||
| ms.topic | language-reference | |||||
| f1_keywords |
|
|||||
| dev_langs |
|
|||||
| helpviewer_keywords |
|
|||||
| ms.assetid | 589b6f8e-dc80-416f-9e74-48bed5337f58 | |||||
| caps.latest.revision | 33 | |||||
| author | douglaslMS | |||||
| ms.author | douglasl | |||||
| manager | craigg | |||||
| ms.workload | On Demand |
[!INCLUDEtsql-appliesto-ss2008-asdb-xxxx-xxx-md]
Alters the flow of execution to a label. The [!INCLUDEtsql] statement or statements that follow GOTO are skipped and processing continues at the label. GOTO statements and labels can be used anywhere within a procedure, batch, or statement block. GOTO statements can be nested.
Transact-SQL Syntax Conventions
Define the label:
label:
Alter the execution:
GOTO label
label
Is the point after which processing starts if a GOTO is targeted to that label. Labels must follow the rules for identifiers. A label can be used as a commenting method whether GOTO is used.
GOTO can exist within conditional control-of-flow statements, statement blocks, or procedures, but it cannot go to a label outside the batch. GOTO branching can go to a label defined before or after GOTO.
GOTO permissions default to any valid user.
The following example shows how to use GOTO as a branch mechanism.
DECLARE @Counter int;
SET @Counter = 1;
WHILE @Counter < 10
BEGIN
SELECT @Counter
SET @Counter = @Counter + 1
IF @Counter = 4 GOTO Branch_One --Jumps to the first branch.
IF @Counter = 5 GOTO Branch_Two --This will never execute.
END
Branch_One:
SELECT 'Jumping To Branch One.'
GOTO Branch_Three; --This will prevent Branch_Two from executing.
Branch_Two:
SELECT 'Jumping To Branch Two.'
Branch_Three:
SELECT 'Jumping To Branch Three.';
Control-of-Flow Language (Transact-SQL)
BEGIN...END (Transact-SQL)
BREAK (Transact-SQL)
CONTINUE (Transact-SQL)
IF...ELSE (Transact-SQL)
WAITFOR (Transact-SQL)
WHILE (Transact-SQL)