IF GetRead = 0 NotificationRead = 1 --> IF GetRead = 1 N-6ren">
gpt4 book ai didi

sql - TSQL: "IN"子句中的 NULL

转载 作者:行者123 更新时间:2023-12-05 00:23:47 25 4
gpt4 key购买 nike

我需要过滤以下记录:

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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com