GOTO Label in SQL Server

There are times when you want to jump to a specific section (Label) in the code when a condition satisfies. You can create a label and then use the GOTO statement to branch directly to the code.

To create a label , simply specify the label name followed by the colon.

Label1:

Here’s a query demonstrating the usage of the Label named “RecordExistsLabel” and GOTO statement.

use AdventureWorks2014
GO
IF EXISTS (SELECT BusinessEntityID     
                FROM HumanResources.Employee   
                 WHERE MaritalStatus = 'S')  
BEGIN     
    GOTO RecordExistsLabel
END;  
PRINT 'Record does not exist'
RecordExistsLabel:
SELECT *  FROM HumanResources.Employee   WHERE  MaritalStatus = 'S';  
PRINT 'Record Exists'
image