Understanding T-SQL GOTO

和自甴很熟 提交于 2020-04-17 07:45:21

问题


My teacher recently talked about the statement 'GOTO', to be used in Management Studio, but I didn't quite understand it at first. He stated that GOTO is being used to jump to different pieces of code, with the help of a label I can name by myself. This is the code he used to represent his example:

select 'first'

goto jump
select 'second'

jump:
select 'third'

When I execute the code, sure enough, it prints 'first' and 'third'. My question now is what was the select 'second' doing there in the first place?


回答1:


In your example, the second select is clearly unnecessary.

GOTO is an example of "control-flow" for the the program code. It is a construct from the earliest computer languages, one that maps directly onto how the hardware works when processing languages such as C or assembly code. Since then, it has been included in many other languages.

GOTO would often be used with IF. However, T-SQL offers better control flow functionality, such as:

  • WHILE
  • IF/BEGIN
  • TRY/CATCH

In general, you should be using these constructs and not GOTO. In fact, GOTO is rather controversial. Many people think it is always a sign of poor code ("spaghetti code" is sometimes used to describe this type of code). Others will make a very rare exception for something like exception handling (which I sometimes do) or some types of state machines.

In my opinion, GOTO should only be taught after all the other constructs and only for very specific purposes.



来源:https://stackoverflow.com/questions/34453903/understanding-t-sql-goto

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!