2

我有代码,我需要在 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

有没有办法做到这一点。

4

3 回答 3

4

你很亲近,

AND OrderID = (CASE WHEN @X = 0 THEN 10 ELSE 20 END)
AND DepartmentID = (CASE WHEN @X = 0 THEN DepartmentID ELSE 30 END)
于 2013-10-30T12:25:54.480 回答
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)))
于 2013-10-30T12:31:44.223 回答
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
于 2013-10-30T12:31:59.627 回答