Oracle約束enable validate時的資料檢查

來源:互聯網
上載者:User

1 建立原始表及資料

SQL> create table t1(id number, name varchar2(20));

Table created

SQL> insert into t1 values(1,'A');

1 row inserted

SQL> insert into t1 values(1,'B');

1 row inserted

SQL> insert into t1 values(2,'C');

1 row inserted

SQL> insert into t1 values(3,'D');

1 row inserted

SQL> insert into t1 values(3,'E');

1 row inserted

SQL> insert into t1 values(4,'F');

1 row inserted

SQL> commit;

Commit complete

2 在表上建立enable novalidate主鍵

SQL> alter table t1 add constraint pk_t1 primary key(id) enable novalidate;

Table altered

3 嘗試將約束狀態更改為 enable validate,卻發現原有資料有問題

SQL> alter table t1 enable validate constraint pk_t1;

alter table t1 enable validate constraint pk_t1

ORA-02437: 無法驗證 (MYHR.PK_T1) - 違反主鍵

4 找出違反約束的資料,這裡採用Exceptions表儲存異常資料

SQL> @%Oracle_HOME%RDBMS/ADMIN/utlexpt1.sql;

Table created

SQL> alter table t1 enable validate constraint pk_t1 exceptions into exceptions;

alter table t1 enable validate constraint pk_t1 exceptions into exceptions

ORA-02437: 無法驗證 (MYHR.PK_T1) - 違反主鍵

5 根據異常表,找出對應源表中的異常資料

SQL> select id, name from t1 where rowid in(select row_id from exceptions);

        ID NAME

---------- --------------------

         1 A

         1 B

         3 D

         3 E

6 修正異常資料後,將索引生效

相關文章

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.