5

I have some code where variable used in the WHERE clause could be nullable. As a result I have to query data using IF ELSE to check for NULL. Is there anyway of writing in in one query?

DECLARE @OrderID UNIQUEIDENTIFIER

IF @OrderID IS NULL 
BEGIN
    SELECT * 
    FROM Customers
    WHERE OrderID IS NULL
END
ELSE
BEGIN
    SELECT * 
    FROM Customers
    WHERE OrderID = @OrderID
END
4

3 回答 3

9
  SELECT * 
  FROM Customers
  WHERE EXISTS (SELECT OrderID INTERSECT SELECT @OrderID)

将有效地做到这一点。

有关更多信息,请参阅未记录的查询计划:平等比较

于 2013-10-30T13:03:13.480 回答
1

假设您想要 order_id 为空或等于提供的订单 ID 的所有记录,如果不为空,使用 COALESCE 将保留原始订单 ID,但如果空,则生成提供的订单 ID。然后将其与提供的订单 ID 进行比较。

SELECT *
FROM customers c
WHERE COALESCE(c.order_id, @OrderID) = @OrderID;

根据查询的正确版本,我要么将其全部写在 WHERE 子句中,要么可能将双方 COALESCE 写入一个已知不会出现在该列中的值。

SELECT c.*
FROM customers c
WHERE (@OrderID IS NULL AND c.OrderId IS NULL) OR c.OrderId = @OrderId

-- OR

SELECT c.*
FROM customers c
WHERE COALESCE(@OrderId, '@@@') = COALESCE(c.OrderId, '@@@')
于 2013-10-30T13:03:59.940 回答
0

尝试这个

DECLARE @OrderID UNIQUEIDENTIFIER

SELECT * FROM Customers
WHERE ISNULL(@OrderID, 0) = 0 or @OrderID = @OrderID
于 2013-10-30T13:03:04.597 回答