Search code examples
sqlsql-servergoto

Understanding T-SQL GOTO


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?


Solution

  • 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.