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