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
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.