SQL更改WHERE列和值取决于传入变量

时间:2017-03-16 11:14:09

标签: sql sql-server-2016

我有一个存储过程来根据传入的过滤器类型和过滤器值过滤表的结果。

目前这是一个非常大的If / Else声明:

IF @FilterBy = 'CustomerName'
  SELECT X, Y, Z
  FROM @Table
  WHERE CustomerName = @FilterValue
  ORDER BY CustomerID

ELSE IF @FilterBy = 'OrderID'
  SELECT X, Y, Z
  FROM @Table
  WHERE OrderID = CAST(@FilterValue AS SMALLINT)
  ORDER BY CustomerID

我还有5个Else Ifs,我总是从同一个表中选择相同的列。有没有办法为WHERE子句使用CASE或switch语句来清理代码?

3 个答案:

答案 0 :(得分:2)

尝试类似下面的查询,

  SELECT X, Y, Z
  FROM @Table
  WHERE CustomerName    = (CASE WHEN @FilterBy = 'CustomerName' 
                                THEN @FilterValue ELSE CustomerName END)
    AND OrderID         = (CASE WHEN @FilterBy = 'OrderID' 
                                THEN  CAST(@FilterValue AS SMALLINT)    ELSE OrderID END)
  ORDER BY CustomerID

答案 1 :(得分:1)

你认为对你有用吗?

SELECT X, Y, Z
  FROM @Table
  WHERE CustomerName = @FilterValue AND @FilterBy = 'CustomerName'
        OR 
        OrderID = CAST(@FilterValue AS SMALLINT) AND @FilterBy = 'OrderID'
        OR
        ...
  ORDER BY CustomerID

答案 2 :(得分:0)

Use CASE Statement in WHERE Clause to achieve your result easily :

 SELECT X, Y, Z FROM @Table
 WHERE CustomerName = CASE WHEN @FilterValue = 'CustomerName' THEN 
  @FilterValue ELSE CustomerName END AND 
  OrderID = CASE WHEN @FilterValue = 'OrderID' THEN CAST(@FilterValue AS         
  SMALLINT) ELSE OrderID END AND
  --- Your another 3 case statements like above format----
 ORDER BY CustomerID