Controlling The Flow – Part 4

I am going to continue my articles (tidbits) on controlling the execution flow of statements in a Transaction SQL (T-SQL) program.

Every program has to be deterministic on what step to execute next. Otherwise, the computer would be clueless on what to do next.

The only exception to this rule is error handling. A runtime error may cause the program to branch to a error handler and exit the program.

Today, I want to talk about how to use the GOTO statement. I never use this statement during my coding adventures.

The primary criticism is that code that uses GOTO statements is harder to understand than alternative constructions. GOTO remains in use in certain common usage patterns, but alternatives are generally preferred if available.

The T-SQL example below randomly prints odd or even depending upon the result of the RAND() function. Just like the flip of a coin to determine heads or tails.

The output of this program is shown below.

To wrap up this talk, you might come across the GOTO command during your development endeavors.

If the code is hard to understand, consider re-writing the code using function/procedure, selection/choice and/or repetition/iteration constructs. These are the building blocks of structured programming.

Related posts

Leave a Comment