2015-02-23 77 views
3

重叠我有一个表tblBranchTimingEntry检查日期是在SQL

+---------------+-------------------------+-------------------------+------------------+ 
| 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) 

这将检查的重叠。


问题

如果输入日期落在目前在DB日期间这只会工作。 这个例子会失败。

假设我给日期和日期为'2015-02-16'和'2015-08-27', 此查询不会返回任何内容。但是这些日期之间有日期重叠。

ANy解决方案?

+0

的可能重复[确定是否两个日期范围重叠(HTTP://计算器的.com /问题/ 325933 /确定-是否-两日期范围,重叠) – Magnus 2015-02-23 12:20:34

回答

2

试试这个逻辑:

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

根据你所说的 “重叠”,可能是<=和/或>=什么。

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

1

试试这个:

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