SQL 服务器查询在 where 子句中包含 null

SQL Server query include null in where clause

我有以下格式的 table。我正在尝试查询此 table 以获取所有不是 PC 和 PT 的记录。

所以我的查询应该 return ID 3,4,5,6,7 并且应该忽略 1 和 2

    CREATE TABLE #t (ID INT, V VARCHAR(16))

    INSERT  INTO #t
    VALUES  (1, 'PC'),
            (2, 'PT'),
            (3, NULL),
            (4, NULL),
            (5, NULL),
            (6, 'PS'),
            (7, 'PD');

drop table #t

我正在使用的查询是 return 只有 6 和 7 并忽略结果集中的空记录。:

select 
    id, v 
from 
    #t 
where  
    v != 'PC' and V != PT

请告诉我应该怎么做才能在我的结果集中包含 null?

select id , v from #t where  v!='PC' and V!=PT or OR V IS NULL

一切顺利。请也添加 null 条件

select id , v from #t where  v not in ('PC' , 'PT') and v is null 

使用not in它将return除PC和PT之外的所有行

不是对每个条件都使用 !=,而是使用 not in,对于处理空值,使用 isnull

select 
  id, v 
from 
  #t 
where  
  isnull(v,'') not in ('PC', 'PT')

您的查询也应该检查空条件。

查询 -

select id , v from #t where  v not in ('PC' , 'PT') OR v is null