Kyle C
Kyle C

Reputation: 1637

Select most recent rows based on a DateTime field within 5 mins of current time

In a SQL Server table, I have a DateTime field and every time I have a login failure for an external web service I write the current DateTime to the table.

I currently have code that parses through the returns and determines if there are > 2 failures within 5 mins. If so I have a flag to turn off calling of the web service. I am curious if there is a way I can just use sql to return the number of rows that are within 5 mins from the current time?

Upvotes: 1

Views: 2097

Answers (2)

bobs
bobs

Reputation: 22184

You can try this

SELECT COUNT(*)
FROM MyTable
WHERE MyDateTimeField > DATEADD(mm, -5, GETDATE())

Upvotes: 2

This will return all records that are less than five minutes old:

SELECT [Columns]
FROM [YourTable]
WHERE [DateTimeField] >= dateadd(minute, -5, getdate())

You can get more information on DATEADD here .

Upvotes: 7

Related Questions