Unique Date Range Fields in SQL Server 2008

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

I want to add a restriction that prevents the insertion of any records that overlap with existing time ranges. For example. if the record already exists with StartTime = 5:00, EndTime = 10:00, I would like the insert with StartTime = 6:00, EndTime = 9:00 to fail due to overlap.

Is there a way to accomplish this with or without triggers?

+5
source share
3 answers

- , , .

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
+4

, , :

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
+4

, . , 6:00 - 9:00, 5:00 - 10:00.
( )

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

All Articles