Nov 29, 2016

GOTO Statement in SQL Server

After a condition/statement execution, if we need to alter the flow of execution to start from a particular label, then GOTO statement will help you. Basically, GOTO keyword uses to skip statement process and continue from a particular label.
GOTO Statement in SQL Server contains two parts –

     GOTO statement declaration: GOTO statement contains GOTO keywords and label_name as below.

GOTO label_name

    Label Declaration: Label contains label_name only with at least one statement as below.

select * from tbl

Label_name must be unique within the scope of the code and after label_name declaration, there should be one SQL-statement.

Example: How can we use GOTO statement in SQL server, you can see below.

DECLARE @rating INT=10
WHILE @rating>0
            IF @rating=8
                        GOTO Codefari
            SET @rating=@rating-1
            PRINT @rating


In above example, we have created one GOTO statement lable_name is Codefari if the @rating value is 8 then code will branch to the label called Codefari.