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
精彩评论