Search code examples
sqlt-sqldatetimejoindate-comparison

How can I force TSQL to accept two dates EQUAL if there is only an n miliseconds difference?


I have two tables, table1 and table2.

And I join them by comparing a couple of columns and one of them is a Date column.

select *
from table1 t1 
INNER JOIN table2 t2 ON t1.HaloDate = t2.HaloDate

My question is I found that the join fails for comparison of 2 dates below:

'2011-07-23 14:01:32.113' and '2011-07-23 14:01:32.114'

is it possible to write this join by ignoring the miliseconds or by introducing a range like 5 milisecons as a tolerance range?

Thanks


Solution

  • Yes:

    select *
    from table1 t1 
    INNER JOIN table2 t2 
    ON t1.HaloDate between dateadd(ms,-5,t2.HaloDate) and dateadd(ms,5,t2.HaloDate)