SA0176 : Consider merging nested IF statements to improve readability

The topic describes the SA0176 analysis rule.

Message

Consider merging nested IF statements to improve readability

Description

The rule checks the SQL code for nested IF statements, which can be combined in a single statement.

IF statement, which contain only IF statements and all have no ELSE clauses, can be merged in a single statement in order to improve code readability.

How to fix

Merge the nested IF statements in a single statement.

For example:

SQL
 1IF (boolean_expression1) 
 2BEGIN
 3   IF (boolean_expression2) 
 4   BEGIN
 5     sql_statements
 6   END
 7END
 8
 9IF ((boolean_expression1) AND (boolean_expression2)) 
10BEGIN
11sql_statements
12END

Scope

The rule has a Batch scope and is applied only on the SQL script.

Parameters

Rule has no parameters.

Remarks

The rule does not need Analysis Context or SQL Connection.

Effort To Fix
5 minutes per issue.
Categories

Design Rules, Code Smells

Additional Information

There is no additional info for this rule.

Example Test SQL
SQL
 1CREATE PROCEDURE tsp_TestSA0176
 2@param1 int,
 3@param2 int = 0
 4AS
 5IF (@param1 > 1) 
 6BEGIN
 7   IF (@param1 <= 10) 
 8   BEGIN
 9     SELECT @param1
10   END
11END
12
13IF (@param1 > 1) 
14    IF (@param1 <= 10)  
15        IF (@param2 != 0) 
16        BEGIN
17         SELECT @param1
18        END 
19
20
21IF (@param1 > 1 AND @param1 <= 10) 
22BEGIN
23     SELECT @param1
24END
25
26IF (@param1 > 1) 
27BEGIN
28   IF (@param1 <= 10)    
29     SELECT @param1
30SELECT 2
31END

Analysis Results
  Message Line Column
1 SA0176 : Consider merging nested IF statements to improve readability. 5 0
2 SA0176 : Consider merging nested IF statements to improve readability. 13 0
3 SA0176 : Consider merging nested IF statements to improve readability. 14 4
See Also

Other Resources