PLSQL - 删除用户的所有数据库对象

NMa*_*Man 18 oracle schema plsql stored-procedures

我正在尝试使用一个过程(没有参数)来删除程序启动过程中位于模式中的所有用户创建的数据库对象,但我真的不确定如何解决这个问题.这是我到目前为止所拥有的,但我认为我的方式是错误的.


create or replace procedure CLEAN_SCHEMA is
cursor schema_cur is
select 'drop '||object_type||' '|| object_name||  DECODE(OBJECT_TYPE,'TABLE',' CASCADE CONSTRAINTS;',';')
from user_objects;
schema_rec schema_cur%rowtype;
begin
select 'drop '||object_type||' '|| object_name||  DECODE(OBJECT_TYPE,'TABLE',' CASCADE CONSTRAINTS;',';')
into schema_rec
from user_objects;
end;
/

小智 19

create or replace
FUNCTION                DROP_ALL_SCHEMA_OBJECTS RETURN NUMBER AS
PRAGMA AUTONOMOUS_TRANSACTION;
cursor c_get_objects is
  select object_type,'"'||object_name||'"'||decode(object_type,'TABLE' ,' cascade constraints',null) obj_name
  from user_objects
  where object_type in ('TABLE','VIEW','PACKAGE','SEQUENCE','SYNONYM', 'MATERIALIZED VIEW')
  order by object_type;
cursor c_get_objects_type is
  select object_type, '"'||object_name||'"' obj_name
  from user_objects
  where object_type in ('TYPE');
BEGIN
  begin
    for object_rec in c_get_objects loop
      execute immediate ('drop '||object_rec.object_type||' ' ||object_rec.obj_name);
    end loop;
    for object_rec in c_get_objects_type loop
      begin
        execute immediate ('drop '||object_rec.object_type||' ' ||object_rec.obj_name);
      end;
    end loop;
  end;
  RETURN 0;
END DROP_ALL_SCHEMA_OBJECTS;
Run Code Online (Sandbox Code Playgroud)

创建上面的函数(自主,因此可以通过函数调用DDL)然后您可以:

select DROP_ALL_SCHEMA_OBJECTS from dual;
Run Code Online (Sandbox Code Playgroud)

当你想要删除所有对象时,请确保你不要尝试删除你正在运行的proc(我不关心procs,这就是为什么我在object_type列表中没有procs或函数)

如果你想丢弃所有你需要一个匿名块

但我需要能够从一个只允许ansi sql(而不是plsql)的工具做到这一点,因此存储过程.

请享用.


小智 13

declare
  cursor ix is
    select *
      from user_objects
     where object_type in ('TABLE', 'VIEW', 'FUNCTION', 'SEQUENCE');
begin
 for x in ix loop
   execute immediate('drop '||x.object_type||' '||x.object_name);
 end loop;
end;
Run Code Online (Sandbox Code Playgroud)


Mat*_*son 2

除非用户很难重新应用权限,否则删除用户并重新创建它们可能会更容易。