Home

GOTO statements should not be used

Description

    The GOTO statements should not be used rule states that GOTO statements should not be used when writing SQL Server code. GOTO statements are a type of unconditional jump which can make code difficult to read and maintain. They should be avoided in favor of more structured programming techniques, such as using IF-ELSE statements. Using GOTO statements can also lead to unintended results, as the code may not execute as intended. This rule encourages developers to use more structured programming techniques to ensure that code is more readable and maintainable.

Key Benefits

  • Eliminates the possibility of an infinite loop: GOTO statements can create loops that are difficult to debug and can cause programs to run indefinitely. By eliminating them, the program's flow is easier to understand and maintain.
  • Improves code readability: GOTO statements can make code harder to read and understand, as the flow of the program is not always straightforward. By avoiding them, code readability is improved.
  • Makes debugging easier: GOTO statements can make debugging more difficult, as the flow of the program is not always obvious. By avoiding them, debugging is made simpler.

 

Non-compliant Code Example

DECLARE @Counter int;  
SET @Counter = 1;  
WHILE @Counter < 10  
    BEGIN   
        SELECT @Counter  
        SET @Counter = @Counter + 1  
        IF @Counter = 4 GOTO Branch_One  --Non compliant code (GOTO statements is used)
        IF @Counter = 5 GOTO Branch_Two   --Non compliant code (GOTO statements is used)
    END  
Branch_One:  
    SELECT 'Jumping To Branch One.'  
    GOTO Branch_Three;  --Non compliant code (GOTO statements is used)
Branch_Two:  
    SELECT 'Jumping To Branch Two.'  
Branch_Three:  
    SELECT 'Jumping To Branch Three.'; 
Visual Expert 2024
 VETSQLRULE23