Skip to content
Advertisement

Compare 2 time datatype

I have a table in SQL Server which has 2 columns StartTime AND EndTime. The datatype of both columns in time(7). So when I view data in the table it can look like this:

08:33:00.0000000

or

19:33:00.0000000

I want to return all the rows in the table where StartTime and EndTime conflicts with another row.

Example table TimeTable

RowID  StartTime           EndTime
1      08:33:00.0000000    19:33:00.0000000
2      10:34:00.0000000    15:32:00.0000000
3      03:00:00.0000000    05:00:00.0000000

Type of query I am trying to do:

SELECT * FROM TimeTable 
WHERE RowID = 1 
AND 
TimeTable.StartTime AND EndTime 
Falls in range
(SELECT * FROM TimeTable WHERE RowID <> 1)

Expected result:

2      10:34:00.0000000    15:32:00.0000000

Advertisement

Answer

You can use logic like this for at least a fraction of a second of overlap:

select tt.*
from timetable tt
where exists (select 1
              from tt2
              where tt2.rowid <> tt.rowid and
                    tt2.endtime > tt.starttime and
                    tt2.starttime < tt.endtime
             );
User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement