Home

Loops with at most one iteration should be refactored

Rule description

  • Loops with at most one iteration should be refactored

 

Non-compliant Code Example

WHILE ( SELECT AVG(ListPrice) FROM dbo.DimProduct) < 300   --Non compliant code (While loop will break after first iteration)
BEGIN  
    UPDATE dbo.DimProduct SET ListPrice = ListPrice * 2;  

    SELECT MAX ( ListPrice) FROM dbo.DimProduct; 

    BREAK;  
END

Compliant Code Example

WHILE ( SELECT AVG(ListPrice) FROM dbo.DimProduct) < 300   --Compliant code (While loop will break based on the IF condition result)
BEGIN  
    UPDATE dbo.DimProduct  
        SET ListPrice = ListPrice * 2;  

    SELECT MAX ( ListPrice) FROM dbo.DimProduct;

    IF ( SELECT MAX (ListPrice) FROM dbo.DimProduct) > 500  
        BREAK;  
END
Visual Expert 2020
 VETSQLRULE21