Question

I have a SQL data calculation which is used as part of where clause to get bookings from calculated date at midnight.

My solution:

bookDate >= (SELECT DATEADD(dd, -7, DATEADD(dd, DATEDIFF(dd, 0, GETDATE()), 0)))

The original was:

bookDate >= DATEADD(dd, -7, GETDATE())

However it returns at calculated date + current time

Is there a alternative and far simpler approach to this?

Was it helpful?

Solution

This is a bit simpler.

bookDate >= DATEADD(dd, DATEDIFF(dd, 0, GETDATE()) - 7, 0)

In SQL Server 2008 and SQL Server 2012 you can use the date data type.

bookDate >= DATEADD(dd, -7, CAST(GETDATE() as DATE))

OTHER TIPS

The following will also work for 2005:

SELECT DATEADD(dd, -7, FLOOR(CAST(GETDATE() AS FLOAT)))

This works because SQL Server (and windows, for that matter) stores a date as a floating point, with the whole number representing the number of days is 01/01/1900, and the fraction part representing the time. The following is shorter, and more consistent with what I usually use in this situation:

SELECT FLOOR(CAST(GETDATE() AS FLOAT) -7)

DATEADD is useful if you're calculating on something other than days (i.e. months, years), because of the varying number of days is each given month or year. When working with days, it's often easier to add or subtract directly. Similarly, if you wanted to subtract, for example, two hours from a date, you can use:

SELECT CAST(GETDATE() AS FLOAT) * 2.0/24.0

You could also do it like this:

bookDate >= CAST(CONVERT(char(8), GETDATE() ,112) as datetime)
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top