最近,工作中有個需求,需要刪除表結構,重新導入數據。在俊哥指導下,有了以下的sql腳本,記錄之。
declare
t1 user_tables%rowtype;
t2 varchar2(100);
begin
for t1 in (select * from user_tables ORDER BY TABLE_NAME)
loop
// t2 := 'truncate table EBAY_LOMBARDI7_DEV_DB_PROC06.' ||t1.table_name|| ';';
t2 := 'drop table EBAY_LOMBARDI7_DEV_DB_PROC06.' ||t1.table_name|| ' cascade constraints purge;';
dbms_output.put_line( t2);
end loop;
end;
在刪表的時候,時常會有以下的報錯:
Error starting at line 15 in command:
drop table EBAY_LOMBARDI7_DEV_DB_PROC06.LSW_BPD
Error report:
SQL Error: ORA-02449: unique/primary keys in table referenced by foreign keys
02449. 00000 - "unique/primary keys in table referenced by foreign keys"
*Cause: An attempt was made to drop a table with unique or
primary keys referenced by foreign keys in another table.
*Action: Before performing the above operations the table, drop 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";
那麼需要加上級聯刪除,例如:
drop table [schema_name].[table_name] cascade constraints purge;
另外說明:
1. delete語句是dml,這個操作會放到rollback segement中,事務提交之後才生效;如果有相應的trigger,執行的時候將被觸發.
truncate,drop是ddl, 操作立即生效,原數據不放到rollback segment中,不能回滾. 操作不觸發trigger.
2. delete語句不影響表所佔用的extent, 高水線(high watermark)保持原位置不動
顯然drop語句將表所佔用的空間全部釋放
truncate 語句缺省情況下見空間釋放到 minextents個 extent,除非使用reuse storage; truncate會將高水線復位(回到最開始).
3. 速度,一般來說: drop>; truncate >; delete
4.安全性:小心使用drop 和truncate,尤其沒有備份的時候.否則哭都來不及
使用上,想刪除部分數據行用delete,注意帶上where子句. 回滾段要足夠大.
想刪除表,當然用drop
想保留表而將所有數據刪除. 如果和事務無關,用truncate即可. 如果和事務有關,或者想觸發trigger,還是用delete.