如何更改表以添加约束?

时间:2018-11-06 07:37:53

标签: sql oracle

所以,我的问题是:

  

由于用户为设施状态输入了各种值,因此导致   感到困惑。数据库所有者想限制以下值   “打开”,“关闭”,“保留”和“维护”用于状态   设施。

我的表格FACILITY包含以下列:

FACILITYNAME
RATE
STATUS

我尝试了以下操作:

ALTER TABLE FACILITY ADD CONSTRAINT FACILITY_STATUS 'Open','Closed','Reserved','Maintenance' FOR STATUS;

我收到错误消息ORA-00904:无效的标识符

然后我尝试了以下操作:

ALTER TABLE FACILITY ADD CONSTRAINT STATUS_CHECK CHECK (STATUS IN ('Open','Closed','Reserved','Maintenance'));

它说表已更改,但是当我尝试用“ abc”和“ Open”更新STATUS列时,它说行已更新,但是什么也没发生。我原以为它会给我'abc'的约束错误,然后将其更新为'Open'。

2 个答案:

答案 0 :(得分:4)

奇怪,对我来说,它按预期运行:

CREATE TABLE FACILITY (
    FACILITYNAME VARCHAR2(100),
    RATE INTEGER,
    STATUS VARCHAR2(20));
Table created.

INSERT INTO FACILITY VALUES ('f1', 1, 'Open');
1 row created.

ALTER TABLE FACILITY ADD CONSTRAINT STATUS_CHECK CHECK (STATUS IN ('Open','Closed','Reserved','Maintenance'));
Table altered.

UPDATE FACILITY SET STATUS = 'abc';

ORA-02290: check constraint (XXX.STATUS_CHECK) violated

也许验证约束的状态:

SELECT CONSTRAINT_NAME, STATUS, DEFERRABLE, DEFERRED 
FROM USER_CONSTRAINTS 
WHERE TABLE_NAME = 'FACILITY';

+------------------------------------------------+
|CONSTRAINT_NAME|STATUS |DEFERRABLE    |DEFERRED |
+------------------------------------------------+
|STATUS_CHECK   |ENABLED|NOT DEFERRABLE|IMMEDIATE|
+------------------------------------------------+

还请注意,除非您在ALTER TABLE中提供子句VALIDATE,否则约束不会检查现有值!默认情况下,约束仅影响新值和更新值。

答案 1 :(得分:3)

@KaushikNayak建议尝试添加检查约束:

ALTER TABLE FACILITY  ADD CONSTRAINT check_status CHECK (FACILITY_STATUS IN ('Open','Closed','Reserved','Maintenance'));

否则,Column level constraint必须使用另一列:

  

列级约束   列级约束引用表中的单个列,并且不指定列名(检查约束除外)。他们参考其关注的专栏

我建议您create table FACILITY_STATUS以列STATUS作为主键并插入值。

然后使用FACILITY作为外键将约束添加到STATUSFACILITY_STATUS(STATUS)