sql server - TSQL check constraint related to existing rows -
i have following table:
create table dbo.mytable] ( id1 [int] not null, id2 [int] not null, startdate smalldatetime not null, enddate smalldatetime null, constraint [pk_mytable1] primary key clustered (id1 asc, id2 asc, startdate asc) ) on [primary] i want ensure startdate enddate period each id1 , id2 unique, , there no overlap.
how create check constraint this:
( id1 <> existingrow.id1 or id2 <> existingrow.id2 ) or ( id1 = existingrow.id1 , id2 = existingrow.id2 , ( startdate >= isnull(existingrow.enddate, startdate + 1) or isnull(enddate, existingrow.startdate + 1) <= existingrow.startdate ) ) ...or constraint condition this:
if id1 = existingrow.id1 , id2 = existingrow.id2 check ( startdate >= isnull(existingrow.enddate, startdate + 1) or isnull(enddate, existingrow.startdate + 1) <= existingrow.startdate ) thanks in advance...
did try this?
create function dbo.fn_check_unique_value ( @id1 int, @id2 int, @startdate smalldatetime, @enddate smalldatetime ) returns int begin declare @result int set @result = (select count(*) dbo.mytable existingrow ( @id1 <> existingrow.id1 or @id2 <> existingrow.id2 ) or ( @id1 = existingrow.id1 , @id2 = existingrow.id2 , ( @startdate >= isnull(existingrow.enddate, @startdate + 1) or isnull(@enddate, existingrow.startdate + 1) <= existingrow.startdate ) )) return @result end go alter table dbo.mytable add constraint ck_no_overlap check ( dbo.fn_check_unique_value(id1, id2, startdate, enddate) <= 1 )
Comments
Post a Comment