1

这是我试图做的,但它不起作用:

ALTER TABLE DEPT
ADD CONSTRAINT DEPT_DNAME_CK CHECK (DNAME = 'ALF%');
4

2 回答 2

1

如果列中有一些条目,dname例如alf%,您必须在添加约束之前删除这些条目。

create table dept (dname varchar(250));
insert into dept select 'alflll' from dual;
alter table dept add constraint dept_dname_ck check (lower(dname) not like 'alf%');

你得到一个错误;

ORA-02293: cannot validate (*****.DEPT_DNAME_CK) - check constraint violated

现在删除条目:

delete from dept where lower(dname) like 'alf%';
alter table dept add constraint dept_dname_ck check (lower(dname) not like 'alf%');

启用此约束后,如果您尝试违反该约束,则会收到错误消息:

ORA-02290: 违反检查约束 (****.DEPT_DNAME_CK)

于 2015-07-20T06:55:29.593 回答
0

如果您想允许单个值但不允许任何类似的值 - 这里的“相似”似乎以相同的前三个字母开头,无论如何 - 您可以使用唯一的基于函数的索引:

CREATE UNIQUE INDEX UNQ_DNAME_START ON DEPT (UPPER(SUBSTR(DNAME, 1, 3)));

Unique index UNQ_DNAME_START created.

然后你可以有一个值:

INSERT INTO DEPT (DNAME) VALUES ('Alfred');

1 row inserted.

但是尝试插入第二个类似的值会出错:

INSERT INTO DEPT (DNAME) VALUES ('alfonso');

Error report -
SQL Error: ORA-00001: unique constraint (SCHEMA.UNQ_DNAME_START) violated
00001. 00000 -  "unique constraint (%s.%s) violated"
*Cause:    An UPDATE or INSERT statement attempted to insert a duplicate key.
           For Trusted Oracle configured in DBMS MAC mode, you may see
           this message if a duplicate entry exists at a different level.
*Action:   Either remove the unique restriction or do not insert the key.

我假设您只使用了 'alf%' 作为示例,并且您实际上想要阻止所有类似的条目,而不是那个特定的前缀。

于 2015-07-20T08:56:34.713 回答