我需要过滤以下记录:
NotificationRead = 0 || NULL --> IF GetRead = 0
NotificationRead = 1 --> IF GetRead = 1
NotificationRead = 0 || 1 || NULL --> IF GetRead = NULL
这是我为此使用的查询:
DECLARE @GetRead BIT
DECLARE @Query VARCHAR(20)
SET @GetRead = NULL
IF @GetRead = 0 SET @Query = '0,NULL'
ELSE IF @GetRead = 1 SET @Query = '1'
ELSE SET @Query = '0,1,NULL'
SELECT * FROM vwNotifications WHERE NotificationRead IN (@Query)
当我在 IN
子句中提供 NULL
时,上面的查询基本上会失败。
感谢this question,我知道原因.
但是,如果我采用该问题的答案中建议的方法(使用 NotificationRead IN (@Query) OR NotificationRead IS NULL
),我会得到 NotificationRead = NULL
的所有记录> 例如,当我不需要它们时,当 @GetRead = 1
你能告诉我正确的方向吗?
最佳答案
不,问题是您将值作为字符串提供。
1 IN (1, 2) -- true.
1 IN ('1, 2') -- false.
试试这个:
SELECT *
FROM vwNotifications
WHERE (@GetRead = 0 AND (NotificationRead = 0 OR NotificationRead IS NULL))
OR (@GetRead = 1 AND NotificationRead = 1)
OR (@GetRead IS NULL AND (NotificationRead IN (0, 1) OR
NotificationRead IS NULL))
关于sql - TSQL: "IN"子句中的 NULL,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7923229/