WHERE IF(字段取决于参数)SQL

时间:2017-04-04 04:46:10

标签: sql sql-server reporting-services sql-server-2014

初始数据示例:

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

使用SQL Server 2014,我有表,我需要在ssrs参数中获取依赖于值的数据。查询样本。

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

3 个答案:

答案 0 :(得分:5)

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

将条件(2)与列进行比较。

答案 1 :(得分:1)

使用AND/OR条件

Select *
From Table1
Where (@Scenario=1 and Field1 < 2) Or 
      (@Scenario=2 and Field2 < 2) Or
      (@Scenario=3 and Field3 < 2)

答案 2 :(得分:1)

在WHERE cluase中使用CASE语句:

SELECT *
FROM Table1
WHERE CASE @Scenario WHEN 1 THEN Field1 
       WHEN 2 THEN Field 2
       WHEN 3 THEN Field 3
       ELSE 0 END < 2