在WHERE中使用CASE

时间:2013-10-30 12:24:35

标签: sql-server-2008 tsql case where-clause

我有代码,我需要将过滤器添加到where子句中,该子句根据变量的值而变化。如下例所示,如果@X的值为0,那么我想要 包括OrderID = 10的过滤器;否则我想为OrderID = 20添加过滤器,而DepartmentID的另一个过滤器为NULL或值为30.这可以使用IF ELSE完成,如下所示

DECLARE @X INT

-- Retrieve value for @X

IF @X = 0 
BEGIN
    SELECT *
    FROM Customers
    WHERE ProductID IS NOT NULL
    AND OrderID = 10
END
ELSE
BEGIN
    SELECT *
    FROM Customers
    WHERE ProductID IS NOT NULL
    AND OrderID = 20 AND ( DepartmentID IS NULL OR DepartmentID = 30)
END

我想知道是否有使用一个SQL语句进行此操作。我认为在WHERE中使用CASE是可行的,但SQL似乎不允许在下面。

SELECT *
    FROM Customers
    WHERE ProductID IS NOT NULL
    AND CASE WHEN @X = 0 THEN OrderID = 10 ELSE OrderID = 20 AND ( DepartmentID IS NULL OR DepartmentID = 30) END

有没有完成这个。

3 个答案:

答案 0 :(得分:4)

你很亲密,

AND OrderID = (CASE WHEN @X = 0 THEN 10 ELSE 20 END)
AND DepartmentID = (CASE WHEN @X = 0 THEN DepartmentID ELSE 30 END)

答案 1 :(得分:1)

您可以在没有CASE的情况下执行此操作:

SELECT *
FROM Customers
WHERE ProductID IS NOT NULL
AND ((@X = 0 AND OrderID = 10) OR (@X <> 0 AND OrderID = 20 AND DepartmentID = 30))

编辑:

根据您要添加的条件:

SELECT *
FROM Customers
WHERE ProductID IS NOT NULL
AND ((@X = 0 AND OrderID = 10) OR (@X <> 0 AND OrderID = 20 AND (DepartmentID IS NULL OR DepartmentID = 30)))

答案 2 :(得分:1)

SELECT *
FROM Customers
WHERE ProductID IS NOT NULL
AND OrderID = CASE WHEN @X = 0 THEN 10 ELSE 20 END
AND ISNULL(DepartmentID,30) = CASE WHEN @X = 0 THEN ISNULL(DepartmentID,30)  ELSE 30 END