开发者

Querying datetime columns for 'Now' minus a certain amount of time?

Is there a way in TSQL to query for开发者_运维问答 rows where a datetime column's value is "now minus (a certain amount of time)" to select a time range?

For example in MySQL I could build this predicate like:

(EndTime BETWEEN NOW() - INTERVAL 2 DAY AND NOW())

How can this be done in TSQL in SQL Server?


You would use the dateadd function, e.g.

where endtime between dateadd(day, -2, getdate()) and getdate()

Because the column endtime is not a function parameter, the query optimizer can use any indexes that might be defined on it (the definition of sargable).


If you are trying to subtract two days from today, you can do

DateAdd( d, -2, CURRENT_TIMESTAMP)

DATEADD (Transact-SQL)


You can use the datediff function.

For example, to find things created within the last five minutes, you could execute

select *
from   Table t
where  datediff(minute, t.CreationDate, getutcdate()) <= 5
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜