Query to check overlapping ranges in sql server?

后端 未结 2 1600
执念已碎
执念已碎 2020-12-31 23:30

I have my table as

   From_Range      ToRange
   1                999
   9000             10000
   2000             5000

When I try to inse

相关标签:
2条回答
  • 2021-01-01 00:13

    This works fine for me

    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
     )
    )
    
    0 讨论(0)
  • 2021-01-01 00:14

    The easiest way to find an overlap is like this:

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

    This can be shown to work if you compare the condition above against each of the bars in the diagram below:

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

    in all the overlap cases, both these tests are true:

    • the start date of the existing range is always before the end date of the new range
    • the end date of the existing range is after the start date of the new range

    Those that don't overlap fail one or other of this test.

    0 讨论(0)
提交回复
热议问题