1

Why is it that each of the following returns records:

SELECT Name, CreatedDate 
FROM EmployeeTable 
WHERE CreatedDate < '20151214'

SELECT Name, CreatedDate 
FROM EmployeeTable 
WHERE CreatedDate > '20151214'

While the following query doesn't?

SELECT Name, CreatedDate 
FROM EmployeeTable 
WHERE CreatedDate = '20151214'

I had to use a CAST with the equality operator to get the results I wanted:

SELECT Name, CreatedDate 
FROM EmployeeTable 
WHERE CAST(CreatedDate as DATE) = '2015-12-14'

Is there any way to use the equality operator without having to use a cast?

CreatedDate is of type DATETIME, and includes times.

4

2 回答 2

7

可能CreatedDate包含时间部分(例如类型为datetime)。这就是为什么=它不能开箱即用。当您将其投射到date时间部分时,该部分被删除,然后=比较工作正常。

于 2015-12-14T17:43:22.757 回答
1

DATEDIFF是在 SQL 中检查日期相等性的首选方法,除非您使用较新的DATE类型(而不是DATETIME)。

投射到DATE删除任何时间部分。

DATEDIFF可能也更健壮(比<>=)

于 2015-12-14T17:45:51.620 回答