检查约束不符合sql server中定义的条件

时间:2016-01-29 11:59:50

标签: sql sql-server

我有一张桌子aa(id int, sdate date, edate date, constraint chk check(sdate<= enddate)。对于特定的ID,我必须检查重叠日期。那就是我不希望任何人插入具有重叠日期的特定id的数据。所以我需要检查以下条件 -

  1. 如果@id = id和(@sdate&gt; = edate或@edate&lt; = sdate),则允许插入

  2. 如果@id = id和(@sdate&lt; edate或@edate&gt; sdate)则不允许插入

  3. 如果@id&lt;&gt; id然后允许插入

  4. 我在函数中封装了上述逻辑,并在check约束中使用了该函数。功能正常,但检查约束不允许我输入任何记录。我不知道为什么 - 我的功能和约束如下所述:

    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)
    

    现在当我尝试在表aa中插入任何值时,我收到以下错误 -

    &#34; Msg 547,Level 16,State 0,Line 1 INSERT语句与CHECK约束冲突&#34; aa_ck&#34;。冲突发生在数据库&#34; tempdb&#34;,table&#34; dbo.aa&#34;中。 该声明已被终止。&#34;

    函数返回值1但约束不允许插入数据。有人可以帮助我吗?我正在尝试最后2个小时,但无法理解我做错了什么?

    -

1 个答案:

答案 0 :(得分:0)

我认为你的逻辑错了。两行重叠

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;

如果满足以下任一条件,您的版本将返回1:@sdate >= edate@edate <= sdate。但是,检查重叠取决于两个端点。