简体   繁体   English

使用IN条件对新表的检查约束未按预期工作

[英]Check constraint on new table using an IN condition is not working as expected

I have created a new table that included a check constraint using an in clause to create a list of allowed entries, or at least that was the plan. 我创建了一个新表,其中包含一个检查约束,该约束使用in子句创建允许条目的列表,或者至少是计划。 The create table command executed without error however in testing I am able to insert rows without the constraint preventing incorrect values for the column "CAUSE" 执行创建表命令时没有错误,但是在测试中我能够插入行而没有约束,从而防止了“ CAUSE”列的值不正确

I have done a bit of internet reasearch but I have not figured this one our yet. 我做了一些互联网研究,但我还没有想到这一点。 I will include the create table statement bellow. 我将在下面包含创建表语句。

''' '''

USE TEST 
GO

CREATE TABLE EMP_POINTS (
ROWID int NOT NULL IDENTITY(1,1),
WEEK_ID nvarchar(15) NOT NULL,
EMPLOYEE_ID nvarchar(15) NOT NULL,
DATE date NOT NULL,
CAUSE nvarchar(15),
POINTS decimal(2,1),

PRIMARY KEY(EMPLOYEE_ID, DATE),
CONSTRAINT FK_EmpID FOREIGN KEY(EMPLOYEE_ID) REFERENCES EMPLOYEE(ID),
CONSTRAINT chk_cause CHECK (
                            CAUSE IN('Late In','Early Out','E & L', 'NCNS', 'Absent', '0.5','1.0', NULL)
                           )
);

''' '''

I would expect that the only values which would be allowed in the CAUSE column would be the ones identified in the chk_cause constraint however it is allowing any values to be entered. 我希望“原因”列中唯一允许的值是chk_cause约束中标识的值,但是它允许输入任何值。

CHECK constraints are different from WHERE and CASE conditions. CHECK约束与WHERECASE条件不同。 A CHECK constraint only fails when the result is explicitly false. 仅当结果显式为 false时, CHECK约束才会失败。 The others require that the condition is explicitly true. 其他要求条件明确为真。 The difference is how NULL values are handled. 区别在于如何处理NULL值。

So, you can write your constraint as: 因此,您可以将约束写为:

CONSTRAINT chk_cause CHECK (CAUSE IN('Late In', 'Early Out', 'E & L', 'NCNS', 'Absent', '0.5', '1.0')
                           )

Then, only these values and NULL will be allowed (assuming CAUSE is not declared NOT NULL ). 然后,仅允许使用这些值 NULL (假设未将CAUSE声明为NOT NULL )。

The problem with your version is that other values will result in NULL (due to the NULL in the IN list). 您的版本的问题是其他值将导致NULL (由于IN列表中的NULL )。 And that passes the CHECK constraint. 并通过了CHECK约束。

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

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