检查 SQL 中的日期是否重叠

Check if date is overlapping in SQL

我有一个 table tblBranchTimingEntry

+---------------+-------------------------+-------------------------+------------------+
| BranchEntryID |        fromDate         |         toDate          |     SundayIn     |
+---------------+-------------------------+-------------------------+------------------+
|            24 | 2015-01-01 00:00:00.000 | 2015-01-31 00:00:00.000 | 12:00:00.0000000 |
|            24 | 2015-02-01 00:00:00.000 | 2015-02-15 00:00:00.000 | 12:00:00.0000000 |
|            24 | 2015-03-01 00:00:00.000 | 2015-03-31 00:00:00.000 | 00:00:00.0000000 |
|            24 | 2014-01-01 00:00:00.000 | 2014-12-31 00:00:00.000 | 00:00:00.0000000 |
+---------------+-------------------------+-------------------------+------------------+

要求

我正在输入 BranchEntryID、fromDate、toDate,我想检查 fromDate 和 toDate 之间的任何日期是否与存储在 tblBranchTimingEntry 中的日期范围重叠。


到目前为止我做了什么

我有这个问题

SELECT 
        * 
    FROM
        [dbo].[tblBranchTimingEntry] 

    WHERE
        BranchEntryId = 24
    AND
        ('2015-01-14' BETWEEN fromDate AND toDate OR '2015-02-28' BETWEEN fromDate AND toDate)

这将检查重叠。


问题

只有当输入日期介于数据库中存在的日期之间时,这才有效。 在此示例中,这将失败。

假设我将 fromdate 和 todate 指定为“2015-02-16”和“2015-08-27”, 此查询不会 return 任何内容。但是这些日期之间有重叠的日期。

有什么解决办法吗?

试试这个逻辑:

SELECT te.* 
FROM [dbo].[tblBranchTimingEntry]  te
WHERE BranchEntryId = 24 AND
      '2015-01-14' < toDate AND
      '2015-02-28' > fromDate;

根据您所说的 "overlapping" 的意思,可能是 <= and/or >=.

逻辑是:两个日期范围重叠是第一个开始在第二个结束之前,第一个结束在第二个开始之后。

试试这个:

SELECT 
        * 
FROM
        [dbo].[tblBranchTimingEntry]
WHERE
    BranchEntryId = 24
AND
    (('2015-01-14' < toDate AND
  '2015-01-14' > fromDate) or ('2015-02-28' > fromDate and '2015-02-28' < toDate) or ('2015-02-28' > toDate AND
  '2015-01-14' < fromDate))

这样你就可以检查是否有任何日期在 fromDate 和 ToDate 之间