检查约束不允许我添加数据

Check constraint not allowing me to add data

我有一个用户定义的函数,returns 一个 BIT。

我已经测试了 UDF,它似乎运行正常。

这是我添加的以下检查约束:

ALTER TABLE [Gizmo] WITH CHECK ADD CONSTRAINT [CK_DateOverlap]
CHECK [dbo].[MyUserFunction]([GizmoName],[GizmoState],[BeginDate],[EndDate]) = 0;

table里面没有任何数据。当我去插入一条新记录时,我得到了错误

The INSERT statement conflicted with the CHECK constraint

我手动调用 UDF 进行测试,它返回了 0。

如果 UDF returns a 0,我希望约束添加记录。如果 returns a 1,我不想添加它。

我错过了什么?

编辑 - UDF

ALTER FUNCTION [dbo].[MyUserFunction]
(
     @GizmoName AS VARCHAR(max),
     @GizmoState AS VARCHAR(max),
     @BeginDate AS DATETIME,
     @EndDate AS DATETIME

)

RETURNS BIT
AS
BEGIN
       DECLARE @Result BIT
       IF EXISTS(
                    SELECT *
                    FROM Gizmos
                    WHERE (@GizmoName = Name AND @GizmoState = [State])
                    AND (@EndDate >= EffectiveFrom AND EffectiveTo >= @BeginDate)
                    )
                    BEGIN
                        SET @Result = 1;
                    END
                    ELSE
                    BEGIN
                           SET @Result = 0;   
                    END
       RETURN @Result
END

插入

INSERT INTO Gizmos VALUES('XXX', 'CA', '1/1/2019', '12/31/2019');

该行已插入 table 并且约束应用于 table。所以数据已经可用,函数 returns 1 并且事务被回滚。所以我们需要忽略第一行,然后它会按你预期的那样工作。

CREATE OR ALTER FUNCTION [dbo].[MyUserFunction]
(
     @GizmoName AS VARCHAR(max),
     @GizmoState AS VARCHAR(max),
     @BeginDate AS DATETIME,
     @EndDate AS DATETIME

)

RETURNS BIT
AS
BEGIN
       DECLARE @Result BIT

       IF (SELECT COUNT(Name)
                    FROM Gizmos
                    WHERE (@GizmoName = Name AND @GizmoState = [State])
                    AND (@EndDate >= EffectiveFrom AND EffectiveTo >= @BeginDate)
                    ) > 1
                    BEGIN
                        SET @Result = 1;
                    END
                    ELSE
                    BEGIN
                           SET @Result = 0;   
                    END

                    RETURN @Result

END
GO