SQL Server 2005 - 检查空日期时间值

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1632606/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-01 04:10:52  来源:igfitidea点击:

SQL Server 2005 - Check for Null DateTime Value

sqlsql-serversql-server-2005tsql

提问by user70192

I'm trying to count the number of records that have a null DateTime value. However, for some reason, my attempts have failed. I have tried the following two queries without any luck:

我正在尝试计算具有空 DateTime 值的记录数。但是,由于某种原因,我的尝试失败了。我尝试了以下两个查询但没有任何运气:

SELECT COUNT(BirthDate) 
  FROM Person p
 WHERE p.BirthDate IS NULL

and

SELECT COUNT(BirthDate)
  FROM Person p
 WHERE p.BirthDate = NULL

What am I doing wrong? I can see records with a BirthDate of NULL when I query all of the records.

我究竟做错了什么?当我查询所有记录时,我可以看到 BirthDate 为 NULL 的记录。

回答by Joel Coehoorn

SELECT COUNT(*)
FROM Person
WHERE BirthDate IS NULL

回答by gbn

All answers are correct, but I'll explain why...

所有答案都是正确的,但我会解释为什么......

COUNT(column) ignores NULLs, COUNT(*) includes NULLs.

COUNT(column) 忽略 NULL,COUNT(*) 包括 NULL。

So this works...

所以这有效...

SELECT COUNT(*)
FROM Person
WHERE BirthDate IS NULL

回答by Raj More

This is happening because you are trying to do a COUNT on NULL. I think that if you check the messages tab, you may have a message there saying NULL values eliminated from aggregate

发生这种情况是因为您正在尝试对 NULL 进行 COUNT。我认为如果您检查消息选项卡,您可能会收到一条消息说NULL values eliminated from aggregate

What you have to change is the field that you are counting

你必须改变的是你正在计算的领域

Select Count (1) FROM Person WHERE BirthDate IS NULL

Select Count (1) FROM Person WHERE BirthDate IS NULL

Select Count (*) FROM Person WHERE BirthDate IS NULL

Select Count (*) FROM Person WHERE BirthDate IS NULL

Select Count (1/0) FROM Person WHERE BirthDate IS NULL

Select Count (1/0) FROM Person WHERE BirthDate IS NULL

Select Count ('duh') FROM Person WHERE BirthDate IS NULL /* some non null string*/

Select Count ('duh') FROM Person WHERE BirthDate IS NULL /* some non null string*/

回答by Fredou

try this

尝试这个

SELECT     COUNT(*) 
FROM     Person p
WHERE     p.BirthDate IS NULL

回答by MattB

You need to use "IS NULL" not "= NULL"

您需要使用“IS NULL”而不是“= NULL”

SELECT
  COUNT('')
FROM
  Person p
WHERE
  BirthDate IS NULL