SQL Server GOTO Statement

January 16, 2011

in Developer, SQL Basics

People coming from other programming languages to any SQL based language will know how GO TO works in general, even with SQL Server, it is nearly the same.

Go To statement makes the execution of the T-SQL batch to jump and go to a “pre-defined” label. The term pre-defined is important over here, go to statement abruptly makes the code to jump to a label without executing any lines after it, unless the label is next to the Go To line….

We can embed Go to in any of the conditional control-of-flow statements, statement blocks, or procedures but, in practice it is not practical to make much use of this statement as too much of it would not make to code readable and understandable by humans!!! But one thing is, if we have no other choice other than to use this statement then we have to just go ahead using it.

The below is an example from BOL on how to use the GOTO statement, it shows us on how it can be used and how the calls can be made using it, not that the second branch would never be execute because of the condition that is there.

DECLARE @Counter int;

SET @Counter = 1;

WHILE @Counter < 10

BEGIN

SELECT @Counter

SET @Counter = @Counter + 1

IF @Counter = 4 GOTO Branch_One --Jumps to the first branch.

IF @Counter = 5 GOTO Branch_Two  --This will never execute.

END

Branch_One:

SELECT 'Jumping To Branch One.'

GOTO Branch_Three; --This will prevent Branch_Two from executing.

Branch_Two:

SELECT 'Jumping To Branch Two.'

Branch_Three:

SELECT 'Jumping To Branch Three.'

And the below is with a small alter to the above code just showing that we can have a GO TO call/ the Label’s anywhere, there is no precedence.


DECLARE @Counter int;

SET @Counter = 1;

Branch_One:

SELECT 'I am above the GOTO Call'

GOTO Branch_Three; --This will prevent Branch_Two from executing.

WHILE @Counter < 10

BEGIN

SELECT @Counter

SET @Counter = @Counter + 1

IF @Counter = 4 GOTO Branch_One --Jumps to the first branch.

IF @Counter = 5 GOTO Branch_Two  --This will never execute.

END

Branch_Two:

SELECT 'Jumping To Branch Two.'

Branch_Three:

SELECT 'I am below the GOTO Call'

Comments on this entry are closed.

Previous post:

Next post: