T-SQL Tutorial

GOTO label


The SQL Server GOTO statement is used to allow the sql code to jump from one label to another. If a condition is met, then the jump is made directly to the specified label.


Syntax

Define the label:
label:
Alter the execution:
GOTO label


Example of GOTO

In the following example, 3 labels have been declared (Label_1, Label_2, Label_3) that represent 3 points from which the sql code is executed. When the first condition is met (@Count = 3) the T-SQL script goes from Label_1 directly to Label_3, skipping Label_2.

USE model
GO
DECLARE @Count int;
SET @Count = 1;
WHILE @Count < 5
BEGIN
SELECT @Count
SET @Count = @Count + 1
IF @Count = 3 GOTO Label_1
IF @Count = 4 GOTO Label_2
END
Label_1: SELECT 'A'
GOTO Label_3;
Label_2: SELECT 'B';
Label_3: SELECT 'C';
GO