简体   繁体   中英

check constraint not working as per the condition defined in sql server

I have a table aa(id int, sdate date, edate date, constraint chk check(sdate<= enddate) . For a particular id I have to check for overlapping dates. That is I do not want any one to insert data of a perticular id which has overlapping dates. So i need to check the below conditions -

  1. if @id = id and (@sdate >= edate or @edate <= sdate) then allow insert

  2. if @id = id and (@sdate < edate or @edate > sdate) then do not allow insert

  3. if @id <> id then allow inserts

I have encapsulated the above logic in a function and used that function in check constraint. Function is working fine but check constraint is not allowing me to enter any records. I do not know why - my function and constraint are mentioned below :

alter function fn_aa(@id int,@sdate date,@edate date)
returns int
as
begin
declare @i int
if exists (select * from aa where id = @id and (@sdate >= edate or @edate <= sdate)) or not exists(select * from aa where id = @id)
begin
set @i = 1
end
if exists(select * from aa where id = @id and (@sdate < edate or @edate < sdate)) 
begin
set @i = 0
end
return @i
end

go

alter table aa
add constraint aa_ck check(dbo.fn_aa(id,sdate,edate) = 1)

Now when I try to insert any value in the table aa I get the following error -

"Msg 547, Level 16, State 0, Line 1 The INSERT statement conflicted with the CHECK constraint "aa_ck". The conflict occurred in database "tempdb", table "dbo.aa". The statement has been terminated."

Function is returning value 1 but constraint is not allowing to insert data. Can some one help me here. I am trying for last 2 hours but cannot understand what am i doing wrong?

-

I think your logic is wrong. Two rows overlap

alter function fn_aa(@id int,@sdate date,@edate date)
returns int
as
begin
    if exists (select *
               from aa
               where id = @id and
                     @sdate < edate and @edate > sdate
              )
    begin
        return 0;
    end;
    return 1;
end;

Your version would return 1 when either of these conditions is true: @sdate >= edate or @edate <= sdate . However, checking for an overlap depends on both end points.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM