简体   繁体   中英

How to drop list of table from a schema in Oracle?

My Oracle scott schema contains table list like that

'prefix_A'
'prefix_B'
'prefix_C'
'A'
'B'
'C'

Now i want to drop list of tables ,containing table prefix like that 'Prefix_',But others table A ,B ,C will be remain same.

How it is possible ?

Thanks in Advance.

Use dynamic SQL driving off the data dictionary.

begin
     for trec in ( select table_name
                   from user_tables
                   where table_name like 'PREFIX\_%' escape `\' )
     loop
         dbms_output.put_line('dropping table ' || trec.table_name);
         execute immediate 'drop table '||trec.table_name;
     end loop;
end;

It's a good idea to be precise with the LIKE clause; using the escape keyword to ensure underscores aren't treated as wildcards. Alternatively use substr(table_name, 1, 7) = 'PREFIX_' .

Dropping the wrong table isn't a disaster provided you're working on 10g or later and the RECYCLE BIN is enabled , but it's still better not to. Obviously you wouldn't run code like this in Production, but you would use the principle to generate a script of drop statements.

The above code doesn't handle dependencies. If you have foreign keys referencing the prefixed tables and you want to force the dropping of the tables use this additional logic:

     execute immediate 'drop table '|| trec.table_name ||' cascade constraint';

This drops the foreign key constraints but leaves the (formerly) dependent tables.

I used this to disable constraints, drop constraints and delete the tables.

 -- disable constraints on tables
BEGIN
  FOR c IN
  (SELECT c.owner, c.table_name, c.constraint_name
   FROM user_constraints c, user_tables t
   WHERE c.table_name = t.table_name 
   AND t.table_name like 'WF_%'
   AND c.status = 'ENABLED'
   ORDER BY c.constraint_type DESC)
  LOOP
    dbms_utility.exec_ddl_statement('alter table "' || c.owner || '"."' || c.table_name || '" disable constraint ' || c.constraint_name);
  END LOOP;
END;             

-- drop the constraints
begin
    for r in ( select table_name, constraint_name
               from user_constraints where
               table_name like 'WF_%' )
    loop
        execute immediate 'alter table '||r.table_name
                          ||' drop constraint '||r.constraint_name;
    end loop;
end loop;

-- drop the tables
begin
     for trec in ( select table_name
                   from user_tables
                   where table_name like 'WF_%' )
     loop
         execute immediate 'drop table '||trec.table_name|| ' purge';
     end loop;
end;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM