In a "religious" discussion about formatting of Microsoft T-SQL code, I questioned whether or not the GOTO statement was still available in T-SQL syntax. In 13 years of using T-SQL I have never had occasion to use it, and indeed didn't know if it existed. After a brief search of the documentation and to my consternation it does indeed exist!
My question is this:
Is there at least one case where GOTO statements would yield a solution that performs better than one in which other higher order programming constructs are used?
My question is NOT:
The GOTO statement is a straightforward and basic flow of control statement that causes an unconditional change in the flow of control. It is used to branch to a specific user-defined location using labels defined in the SQL procedure.
GoTo (goto, GOTO, GO TO or other case combinations, depending on the programming language) is a statement found in many computer programming languages. It performs a one-way transfer of control to another line of code; in contrast a function call normally returns control.
Use of goto LABEL or goto EXPR to jump into a construct is deprecated and will issue a warning. Even then, it may not be used to go into any construct that requires initialization, such as a subroutine, a foreach loop, or a given block.
As an alternative, you can always use a command exit which causes an immediate termination of the running loop and continuation your program after the corresponding enddo identifier. Another useful command is cycle which stops executing the current loop and goes back to the header of the loop to initiate a new cycle.
I almost never use GOTO
and can easily live without it.
The one case where I would consider using it is when I have complicated code that does lots of error checking. I might want to take some action when an error returns, and GOTO
allows me to define a single block of code for the error checking.
You can solve this problem in multiple ways, but GOTO
is a reasonable option that guarantees that errors are processed consistently and the code is not cluttered with a lot of if @Error = 0 . . .
statements.
i saw goto a few times in large scripts where people used it to improve readability. sometimes it is better readable but mostly it turns into spaghetti code.
i see just one situation where goto can maybe perform better. its inside a multiple while loop. you can use goto once instead of multiple breaks which just exists the innermost loop. nevertheless in my opinion break is not much better than goto, its both not a good programming style.
while ...
while ...
while...
break
break
break
while ...
while ...
while...
goto endloops
endloops:
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With