Comparing two dates minutes in sql server

What I'm trying to do is comparing a DateTime variable and a date inside a table in sql server if the the differece between those two date are less than 30 min the select query will return some values I'm using c# to send the DateTime variable

string query = "Select * from LoginAttempts where IP_ADDRESS='" + Ipadress + "' and ATTEMPTS<"+MaxLoginAttempts+" and (GETDATE()-LOGIN_DATE)<30";

and (GETDATE()-LOGIN_DATE)<30 I know this is a wrong statement but how should I fix it?

Jon Skeet
people
quotationmark

Firstly, stop building your SQL dynamically like that. Use parameterized SQL instead.

Next, I think you just want DATEADD. If you know that LOGIN_DATE will always be in the past, you just need to add 30 minutes to that, and check that the result is later than GETDATE() - or equivalently, subtract 30 minutes from now and check that LOGIN_DATE is later than the result:

string query = @"Select * from LoginAttempts where IP_ADDRESS=@IPAddress'
                 and ATTEMPTS < @MaxLoginAttempts
                 and LOGIN_DATE > DATEADD(minute, -30, GETDATE())";
// Then fill in the parameters in the SqlCommand

As noted in comments, applying DATEADD to GETDATE() instead of to LOGIN_DATE allows more optimization, because it only needs to be performed once instead of once for each row, and allows any index on LOGIN_DATE to be effective.

You can use DATEDIFF instead in this case, but it's worth being aware that DATEDIFF doesn't always do exactly what you might expect it to, as it's about "boundary crossings". Not much of an issue here, but it means that the difference between (say) September 1st and August 31st is 1 month, as is the difference between September 30th and August 1st.

In this case the impact would just be that (say) 10:00:59 and 10:30:00 would be seen as 30 minutes, despite them only being just over 29 minutes apart... whereas the difference between 10:00:00 and 10:29:59 would also be 29 minutes despite being very nearly 30 minutes apart. So you'd be slightly inconsistent in terms of real elapsed time.

people

See more on this question at Stackoverflow