SQL Server: GOTO Statement

This SQL Server tutorial explains how to use the GOTO statement in SQL Server (Transact-SQL) with syntax and examples.

Description

The GOTO statement causes the code to branch to the label after the GOTO statement.

Syntax

The syntax for the GOTO statement in SQL Server (Transact-SQL) consists of two parts – the GOTO statement and the Label Declaration:

GOTO statement

The GOTO statement consists of the GOTO keyword, followed by a label_name.

GOTO label_name;

Label Declaration

The Label Declaration consists of the label_name, followed by at least one statement to execute.

label_name:
 {...statements...}

Note

  • label_name must be unique within the scope of the code.
  • There must be at least one statement to execute after the Label Declaration.

Example

Let’s look at how to use the GOTO statement in SQL Server (Transact-SQL).

For example:

DECLARE @site_value INT;
SET @site_value = 0;

WHILE @site_value <= 10
BEGIN

   IF @site_value = 2
      GOTO TechOnTheNet;

   SET @site_value = @site_value + 1;

END;

TechOnTheNet:
   PRINT 'TechOnTheNet.com'; 

GO

In this GOTO example, we have created one GOTO statements called TechOnTheNet. If @site_value equals 2, then the code will branch to the label called TechOnTheNet.