Monday, July 19, 2021

GoTo in SQL Store Procedures

 GoTo in Microsoft SQL Server is a keyword in the control flow of a SQL stored procedure. It allows logic to "go to" another point in the code. This effectively allows for jumping around the code and skipping/exiting conditions in an easy way.

Syntax:

DECLARE 
    @condition1 varchar='true';
    @condition2 varchar='true';
IF @condition1='true'
    BEGIN
        GOTO DevB;
    END
    
DevA:
    <SQL statements>
    GOTO DevEnd;
DevB: <SQL statements> IF @condition2='true' BEGIN GOTO DevA;
END DevEnd: return;             
Read more in the official Microsoft doc here.