SELECT *
FROM TableA AS A
JOIN TableB AS B
ON A.TTime BETWEEN B.DateTimeStart AND B.DateTimeEnd
Be aware that BETWEEN
is inclusive, meaning that it will return true if A.TTime
is the same as either B.StartDateTime
or B.EndDateTime
. If you want to get just the ones that truly fall between start and end you should use greater than >
and less than <
operators.
You should also be aware of accuracy on SQL Server, per MSDN, DateTime is
Rounded to increments of .000, .003, or .007 seconds
Running the following queries can help illustrate:
DECLARE @StartTime DATETIME = '2016-01-01 00:00:00.000',
@TestTime DATETIME = '2016-01-01 08:00:00.008', -- rounds down to .007
@EndTime1 DATETIME = '2016-01-01 08:00:00.007', -- stays the same
@EndTime2 DATETIME = '2016-01-01 08:00:00.006'; -- rounds up to .007
SELECT 'Eh? What just happened?'
WHERE @TestTime BETWEEN @Starttime AND @EndTime1;
SELECT 'What is going on!'
WHERE @TestTime BETWEEN @Starttime AND @EndTime2;