How can we delete some specific tables from a database. For instance I have a database with more than 20.000 tables and I need to delete the one which contains some specific strings in their names. So how can I do it? Is there a way to get the all table names from the database?
-
Are you really DELETING TABLES based on content of ROWS in that table? What about referential integrity?n8wrl– n8wrl2011-05-13 19:09:36 +00:00Commented May 13, 2011 at 19:09
-
Yes I am going to delete tables but based on the their names not the content of rows. Also there is no referential integrity problem in my case.makyol– makyol2011-05-13 19:14:07 +00:00Commented May 13, 2011 at 19:14
-
1The fact that you need to delete tables based on strings in their names indicates that you have a DB design problem. What's your actual use case?Marnen Laibow-Koser– Marnen Laibow-Koser2011-06-15 22:30:17 +00:00Commented Jun 15, 2011 at 22:30
3 Answers
You can get tables with certain names from information_schema.
This is how you get a list of the tables in your database:
select table_name from information_schema.tables;
With that in mind, you can generate a script to drop the tables you need:
select concat('drop table ', table_name, ';')
from information_schema.tables;
Then copy that script and paste it on a SQL interpreter.
You could also filter tables based on their names or databases:
select concat('drop table ', table_name, ';')
from information_schema.tables
where table_name like 'abc%'
and table_schema = 'myDatabase'; --db name
3 Comments
DROP TABLE table_name FROM information_schema.tables WHERE table_name like '%abc%' and table_schema = 'myDatabase'agree w/@n8wrl, but if you must you could use an IF ... THEN statement http://dev.mysql.com/doc/refman/5.0/en/if-statement.html to DROP TABLE
Comments
The information_schema views are helpful for listing and filtering tables in any ANSI compliant database:
select *
from information_schema.tables T
where T.table_name like '%FILTER HERE%'
You can loop through and drop the relevant tables using dynamic SQL and a cursor through the above recordset.