m0fo
m0fo

Reputation: 2189

SQL checking DateTime difference

I have a datetime column and a stored procedure that should check the difference between the passed argument to the column's datetime.

Basically, I want to return the differences with more or less than 5 minutes.

For example, I have the following table:

ID | Date
----------
1  | 2013-07-20 10:00:00
2  | 2013-07-20 11:00:00
3  | 2013-07-20 10:01:00
4  | 2013-07-20 10:03:00

If the passed argument, for example, is "2013-07-20 10:02:00", the return value should be

1
3
4

Because they are all in the scope of the 5 minutes less or more than the passed argument.

Now the question is, how to?

Upvotes: 0

Views: 221

Answers (2)

Tim Schmelter
Tim Schmelter

Reputation: 460108

Use DATEDIFF:

SELECT * FROM dbo.Table1
WHERE ABS(DateDiff(minute,@date,Date))<=@diffMin

Demo

Upvotes: 1

gvee
gvee

Reputation: 17161

DECLARE @date datetime = '2013-07-20 10:02:00';

SELECT id
FROM   your_table
WHERE  date_field >= DateAdd(mi, -5, @date)
AND    date_field <  DateAdd(mi, +5, @date);

Upvotes: 3

Related Questions