Comparing Datetime Values with Only Date in SQL Server
When querying database records with a comparison to a datetime value that includes only the date portion, it's crucial to understand the implications.
Issue
Consider the following SQL query:
Select * from [User] U where U.DateCreated = '2014-02-07'
If the user was created on '2014-02-07 12:30:47.220', the query will not return any data, as the comparison is performed strictly against the date portion only.
Solution
To correctly compare a datetime value with only the date, you should bracket it with the start and end of the day:
Select * from [User] U where U.DateCreated >= '2014-02-07' and U.DateCreated < dateadd(day,1,'2014-02-07')
This approach ensures that the query includes records created on the specified date, regardless of the time component.
Avoid Using Functions in the WHERE Clause
It's important to avoid using functions (such as convert) in the WHERE clause or join conditions for several reasons:
Don't Rely on BETWEEN Either
It's generally recommended to avoid using the BETWEEN operator for date and time comparisons. Instead, use the form:
WHERE col >= '20120101' AND col < '20120201'
This approach works consistently regardless of data type or precision, and it also avoids potential pitfalls with BETWEEN.
The above is the detailed content of How to Correctly Compare Datetime Values with Only Dates in SQL Server?. For more information, please follow other related articles on the PHP Chinese website!