Unique date range fields in SQL Server 2008

后端 未结 3 443
情歌与酒
情歌与酒 2021-01-01 02:10

I have a table that consists of, among other things, two fields named StartTime and EndTime. Both are TIME fields.

I want to add a constraint preventing the insertio

相关标签:
3条回答
  • 2021-01-01 02:45

    This trigger will also work for situations where one timespan completely contains the other. For example, if there's an existing record for 6:00 - 9:00 and you try to insert one for 5:00 - 10:00.
    (Based on David Hall's answer)

    CREATE TRIGGER DateRangeOverlapTrigger
    ON  TargetTable
    FOR INSERT, UPDATE
    AS 
    BEGIN
    IF EXISTS
        (SELECT t.UniqueId
        FROM TargetTable t
            JOIN inserted i ON i.starttime < t.endtime
                AND i.endtime > t.starttime
                AND i.UniqueId <> t.UniqueId)
    BEGIN
        RAISERROR ('Invalid due to time overlap', 16, 1)
        IF (@@TRANCOUNT > 0)
            ROLLBACK
    END
    END
    
    0 讨论(0)
  • 2021-01-01 02:50

    I haven't tried it but I imagine something like this would work:

    create trigger preventOverlaps
    on infotable
    FOR Insert, Update
    As
    DECLARE @Count int;
    select @Count = count(*) from infotable where 
      (inserted.startdate > startDate && inserted.startdate < endDate) ||
      (inserted.endDate < endDate && inserted.endDate > startDate)
    if(@Count > 0)
    begin
       rollback transaction;
    end
    
    0 讨论(0)
  • 2021-01-01 02:51

    The trigger below should work - it is also possible to do this with check contraints, but the logic shown in this post kind of hurts my head.

    CREATE TRIGGER [dbo].[DateRangeTrigger]
       ON  [dbo].[TargetTable]
       FOR INSERT, UPDATE
    AS 
    BEGIN
    
    IF EXISTS (SELECT t.starttime, t.endtime FROM TargetTable t
            Join inserted i
            On (i.starttime > t.starttime AND i.starttime < t.endtime AND i.UniqueId <> t.UniqueId) 
               OR (i.endtime < t.endtime AND i.endtime > t.starttime AND i.UniqueId <> t.UniqueId)
               OR (i.starttime < t.starttime AND i.endtime > t.endtime AND i.UniqueId <> t.UniqueId)
            )
    BEGIN
        RAISERROR ('Inserted date was within invalid range', 16, 1)
        IF (@@TRANCOUNT>0)
            ROLLBACK
    END
    
    
    END
    
    0 讨论(0)
提交回复
热议问题