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

标签 sql sql-server tsql sql-server-2008

我需要过滤以下记录:

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/

相关文章:

Mysql Join 两表合并为一个输出结果子查询返回多于 1 行

sql - 规范化 ORACLE 11g 中的列名

sql - 如何在列的 sql select 语句中插入新的 guid

sql - 为什么我的表没有显示在 SQL Server Management Studio 智能感知中?

sql-server - 如何在 HBase 中查看 3 版本的数据

SQL 按月分组日期

mysql - jsp中palette(数据库报表)生成的sql语句没有结果时如何显示错误信息

c# - 尝试使用 LINQ 以数据库字段作为参数获取不同的值

sql - 在生成查询时需要帮助

sql-server - 有没有办法在脚本中暂停或等待几分钟?