SQL Server 2005 - 检查Null DateTime值

时间:2009-10-27 18:01:37

标签: sql sql-server sql-server-2005 tsql

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

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

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

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

5 个答案:

答案 0 :(得分:28)

SELECT COUNT(*)
FROM Person
WHERE BirthDate IS NULL

答案 1 :(得分:15)

所有答案都是正确的,但我会解释原因......

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

所以这有效......

SELECT COUNT(*)
FROM Person
WHERE BirthDate IS NULL

答案 2 :(得分:4)

试试这个

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

答案 3 :(得分:4)

这种情况正在发生,因为您尝试在NULL上执行COUNT。我认为,如果您查看邮件标签,则可能会在其中显示NULL values eliminated from aggregate

的消息

您需要更改的是您正在计算的字段

Select Count (1) 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 ('duh') FROM Person WHERE BirthDate IS NULL /* some non null string*/

答案 4 :(得分:1)

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

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