在刪除有父子表關係的表的資料時,我們都知道要先刪除子表 再刪除父表資料;或者先取消外鍵 然後再刪除。
昨天採用先刪子表 ,再刪父表,刪除時使用truncate,結果在刪除父表的時候,給出了這個提示:
“
在行 1 上開始執行命令時出錯:
truncate table ep_point
錯誤報表:
SQL 錯誤: ORA-02266: 表中的唯一/主鍵被啟用的外鍵引用
02266. 00000 - "unique/primary keys in table referenced by enabled foreign keys"
*Cause: An attempt was made to truncate a table with unique or
primary keys referenced by foreign keys enabled in another table.
Other operations not allowed are dropping/truncating a partition of a
partitioned table or an ALTER TABLE EXCHANGE PARTITION.
*Action: Before performing the above operations the table, disable the
foreign key constraints in other tables. You can see what
constraints are referencing a table by issuing the following
command:
SELECT * FROM USER_CONSTRAINTS WHERE TABLE_NAME = "tabnam";
”。
而改成delete則刪除成功。
網上給出的解釋是ddl與dml 的區別(because truncate isn't going to verify the constraint, truncate is ddl.)。
解決辦法:
SQL> alter table ep_pointdisable primary key cascade;
表已更改。
SQL> truncate table ep_point;
表已截掉。
SQL> alter table ep_point enable primary key;
表已更改。
SQL>ALTER TABLE '子表' ENABLE CONSTRAINT '外鍵約束名';
*特別注意的是在ENABLE主鍵後不會自動回復外鍵(沒有cascade選項),因此需要手工對引用該鍵的約束進行ENABLE。
由於此解決方案會disable掉關聯子表的外鍵,所以慎用。