Sql server 比较列中的整数与空值?

Sql server 比较列中的整数与空值?,sql-server,Sql Server,我有一张桌子。该表有两个整数列。每列中允许为空。以下查询工作正常 select * from table where col1=1 and col2 = 2 但以下两个查询都不起作用 select * from table where col1=1 and col2 != 2 or select * from table where col1=1 and col2 <> = 2 以及insert语句 INSERT INTO test (id, col1 , co

我有一张桌子。该表有两个整数列。每列中允许为空。以下查询工作正常

 select * from table where col1=1 and col2 = 2
但以下两个查询都不起作用

 select * from table where col1=1 and col2 != 2 or
 select * from table where col1=1 and col2 <> = 2
以及insert语句

 INSERT INTO test 
    (id, col1 , col2)
 VALUES 
    (1,1,NULL),
    (2,NULL,2),
    (3,1,2)

如果col2在您的注释中是2或null,那么您需要使用is null

select * from table where col1=1 and col2 IS NULL
或者将空值转换为其他未使用的值

select * from table where col1=1 and ISNULL(col2, 0) != 2

对我来说,这些列应该是位字段

它可以通过使用示例数据分别检查每个查询谓词的结果来帮助您理解。请注意,由于AND逻辑运算符的存在,要返回行,这两个条件的计算结果都必须为TRUE

select * from Test where col1=1 and col2 = 2;

 VALUES 
    (1,1,NULL), --col1=1 is TRUE and col2 = 2 is UNKNOWN
    (2,NULL,2), --col1=1 is UNKNOWN and col2 = 2 is TRUE
    (3,1,2)     --col1=1 is TRUE and col2 = 2 is TRUE: row returned because both are TRUE

select * from table where col1=1 and col2 <> 2
 VALUES 
    (1,1,NULL), --col1=1 is TRUE and col2 <> 2 is UNKNOWN
    (2,NULL,2), --col1=1 is UNKNOWN and col2 <> 2 is FALSE
    (3,1,2)     --col1=1 is TRUE and col2 <> 2 is FALSE

无论是否为null,这些查询都将工作。只是涉及null的比较运算符将返回unknown,而不是true或false,因此结果可能不像您预期的那样。添加您所说的“查询不起作用”的确切含义。如果添加示例数据和预期结果,可能会有所帮助。第一个查询返回正确的行数。第二个查询要么返回零行,但我知道有许多行实际上满足查询。在表中,col2要么有一个2,要么有一个null。col1中有1或null。添加带有INSERT语句的CREATE TABLE,以便更好地帮助您。好的,我添加了将创建一个表,然后向其中插入3行的sql。是的,col2是2或null。但是col1要么是1,要么也是null。那么,为什么我必须在第二个查询中使用ISNULL,而在第一个查询中不必使用它呢?
select * from Test where col1=1 and col2 = 2;

 VALUES 
    (1,1,NULL), --col1=1 is TRUE and col2 = 2 is UNKNOWN
    (2,NULL,2), --col1=1 is UNKNOWN and col2 = 2 is TRUE
    (3,1,2)     --col1=1 is TRUE and col2 = 2 is TRUE: row returned because both are TRUE

select * from table where col1=1 and col2 <> 2
 VALUES 
    (1,1,NULL), --col1=1 is TRUE and col2 <> 2 is UNKNOWN
    (2,NULL,2), --col1=1 is UNKNOWN and col2 <> 2 is FALSE
    (3,1,2)     --col1=1 is TRUE and col2 <> 2 is FALSE