简体   繁体   English

我该如何编写这个约束?

[英]How Can I Write This Constraint?

The task is to write an alter query for general constraints.任务是为一般约束编写一个更改查询。 Specifically: "In Employee, if EmployeeLevel is NULL, then EmployeeSalary must also be NULL".具体来说:“在 Employee 中,如果 EmployeeLevel 为 NULL,则 EmployeeSalary 也必须为 NULL”。 If anyone could explain a correct solution, it would be much appreciated!如果有人可以解释正确的解决方案,将不胜感激!

ALTER TABLE Employee
ADD CONSTRAINT 
CHECK (
EmployeeLevel IS NULL
AND EmployeeSalary IS NULL
);

The statement "If employeeLevel is not null, then employeeSalary can be null" can be accepted.可以接受“如果employeeLevel不是null,则employeeSalary可以为null”的说法。 The "and vise-versa" cannot be. “反之亦然”不能。 That would say "If employeeSalary is not null, then employeeLevel can be null" but that contradicts the original problem statement "if EmployeeLevel is NULL, then EmployeeSalary must also be NULL".这会说“如果employeeSalary 不是null,那么employeeLevel 可以为null”,但这与原始问题陈述“如果EmployeeLevel 是NULL,那么EmployeeSalary 也必须为NULL”相矛盾。 The result then is a straight forward OR condition and IMHO the clearest expression of the intent:结果是一个直接的 OR 条件,恕我直言,这是意图的最清晰表达:

check ((EmployeeLevel is null and EmployeeSalary is null) or (EmployeeLevel is not null))

Here is one method:这是一种方法:

CHECK (EMPLOYELEVEL IS NOT NULL OR EmployeeSalary IS NULL)

You might find the NOT logic to be clearer:您可能会发现NOT逻辑更清晰:

CHECK (NOT (EMPLOYELEVEL IS NULL AND EmployeeSalary IS NOT NULL))

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

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