2015-07-20 65 views

回答

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 %'作为例子,你实际上想要阻止所有类似的条目,而不是特定的前缀。

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: check constraint (****.DEPT_DNAME_CK) violated