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