Back to all posts

How to use GOTO statement in SQL server

If you want to jump to a specific point in your SQL code, you can use the GOTO statement. The GOTO statement is used to exit a loop or a nested block of co…

If you want to jump to a specific point in your SQL code, you can use the GOTO statement.
The GOTO statement is used to exit a loop or a nested block of code.


The GOTO statement is a control flow statement in SQL that unconditionally transfers control to a label.
The label is a user-defined identifier that is used to mark a specific point in the code.
The GOTO statement is typically used to jump to a label that is located within a loop or a nested block of code.

SQL
IF OBJECT_ID('TestGOTO') IS NOT NULL
BEGIN
	DROP PROC TestGOTO
END
GO
CREATE PROCEDURE TestGOTO
AS
BEGIN
    SELECT 1

    GOTO move1;

	SELECT 2

	move1:
	SELECT 3

	GOTO move3;

	move2:

	SELECT 4



move3:
END;
go
exec TestGOTO 

Let's break it down step by step:

  1. Inside the procedure, there's a SELECT 1 statement, followed by a GOTO move1; statement. This will jump to the label named 'move1'.
  2. SELECT 2 is skipped because of the GOTO statement.
  3. move1:: This is a label in the code. Labels are used as targets for GOTO statements.
  4. SELECT 3: This statement will be executed after the GOTO jump.
  5. GOTO move3;: This jumps to the label named 'move3'.
  6. move2:: This label is not reached because of the GOTO statement.
  7. SELECT 4: This statement is not executed due to the GOTO.
  8. move3:: This label is the target of the second GOTO statement.
  9. END;: Marks the end of the stored procedure definition.
  10. EXEC TestGOTO: Executes the stored procedure named 'TestGOTO'.

When you execute this script, the output will be the result of the SELECT statements that are executed within the stored procedure, which in this case will be just 1 and 3.

Keep building your data skillset

Explore more SQL, Python, analytics, and engineering tutorials.