添加链接
link之家
链接快照平台
  • 输入网页链接,自动生成快照
  • 标签化管理网页链接
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

I had a hard time understanding it, until I realized the whole SQL statement (with goto and all the labels) should be inside the dynamically built SQL statement. Not only the goto statement. duedl0r Aug 6, 2013 at 9:23 If he's using SQL2k, probably is for error processing - as copying-paste all error processing in all necessary places is really worse than goto. Fabricio Araujo Oct 18, 2010 at 14:44

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 .