I have a project which involves comparing a datetime
field with the current date and time, and if the difference between them is 10 minutes, then I have to select some date. It involves complexity, like if the current date and time is a date greater than the field datetime
. Does anyone has a simple solution to this?
This can be done very simply using DATEDIFF
:
IF ( SELECT DATEDIFF(MINUTE, a.StartDate, GETDATE())
FROM TableA a) > 10
BEGIN
SELECT *
FROM TableB
END
This simply says that if the current time ( GETDATE()
) is more than 10 minutes past the StartDate
on TableA
, do something else.
Note that if a.StartDate
is greater than GETDATE()
(for whatever reason), the value of DATEDIFF
will be negative - in which case, you simply change the comparison to > -10
.
EDIT from comments:
I want all the serverID which all didnt run in the last 10 mins
This can be trivially accomplished with the following:
SELECT ServerID
FROM TableA
WHERE DATEDIFF(MINUTE, LastRunTime, GETDATE()) > 10
Here are a few "checks" you can do to see the behavior of DATEDIFF
- the comment regarding only caring about minutes is incorrect, but jumping to larger intervals DAY
, MONTH
, etc. does cause some interesting behavior.
For example:
SELECT DATEDIFF(MONTH, '05/30/2016 08:10:00', '06/01/2016 08:05:00')
Returns 1 (month), despite being only 2 days apart. Similarly,
SELECT DATEDIFF(DAY, '05/30/2016 08:10:00', '06/01/2016 08:05:00')
Returns 2, despite the time not quite making it to the 2-day mark. Finally,
SELECT DATEDIFF(YEAR, '12/31/2016 08:10:00', '01/01/2017 08:05:00')
Returns 1 as well.
Hopefully this helps in your understanding of using DATEDIFF
.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.