TSQL:"IN"子句中的NULL

Moo*_*oon 3 sql t-sql sql-server sql-server-2008

我需要过滤记录,其中:

NotificationRead = 0 || NULL --> IF GetRead = 0
NotificationRead = 1 --> IF GetRead = 1
NotificationRead = 0 || 1 || NULL --> IF GetRead = NULL
Run Code Online (Sandbox Code Playgroud)

这是我正在使用的查询:

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)
Run Code Online (Sandbox Code Playgroud)

当我NULLIN子句中提供时,上面的查询基本上失败了.我知道为什么要感谢这个问题.

但是,如果我按照该问题的答案(使用NotificationRead IN (@Query) OR NotificationRead IS NULL)中的建议采取方法,我会得到所有记录,例如NotificationRead = NULL当我不需要它们时,@GetRead = 1

你能指点我正确的方向吗?

Mar*_*ers 6

不,问题是您将值作为字符串提供.

1 IN (1, 2) -- true.
1 IN ('1, 2') -- false.
Run Code Online (Sandbox Code Playgroud)

试试这个:

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))
Run Code Online (Sandbox Code Playgroud)