Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Compare dates in T-SQL, ignoring the time part

I'm using MS SQL 2005, and I want to check two dates for equality, but ignoring the time part.

I know I can make use of DATEDIFF, but am concerned that it may be slow - this SP gets used in the DB a lot!

Any suggestions?

Edit: David Andres' comment:

'"comparison" includes much more than equality'
made me realise that I didn't make my question clear enough - I am actually just checking for equality, that is all.
like image 380
Fiona - myaccessible.website Avatar asked Sep 15 '09 14:09

Fiona - myaccessible.website


People also ask

How can compare date without time in SQL?

To compare dates without the time part, don't use the DATEDIFF() or any other function on both sides of the comparison in a WHERE clause. Instead, put CAST() on the parameter and compare using >= and < operators.

Can we compare date with datetime in SQL?

The right way to compare date only values with a DateTime column is by using <= and > condition. This will ensure that you will get rows where date starts from midnight and ends before midnight e.g. dates starting with '00:00:00.000' and ends at "59:59:59.999".


2 Answers

The most reasonable way to do this is to strip away the time portion of the datetime values and compare the results, and the best way to strip the time portion from a datetime is like this:

cast(current_timestamp as date)     

I used to use and advocate a process that looked like one of the following two lines:

cast(floor(cast(getdate() as float)) as datetime) dateadd(dd,0, datediff(dd,0, getDate())) 

But now that Sql Server has the Date type, which does not hold a time component, there is little reason to use either of those techniques.

One more thing to keep in mind is this will still bog down a query if you need to do it for two datetime values for every row in a where clause or join condition. If possible you want to factor this out somehow so it's pre-computed as much as possible, for example using a view or computed column.

Finally, note the DATEDIFF function compares the number of boundaries crossed. This means the datediff in days between '2009-09-14 11:59:59' and '2009-09-15 00:00:01' is 1, even though only 2 seconds has elapsed, but the DATEDIFF in days between '2009-09-15 00:00:01' and '2009-09-15 11:59:59' is still zero, even though 86,398 seconds elapsed. It doesn't really care at all about the time portion there, only the boundaries. Depending on what your query is trying to do, you might be able to use that to your advantage.

like image 60
Joel Coehoorn Avatar answered Sep 27 '22 22:09

Joel Coehoorn


WHERE DATEDIFF(day, date1, date2)=0

like image 23
pete Avatar answered Sep 27 '22 22:09

pete