Question

select * from table
where Date BETWEEN DATEADD(dd, DATEDIFF(dd, 84, GETDATE()),0)
and DATEADD(dd, DATEDIFF(dd, 77, GETDATE()),0)

Can someone please explain what this query is doing? Specifically, what is the function of DATEADD and DATEDIFF in this query?

Was it helpful?

Solution

They're trying to get the membership renewals between 84 and 77 days ago, stripping out the time.

GETDATE() returns the datetime but the user isn't interested in the time.

DATEDIFF(dd, 84, GETDATE()) gets the number of days between the current date and the 84th day after Jan 1, 1900.

DATEADD(dd, # days from above, 0) adds those number of days to Jan 1, 1900.

The net is you get 84 days ago at 00:00:00 AM.

If you just did DATEADD(dd, -84, GETDATE()) then you'd have 84 days ago + the current time.

Other ways to do the same thing are to cast the datetime to a date (assuming MS SQL Server).

.. CAST((GETDATE() - 84) AS DATE)
.. CAST(DATEADD(day, -84, GETDATE()) as DATE)

OTHER TIPS

Your expression is using SQL Server syntax to convert a datetime to a date (that is, to remove the date component. The format is quite arcane, because the expression is doing getdate() - 84 as an integer and then adding this to the 0 date. The elimination of the "time" component occurs because the datediff() returns an integer.

I don't think this will work in HQL. For instance, the dd should be 'dd' and HQL has a different method of getting the current date.

And, in more recent versions of SQL Server, you can just do cast(getdate() - 84 as date).

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top