Link to home
Start Free TrialLog in
Avatar of uripapuk
uripapukFlag for United States of America

asked on

How to measure time since midnight in SQL query

We have simple problem.
A MS SQL stored procedure will be executed any day arround 1:0am (+/- 10 minutes). The stored procedure will perform simple math and statistic on data from particular table. For simplicity let us assume that it will calculate average value of record accumulated in a table.
The average value will be calculated for data in predetermined time frame : from 0:01am till 24:59pm for the previous day (in essence average for this values for yesterday).
Since we do not know when exactly the SQL query will run, we do not know the time different between midnight and the time when the SQL query runs.

The questions is: how can we refer to yesterday day as start time and end time?
My existing query is:

SET NOCOUNT ON
DECLARE @StartDate DateTime
DECLARE @EndDate DateTime
SET @StartDate = DateAdd(hh,-24,GetDate())
SET @EndDate = GetDate()

After this line the query continues with actual data extraction and manipulation - finding average.

The @StartDate is already set to Midnight at two days ago ( the midnight before the last one). The @EndDate shall be the time of the most recent Midnight.

Question: how do we set the @EndDate to be the time of the most recent Midnight??
Avatar of Steve Wales
Steve Wales
Flag of United States of America image

Most recent midnight:

declare @EndDate datetime
set @EndDate = dateadd(dd, datediff(dd, 0, getdate())+0, 0)

If you want 23:59:59 of the one second before that you can subtract a second:

set @EndDate = dateadd(ss, -1, @EndDate)
Avatar of uripapuk

ASKER

This solution seems to be correct.
I have one clarifying question.

Since my statement is "SET @StartDate = DateAdd(hh,-24,GetDate())" does this means that am extracting only the date portion of the date OR does this means that I am only making a time shift in units of hours from the precise current time (mm,dd,yy) ??

What I like to make sure is that my EndDate is most recent midnight with precision up to 1 second AND my StartDate is the time of the midnight before the last one (midnight a day ago) with precision up to 1 second.

Would you please clarify.
ASKER CERTIFIED SOLUTION
Avatar of Steve Wales
Steve Wales
Flag of United States of America image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
The expert responded promptly and in detail on all questions asked. The solution proposed was tested and confirmed working as required.