Oracle batch clear table data

There are two ways to clear table data, delete from tableName; truncate table tableName;

The second method is more efficient, delete directly, and cannot be rolled back.

If you want to execute delete scripts in batches, when there are many tables, it is too slow to write scripts one by one. Use the following script to generate delete SQL in batches.

declare
  --需要执行的SQL字符串
  v_alter_sqlstr  varchar2(500);
  -- 游标
  cursor c_result is 
  select 'truncate table ' || t.OBJECT_NAME  || ';' as alter_sqlstr
    from user_objects t where t.OBJECT_TYPE='TABLE' and  t.object_name  like 'T_%';
 
  -- 定义一个与游标一样的变更
  v_result c_result%rowtype;
begin
  open c_result;
    loop
      fetch c_result into v_result;  
      exit when c_result%notfound;
      v_alter_sqlstr := v_result.alter_sqlstr;
      dbms_output.put_line(v_alter_sqlstr); -- 可单独将SQL从output窗口提取出来执行
      
      -- 执行修改
      --execute immediate v_alter_sqlstr;   
    end loop;
  close c_result;
exception
  when others then
    begin
      dbms_output.put_line('异常:' || 'sqlcode:' || sqlcode || ' sqlerrm : ' ||sqlerrm );
    end;  
end;

Script interpretation:

The cursor part is used to splice the SQL statements to be executed.

After the script execution is completed, the generated scripts will be printed out in the pl/sql output window, and the table data will be deleted if these scripts are placed in a new window for direct execution.

Guess you like

Origin blog.csdn.net/liangmengbk/article/details/129702583