Collectives™ on Stack Overflow
Find centralized, trusted content and collaborate around the technologies you use most.
Learn more about Collectives
Teams
Q&A for work
Connect and share knowledge within a single location that is structured and easy to search.
Learn more about Teams
I've cooked up a functional hack that may prove useful to others. On SQL Server 2008, you cannot dynamically build the goto, nor can you supply the label in a variable. The old school hack is to load the variable, jump to a single point that then uses if statements to determine the real destination.
GOTOs are of course
considered harmful
and are generally a bad idea.
print '1'
print '2'
goto l4
print '3' -- should not print
print '4'
declare @lbl nvarchar(5)
set @lbl = N'l6'
goto vjump
-- goto @lbl -- doesn't work
-- exec('goto ' + @lbl) -- doesn't work
print '5'
print '6'
print '7'
return
vjump:
if @lbl = 'l1'
goto l1
if @lbl = 'l2'
goto l2
if @lbl = 'l3'
goto l3
if @lbl = 'l6'
goto l6
This produces
–
–
Not a timely answer obviously, but when I recently found myself wanting to do this, the reason was because I wanted to execute the same bit of code multiple times and then return to the normal flow, basically "gosub" and not "goto"....
And
that
you can do. Not with a gosub, but with a temporary stored procedure -- create a temp stored procedure
create procedure #DRY
and then call it. You can drop it when you are done.
Thanks for contributing an answer to Stack Overflow!
-
Please be sure to
answer the question
. Provide details and share your research!
But
avoid
…
-
Asking for help, clarification, or responding to other answers.
-
Making statements based on opinion; back them up with references or personal experience.
To learn more, see our
tips on writing great answers
.