检查约束以根据其他列值限制NULL值

时间:2016-12-29 17:50:28

标签: sql oracle check-constraint

我有这个非常简单的作品,现在几个小时一直困扰着我的大脑:

CREATE TABLE driving_school_questions(

    question VARCHAR2(200),
    picture VARCHAR2(2), 
    CONSTRAINT q_p_chk CHECK ((question LIKE '%see picture%' AND picture IS NOT NULL) 
                                                   AND
                               (question LIKE '% %' OR picture IS NULL))

);

我想在这里尝试实现的是创建一个约束,如果问题字段包含'请参阅图片'那么图片不能为NULL,对于每个不包含'看图片的问题,它都可以为NULL。在里面。我在CHECK子句中尝试了其他表达式但是有用。

这些插入工作正常:

INSERT INTO driving_school_questions (question, picture)
VALUES ('blahblah see picture', '23'); --NOT NULL so ok for now

INSERT INTO driving_school_questions (question, picture)
VALUES ('blah blah see picture ', NULL); --It's ok to be NULL(constraint violated)

这不起作用:

INSERT INTO driving_school_questions (question, picture)
VALUES ('blah blah', NULL);--it should work but constraint violation

1 个答案:

答案 0 :(得分:2)

我认为您只需要进行一次检查,以防止单一组合“看到图片'和null:

CREATE TABLE driving_school_questions(
    question VARCHAR2(200),
    picture VARCHAR2(2), 
    CONSTRAINT q_p_chk CHECK (NOT(question LIKE '%see picture%' AND picture IS NULL))
);

这会查找单个组合,并检查您拥有的内容。

INSERT INTO driving_school_questions (question, picture)
VALUES ('blahblah see picture', '23');

1 row inserted.

INSERT INTO driving_school_questions (question, picture)
VALUES ('blah blah see picture ', NULL);

Error report -
ORA-02290: check constraint (SCHEMA.Q_P_CHK) violated

INSERT INTO driving_school_questions (question, picture)
VALUES ('blah blah', NULL);

1 row inserted.

正如@vkp建议的那样,您可以使用正则表达式来检查“查看图片”。部分,以防止错误匹配,以及案件问题:

    CONSTRAINT q_p_chk CHECK (NOT(REGEXP_LIKE(question, '(^|\s)see picture(\s|$)', 'i')
      AND picture IS NULL))

这意味着这两个都可以:

INSERT INTO driving_school_questions (question, picture)
VALUES ('blahblah isee pictures', null);

INSERT INTO driving_school_questions (question, picture)
VALUES ('See picture', '25');

但不允许这样做:

INSERT INTO driving_school_questions (question, picture)
VALUES ('See Picture', null);

您甚至可能只想限制整个字符串值只是“查看图片”,或者是几个可能的值之一;您也可以使用略微修改的正则表达式模式。