这是我尝试做的,但它不起作用:
ALTER TABLE DEPT
ADD CONSTRAINT DEPT_DNAME_CK CHECK (DNAME = 'ALF%');
答案 0 :(得分: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)
答案 1 :(得分: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.
我假设您只使用过&alff%' alf%'例如,你实际上想要阻止所有类似的条目,而不是那个特定的前缀。