SQL Server query time ranges overlap

To verify the data often encountered where there is an overlap ranges are conflicting, a typical scenario is room reservation.

If the room has a October 1 - October 10, the recording reservation, the reservation again when the other guest, the system must determine not overlap with the date range.

There are four cases will overlap:

1, all-inclusive: for example, a user attempts a reservation for 9 30 - October 15;

2, is included: for example, a user attempts to bookings of 10 5 - 6 October;

3, the lower limit comprising: a user attempt a reservation for 9 e.g. 30 - October 2;

4, the upper limit include: for example, a user attempts to bookings of 10 8 - 15 October.

When using SQL queries judgment, we need to take into account that all four cases, we often consider only two of the error wording like this:


`SELECT * FROM rooms WHERE ID=1 AND (starttime BETWEEN '2020-10-01' AND '2020-10-10' OR endtime BETWEEN '2020-10-01' AND '2020-10-10' )`

The correct wording is as follows:

SELECT *
  FROM ROOMS
 WHERE ID = 1
   AND (STARTTIME BETWEEN '2020-10-01' AND '2020-10-10' OR
       ENDTIME BETWEEN '2020-10-01' AND '2020-10-10' OR
       '2020-10-01' BETWEEN STARTTIME AND ENDTIME OR
       '2020-10-10' BETWEEN STARTTIME AND ENDTIME)

It's only the four cases all the bases.

Guess you like

Origin blog.51cto.com/11728495/2479243