Please start any new threads on our new site at https://forums.sqlteam.com. We've got lots of great SQL Server experts to answer whatever question you can come up with.

 All Forums
 SQL Server 2008 Forums
 SQL Server Administration (2008)
 Compare date/time to GetDate()

Author  Topic 

robert693
Starting Member

42 Posts

Posted - 2010-10-04 : 10:42:39
Hello,

I would like to pull data from a table where the date/time field in the table equals today's date. The field also stores time data so that the data will have times as well as dates. I only need to compare the date part to see if it equals the date part of GetDate(). Do I use the Convert function to pull the date part of the Date/Time field and the GetDate() function? Thank you!

pk_bohra
Master Smack Fu Yak Hacker

1182 Posts

Posted - 2010-10-04 : 11:24:24
You need to remove the time part for date comparision.

dateadd(d,datediff(d,0,<Place column of your table here>),0) = dateadd(d,datediff(d,0,getdate()),0).


For SQL Server 2008 only:
CAST(@SomeDateTime AS Date)

There are many other methods to remove time part
http://mangalpardeshi.blogspot.com/2008/12/removing-time-from-datetime-column-in.html


Go to Top of Page

robert693
Starting Member

42 Posts

Posted - 2010-10-04 : 11:41:45
Thank you, a method at the site that you linked worked. Thank you for your help!
Go to Top of Page

pk_bohra
Master Smack Fu Yak Hacker

1182 Posts

Posted - 2010-10-04 : 14:17:57
You are welcome

I am here to learn from Masters and help new bees in learning.
Go to Top of Page

jeffw8713
Aged Yak Warrior

819 Posts

Posted - 2010-10-04 : 16:25:24
Be aware that the above approach will not allow for index usage - if an index is available on your datetime column. A better approach is to use an open interval range check:

WHERE datecolumn >= dateadd(day, datediff(day, 0, getdate()), 0)
AND datecolumn < getdate() -- or, you can use this: dateadd(day, 0, getdate()) + 1, 0)

If there is an index on the datecolumn, the above could use that index. If you use any function on the date column itself, then it is no longer SARGABLE and any index on that column cannot be used.

Jeff
Go to Top of Page
   

- Advertisement -