[英]Check constraint with condition
I'm wondering if this condition can be done by a check constraint or do I need to create a trigger. 我想知道是否可以通过检查约束来完成此条件,还是我需要创建一个触发器。
Condition : if student admited date is not null then exam mark is null 条件:如果学生的录取日期不为空,则考试成绩为空
Remark: Constaint case OR Trigger 备注:包含案例或触发器
What I tried : 我试过了
ALTER TABLE ADMITED_TABLE
ADD CONSTRAINT AAAA CHECK
( CASE WHEN DATEADMITED IS NOT NULL THEN MARK NULL END);
Error: 错误:
ORA-00920: invalid relational operator
00920. 00000 - "invalid relational operator"
A check constraints takes a boolean condition, so you'd have to frame this logic in a form of such a condition: 检查约束采用布尔条件,因此您必须以这种条件的形式来构造此逻辑:
ALTER TABLE ADMITED_TABLE
ADD CONSTRAINT AAAA CHECK
(dateadmited IS NULL OR mark IS NULL);
I must be misreading David's requirement, because my solution is: 我一定是在误解David的要求,因为我的解决方案是:
ALTER TABLE admitted_table
ADD CONSTRAINT aaaa CHECK
( (dateadmitted IS NOT NULL
AND mark IS NULL)
OR dateadmitted IS NULL);
The following are my test cases: 以下是我的测试用例:
-- Succeeds
INSERT INTO admitted_table (
dateadmitted, mark
)
VALUES (SYSDATE, NULL);
-- Fails due to check constraint
INSERT INTO admitted_table (
dateadmitted, mark
)
VALUES (SYSDATE, 10);
-- Succeeds
INSERT INTO admitted_table (
dateadmitted, mark
)
VALUES (NULL, 99);
From the description in the question it appears that what you want is a trigger, not a constraint. 从问题的描述中可以看出,您想要的是触发器,而不是约束。 A constraint lets you verify that values in a table are as you expect them to be;
约束使您可以验证表中的值是否符合预期。 however, a constraint cannot change the value of a column.
但是,约束不能更改列的值。 So if you're just trying to verify that the values supplied match your rules a CHECK constraint is sufficient.
因此,如果您只是想验证提供的值是否与您的规则匹配,则CHECK约束就足够了。 If you want to (potentially) change the value of the MARK column you'll need to use a trigger, such as:
如果要(可能)更改MARK列的值,则需要使用触发器,例如:
CREATE OR REPLACE ADMITED_TABLE_BIU
BEFORE INSERT OR UPDATE ON ADMITED_TABLE
FOR EACH ROW
BEGIN
IF :NEW.DATEADMITED IS NOT NULL THEN
:NEW.MARK := NULL;
END IF;
END ADMITED_TABLE_BIU;
Best of luck. 祝你好运。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.