SQL Server: GOTO Statement

GOTO statement in SQL Server

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 adglob;

   SET @site_value = @site_value + 1;

END;

adglob:
   PRINT 'adglob.in'; 

GO

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

Leave a Reply