Oracle

Oracle:啟用 PK 是否會重建其索引?

  • October 25, 2016

設想:

  • MY_TABLE有主鍵約束PK_MY_TABLE
  • MY_TABLE還有一個名為的索引IDX_PK_MY_TABLE,它強制約束的唯一性PK_MY_TABLE

如果我禁用約束PK_MY_TABLE然後重新啟用它,索引IDX_PK_MY_TABLE會重建嗎?

它很容易測試。

有兩種可能的情況。

場景一:

場景 1 是使用現有索引創建 PK:

SQL> create table MY_TABLE
 2  (
 3  pk number
 4  );

Table created.

SQL>

將索引添加到它:

SQL> create unique index IDX_PK_MY_TABLE on MY_TABLE (pk);

Index created.

SQL>

添加約束:

SQL> alter table MY_TABLE add constraint PK_MY_TABLE primary key (pk) USING INDE
X  IDX_PK_MY_TABLE;

Table altered.

SQL> select constraint_name from user_constraints;

CONSTRAINT_NAME
------------------------------
PK_MY_TABLE

SQL>
SQL>
SQL> select index_name
 2  from user_indexes;

INDEX_NAME
------------------------------
IDX_PK_MY_TABLE

插入一些數據:

SQL> insert into MY_TABLE values(1);

1 row created.

SQL> insert into MY_TABLE values(2);

1 row created.

SQL>

測試約束:

SQL> insert into MY_TABLE values(2);
insert into MY_TABLE values(2)
*
ERROR at line 1:
ORA-00001: unique constraint (PHIL.PK_MY_TABLE) violated

SQL>

禁用約束:

SQL>
SQL> alter table MY_TABLE disable constraint PK_MY_TABLE;

Table altered.

SQL> 

再試INSERT一次:

SQL> insert into MY_TABLE values(2);
insert into MY_TABLE values(2)
*
ERROR at line 1:
ORA-00001: unique constraint (PHIL.IDX_PK_MY_TABLE) violated

它成功是因為在禁用約束時唯一索引沒有被禁用/刪除。請注意,原始錯誤是 ORA-00001: unique constraint (PHIL.PK_MY_TABLE) violated,而PHIL.IDX_PK_MY_TABLE一旦禁用 PK 約束,就會違反索引約束。

場景二:

場景 2 是在創建表時創建 PK:

SQL> create table MY_TABLE
 2  (
 3  pk number,
 4  constraint PK_MY_TABLE PRIMARY KEY (pk)
 5  );

Table created.

SQL> select index_name from user_indexes;

INDEX_NAME
------------------------------
PK_MY_TABLE

SQL> select constraint_name from user_constraints;

CONSTRAINT_NAME
------------------------------
PK_MY_TABLE

SQL> 

禁用約束:

SQL> alter table MY_TABLE disable constraint PK_MY_TABLE;

Table altered.

SQL> select constraint_name, status from user_constraints;

CONSTRAINT_NAME                STATUS
------------------------------ --------
PK_MY_TABLE                    DISABLED

SQL>

索引消失了!:

SQL>  select index_name from user_indexes;

no rows selected

SQL>

重新啟用它會重新創建索引:

SQL> alter table MY_TABLE enable constraint PK_MY_TABLE;

Table altered.

SQL> select index_name from user_indexes;

INDEX_NAME
------------------------------
PK_MY_TABLE

SQL>

如果要保留索引:

SQL> alter table MY_TABLE disable constraint PK_MY_TABLE  keep index;

Table altered.

SQL> select index_name from user_indexes;

INDEX_NAME
------------------------------
PK_MY_TABLE

SQL>

引用自:https://dba.stackexchange.com/questions/153274