Search code examples
sql-servergoto

Execute Query After GOTO Syntax


I have a sample query, my problem is how to execute query after triggering GOTO syntax.

This is my query:

DECLARE @TotalMaarks INT
SET @TotalMaarks = 49

IF @TotalMaarks >= 50
   GOTO Pass

IF @TotalMaarks < 50
   GOTO Fail

PRINT ' Congratulations '

Pass:
   PRINT ' Congratulations '
   PRINT ' You pass the Examination '
   RETURN

Fail:
   PRINT ' You Failed! '
   PRINT ' Better Luck Next Time '
   RETURN
GO

The result of that query will GOTO Fail:

You Failed!

Better Luck Next Time

But I want is after triggering Fail: it will also execute PRINT 'Congratulations'

Expected result:

You Failed!

Better Luck Next Time

Congratulations

How can I return to IF to execute the other left queries?

Because after the Fail it will end.


Solution

  • Avoid GOTO. It used to be necessary for error handling before TRY/CATCH was added to TSQL, but I can't really think of a scenario where I would use it any more. GOTO is discouraged in almost every language that has it, way back to the famous 1968 paper Go To Statement Considered Harmful

    DECLARE @TotalMaarks INT
    SET @TotalMaarks = 49
    
    IF @TotalMaarks >= 50
    BEGIN
       PRINT ' Congratulations '
       PRINT ' You pass the Examination '
    END
    ELSE IF @TotalMaarks < 50
    BEGIN
       PRINT ' You Failed! '
       PRINT ' Better Luck Next Time '
    END
    
    PRINT ' Congratulations '
    
    GO