且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

防止使用SQL触发器插入重叠的日期范围

更新时间:2023-02-05 08:23:06

两个小改动

首先,在触发器中添加where子句,以将重复的记录从联接中排除。这样您就不会将插入的记录与其自身进行比较:

First, add a where clause to your trigger to exclude the duplicate records from the join. Then you won't be comparing the inserted records to themselves:

select *
  from testdatetrigger t
   join inserted i
   on ((i.ValidTo >= t.ValidFrom) and (i.ValidFrom <= t.ValidTo))
  Where not (i.ValidTo=t.Validto and i.ValidFrom=t.ValidFrom)

除了,这将允许精确的重复范围,因此您必须在两列之间添加唯一约束。实际上,您可能希望在每一列上使用唯一的约束,因为默认情况下,同一天开始(或结束)的任何两个范围都是重叠的。

Except, this would allow for exact duplicate ranges, so you will have to add a unique constraint across the two columns. Actually, you may want a unique constraint on each column, since any two ranges that start (or finish) on the same day are by default overlapping.