繁体   English   中英

检查约束不按照SQL Server中定义的条件工作

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

我有一张表aa(id int, sdate date, edate date, constraint chk check(sdate<= enddate) 。对于一个特定的id我必须检查重叠的日期。那就是我不想任何人插入a的数据重叠的日期的Perticular ID,因此我需要检查以下情况-

  1. 如果@id = id和(@sdate> = edate或@edate <= sdate),则允许插入

  2. 如果@id = id和(@sdate <edate或@edate> sdate),则不允许插入

  3. 如果@id <> id然后允许插入

我已经将上述逻辑封装在一个函数中,并在检查约束中使用了该函数。 功能运行正常,但检查约束不允许我输入任何记录。 我不知道为什么-下面提到了我的功能和约束:

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中插入任何值时,出现以下错误-

“消息547,级别16,状态0,第1行,I​​NSERT语句与CHECK约束” aa_ck“发生冲突。该冲突在数据库” tempdb“的表” dbo.aa“中发生。该语句已终止。”

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

--

我认为您的逻辑是错误的。 两行重叠

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 但是,检查重叠取决于两个端点。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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