sql 脚本-- 变量所有表进行操作

最近,工作中有个需求,需要删除表结构,重新导入数据。在俊哥指导下,有了以下的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.

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章