7

我有我的桌子

   From_Range      ToRange
   1                999
   9000             10000
   2000             5000

当我尝试插入范围值 1000 - 3000 时,它应该会失败,因为此新范围内的某些值介于现有范围 2000 - 5000 之间。如何检查输入范围是否在现有范围内?

4

2 回答 2

26

找到重叠的最简单方法是这样的:

IF EXISTS (SELECT 1 FROM table WHERE @myValueLo <= ExistingRangeEnd AND @myValueHi >= ExistingRangeStart)
  -- Overlaps
ELSE
  -- Doesn't overlap

如果您将上述条件与下图中的每个条形进行比较,则可以证明这是有效的:

Existing range:         |-------------------|
Overlaps:       |-------------|       |------------|
                |----------------------------------|
                           |-------------|
Not overlaps:   |-----|                       |----|

在所有重叠情况下,这两个测试都是正确的:

  • 现有范围的开始日期总是在新范围的结束日期之前
  • 现有范围的结束日期在新范围的开始日期之后

不重叠的那些未通过此测试中的一项或多项。

于 2012-06-13T09:48:40.690 回答
0

这对我来说很好

DECLARE @From Decimal = 2000
DECLARE @TO Decimal =5000

SELECT COUNT(ID)
FROM TABLENAME
WHERE  
(
 (
 @From BETWEEN OPEN_HRS AND (CLOSE_HRS - 1) 
 OR 
 @TO BETWEEN (OPEN_HRS + 1) AND CLOSE_HRS 
 ) 
OR
 (
 OPEN_HRS BETWEEN @From AND (@TO - 1)
 OR 
 CLOSE_HRS BETWEEN (@From + 1) AND @TO
 )
)
于 2014-07-17T09:43:50.710 回答