Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

I am not sure why the dateadd function is not working here. I am trying to pull only the last 24 hours from current time but i see hours like 3-6 pm of today's date. the data type is datetime but i am not sure what is going on here.

select Name, location, myDate from myTable where myDate >= DATEADD(hh, -24, GETDATE())

when i run the query above the outcome will include this:

2015-03-05 15:00:00.000
2015-03-05 15:30:00.000
2015-03-05 16:00:00.000
2015-03-05 16:30:00.000
2015-03-05 17:00:00.000
2015-03-05 17:30:00.000
2015-03-05 18:00:00.000
2015-03-05 18:30:00.000
2015-03-05 19:00:00.000
2015-03-05 19:30:00.000
2015-03-05 20:00:00.000
2015-03-05 20:30:00.000
2015-03-05 21:00:00.000
2015-03-05 21:30:00.000
2015-03-05 22:00:00.000
2015-03-05 22:30:00.000
2015-03-05 23:00:00.000
2015-03-05 23:30:00.000

I was expecting not to see these hours at all.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
171 views
Welcome To Ask or Share your Answers For Others

1 Answer

Use BETWEEN, ie

select Name, location, myDate from myTable where myDate between DATEADD(hh, -24, GETDATE()) and GETDATE()

This myDate >= DATEADD(hh, -24, GETDATE()) gets you all records where myDate is greater than 24 hours ago, including records that have future dates(if they are correct to have future dates is another story...)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...