2015-07-20 36 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