SQL Server: Query overlapping time range

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

If A has room September 1 - September 10, 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 attempting to book August 30 - October 15;

2, is included: for example, the user attempts a reservation for 9 5 - 6 September;

3, the lower limit comprising: a user attempts Reserve e.g. August 30 - September 2;

4, the upper limit include: for example, a user attempting to book September 8 - October 15th.

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 '2011-09-01' AND '2011-09-10' OR endtime BETWEEN '2011-09-01' AND '2011-09-10' )

The correct wording is as follows:

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

 

It's only the four cases all the bases.
----------------
Original link: https: //blog.csdn.net/yishengreai/article/details/6865426

Guess you like

Origin www.cnblogs.com/luomingui/p/11684090.html