当变量为空时选择空数据SQL Server

时间:2019-07-05 18:47:05

标签: sql-server tsql

我想在变量为null时将变量传递到SQL Server中的存储过程中,它应该返回所有为空的行。

我找不到任何可以帮助我的东西。

如果我将null传递给变量,则它不返回任何内容,因为您需要说IS NULL

DECLARE @itemId INT = 5435
DECLARE @id INT = NULL

SELECT 
    rt.Id,
    'Received' as Type,
    rt.Quantity,
    rt.CuttingInstuctionId,
    rt.Date
FROM 
    ReceivingItemsTransactions rt
LEFT JOIN  
    Order ci ON rt.OrderId = ci.Id
WHERE
    rt.ItemId = @itemId 
    AND ci.PlannedProductionId = @id

在这种情况下,我希望仅获取空行。

有什么替代方法?

1 个答案:

答案 0 :(得分:1)

使用OR条件测试两者

declare @itemId int = 5435
declare @plannedProdId int = null

SELECT rt.Id,
'Received' as Type,
rt.Quantity,
rt.CuttingInstuctionId,
rt.Date
FROM ReceivingItemsTransactions rt
left join CuttingInstructions ci
on rt.CuttingInstuctionId = ci.Id
where rt.ItemId = @itemId and 
(
   (ci.PlannedProductionId = @plannedProdId) 
OR (@plannedProdId IS NULL AND ci.PlannedProductionId IS NULL
)

或者您可以使用工会?

declare @itemId int = 5435
declare @plannedProdId int = null

SELECT rt.Id,
'Received' as Type,
rt.Quantity,
rt.CuttingInstuctionId,
rt.Date
FROM ReceivingItemsTransactions rt
left join CuttingInstructions ci
on rt.CuttingInstuctionId = ci.Id
where rt.ItemId = @itemId and 
(ci.PlannedProductionId = @plannedProdId) 
UNION ALL
SELECT rt.Id,
'Received' as Type,
rt.Quantity,
rt.CuttingInstuctionId,
rt.Date
FROM ReceivingItemsTransactions rt
left join CuttingInstructions ci
on rt.CuttingInstuctionId = ci.Id
where rt.ItemId = @itemId and (@plannedProdId IS NULL AND ci.PlannedProductionId IS NULL)