Search code examples
sqlsql-serverreporting-servicessql-server-2014

WHERE IF (field depends of parameter) SQL


Example of initial data:

 Project   |   Field1   |   Field2    |   Field3    |
 --------------------------------------------------------------------
 Project 1 |      0     |      1      |      2      |
 Project 2 |      2     |      0      |      1      |

Using SQL Server 2014, I have table, where I need to get data which depends of value in ssrs parameter. Sample of query.

Select *
Where IF@Scenario=1, then Field1 < 2
      IF@Scenario=2, then Field2 < 2
      IF@Scenario=3, then Field3 < 2
From Table1

Solution

  • Select *
    FROM x
    Where 
          2 > 
          CASE @Scenario WHEN 1 THEN Field1 
               WHEN 2 THEN Field2
               WHEN 3 THEN Field3
               ELSE 0 --This part is just to avoid errors when scenario isnt in any of the options. 2>0 will display everything
          END
    

    Compare the condition (2) with the columns instead.