SQL Server 未列出具有 NULL 值的记录

Mid*_*C N 1 sql-server sql-server-2008-r2

我今天遇到了一个奇怪的现象。我运行以下查询以查找除 BROKER_RECEIVE_WAITFOR 以外的等待的所有请求

select * from sys.dm_exec_requests where session_id > 55 
and wait_type not like ('BROKER_RECEIVE_WAITFOR') 
Run Code Online (Sandbox Code Playgroud)

查询运行良好,但没有列出任何没有等待的请求,即 wait_type 为NULL(此时有相当多的正在运行的查询没有任何等待)。

为什么会发生这种情况,是不是应该列出所有具有 wait_type 的记录,而不是像“BROKER_RECEIVE_WAITFOR”这样的记录,包括空值?

我正在运行 SQL Server 2008R2 SP3。

Tom*_*m V 10

这样做的原因是 NULL 表示未知值。

NULL 不是LIKE任何东西,也不是NOT LIKE任何东西。

尝试在您的系统上运行以下 2 条语句:

SELECT CASE WHEN null like '%a%' THEN 'true' ELSE 'false' END;
SELECT CASE WHEN null not like '%a%' THEN 'true' ELSE 'false' END;
Run Code Online (Sandbox Code Playgroud)

这应该返回false两个语句。

所以你的查询应该是这样的:

select * from sys.dm_exec_requests where session_id > 55 
and (wait_type not like ('BROKER_RECEIVE_WAITFOR') or wait_type is null)
Run Code Online (Sandbox Code Playgroud)