The SQL GOTO statement is used to alter the flow of a program. When the execution reaches the GOTO statement, then it will jump unconditionally to the label specified in the goto statement.
SQL Goto Statement Syntax
The basic syntax of the GOTO Statement in SQL Server is as follows:
--List of Statements GOTO label ........ ........ label: statements
The label specified after the goto statement is the location, where we place the statements to execute.
SQL Goto Statement Example
This program will check whether the person is pass or fail using SQL server Goto Statement.
DECLARE @TotalMaarks INT SET @TotalMaarks = 49 IF @TotalMaarks >= 50 GOTO Pass IF @TotalMaarks < 50 GOTO Fail Pass: PRINT ' Congratulations ' PRINT ' You pass the Examination ' RETURN Fail: PRINT ' You Failed! ' PRINT ' Better Luck Next Time ' RETURN GO
Let us replace the @TotalMarks value with 76, and we replaced the second If statement with ELSE block
IF @TotalMaarks >= 50 GOTO Pass ELSE GOTO Fail
In the above code, Pass and Fail are the labels we used. First we declared integer variable @Totalmarks and assigned value 49 to it
DECLARE @TotalMaarks INT SET @TotalMaarks = 49
In the next line we used SQL IF ELSE to check whether @Totalmarks is greater than or equal to 50 or not.
IF @TotalMaarks >= 50
If the condition is TRUE then Goto statement inside the If block will take the execution to the Pass label, and execute the statements inside the Pass label
PRINT ' Congratulations ' PRINT ' You pass the Examination '<br>
f the condition is FLASE (Else block) then, Goto statement inside the Else block will take the execution to the Fail label, and execute the statements inside the Fail label
PRINT ' You Failed! ' PRINT ' Better Luck Next Time '
NOTE: Although SQL Server supports GOTO statement, it is always good practice to avoid using it or at least minimize the usage.
Thank You for Visiting Our Blog