sql中区间不能有重叠的检测方法:

--sql中区间不能有重叠的检测方法:

--常规方法:
--check time period overlapping
if (  exists(select 1 from test_tb where  starttime <= @v_starttime and stoptime >= @v_starttime   ) or 
      -- v_start不能落入已有区间
      exists(select 1 from test_tb where  starttime <= @v_stoptime and stoptime >= @v_stoptime  ) or    
      -- v_stop不能落入已有区间
      exists(select 1 from test_tb where  starttime>=@v_starttime and starttime <= @v_stoptime ) or     
      -- 所有的start不能落入 v_start 和 v_stop区间
      exists(select 1 from test_tb where  stoptime >=@v_starttime and stoptime <= @v_stoptime )         
      -- 所有的stop不能落入 v_start 和 v_stop区间
   )
begin
   select 6001 --time overlaps
   return
end

--简化方法:
--上面后面两个可以简化为: 新的区间 不能包含任何已有区间,
--即 v_start 和 v_stop 形成的新区间 不能包含任何已有区间(这种情况是符合12两种情况的)34情况简化为:
starttimp >= @v_starttime and stoptime <= @v_stoptime

--check time period overlapping
if (  exists(select 1 from test_tb where  starttime <= @v_starttime and stoptime >= @v_starttime   ) or 
      -- v_start不能落入已有区间,条件1
      exists(select 1 from test_tb where  starttime <= @v_stoptime and stoptime >= @v_stoptime  ) or    
      -- v_stop不能落入已有区间,条件2
      exists(select 1 from test_tb where  starttimp >= @v_starttime and stoptime <= @v_stoptime )       
      -- v_start 和 v_stop 形成的新区间 不能包含任何已有区间(这种情况是符合12两种情况的)
   )
begin
   select 6001 --time overlaps
   return
end


--已有区间:                 a1|_____________|b1       a2|_____________|b2 
--新区间:    new start |_________________________________________________________|new stop 
--包含了上面的已有区间(符合条件1,2,但是不符合条件3)

 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值