2

我有一张桌子依赖

CREATE TABLE DEPENDANT (DEPENDANT_NM VARCHAR2(15) PRIMARY KEY,
  DEP_GENDER CHAR(1), DEP_BDAT DATE, RELATED_HOW VARCHAR2 (8), ESSNO CHAR(9));
ALTER TABLE DEPENDANT ADD CONSTRAINT FK_ESSNO FOREIGN KEY (ESSNO)
 REFERENCES HW_EMPLOYEE(SSNO);
ALTER TABLE DEPENDANT ADD CONSTRAINT CK_DEP_GENDER CHECK
(DEP_GENDER IN ('M','F'));

我需要添加一个约束,以确保女性家属只能被视为“女儿”或“配偶”,而男性家属只能被视为“儿子”或“配偶”

我是否使用检查约束,例如...

ALTER TABLE DEPENDANT ADD CONSTRAINT CK_RELATEDF CHECK (DEP_GENDER = 'F' AND 
RELATED_HOW IN('Daughter' OR 'Spouse'));
4

2 回答 2

2

你必须这样写:

ALTER TABLE DEPENDANT 
    ADD CONSTRAINT CK_RELATEDF 
        CHECK (DEP_GENDER = 'F' AND RELATED_HOW IN ('Daughter', 'Spouse'));

编辑:你必须做一次检查:

ALTER TABLE DEPENDANT ADD CONSTRAINT CK_RELATEDF
  CHECK ((DEP_GENDER = 'F' AND RELATED_HOW IN ('Daughter', 'Spouse'))
    OR (DEP_GENDER = 'M' AND RELATED_HOW IN ('Son', 'Spouse')));
于 2013-11-05T22:04:39.953 回答
2

“你必须一次性完成”

我对这个断言很感兴趣(不是双关语)。

在我看来,四个约束不仅是可能的而且是可取的(以提供更大的故障消息粒度),例如

ALTER TABLE DEPENDANT ADD CONSTRAINT Gender_legal_values 
    CHECK ( DEP_GENDER IN ( 'M', 'F' ) );

ALTER TABLE DEPENDANT ADD CONSTRAINT Related_legal_values 
    CHECK ( RELATED_HOW IN ( 'Son', 'Daughter', 'Spouse' ) );

ALTER TABLE DEPENDANT ADD CONSTRAINT Female_legal_values
    CHECK ( DEP_GENDER = 'M' OR RELATED_HOW IN ( 'Daughter', 'Spouse' ) );

ALTER TABLE DEPENDANT ADD CONSTRAINT Male_legal_values
    CHECK ( DEP_GENDER = 'F' OR RELATED_HOW IN ( 'Son', 'Spouse' ) );
于 2013-11-06T22:28:18.147 回答