Detect overlapping date ranges from the same table

前端 未结 9 1146
甜味超标
甜味超标 2020-12-01 04:26

I have a table with the following data

PKey  Start       End         Type
====  =====       ===         ====
01    01/01/2010  14/01/2010  S
02    15/01/2010         


        
9条回答
  •  暖寄归人
    2020-12-01 04:47

    We've all needed this kind of overlapping predicate in our queries for quite some time and I think I've found a really simple solution here.

    In my application, as an example, I have policies that have the same Policy Number but maybe the Policy Description changes from one fiscal year to the next. When a user is entering a new record (same Policy Number, different Policy Description), I needed a way to tell if that policy already exists for the specified time range. If the new Policy Effective/Expiration dates overlap with whatever is already in the database, I needed to error out and tell the user why their input was not correct.

    To do this, I went with the following predicate statement:

    AND @_expiration >= EffectiveDate AND ExpirationDate >= @_effective
    

    Hopefully someone else finds this as useful as I have.

提交回复
热议问题