I have a bunch of tables in a MySQL
database, some of them starting with phpbb_* which I wanted to delete all of them. Does someone know a way to do so instead of doing
drop table <tablename>;
every single time? Like a regex?
drop table phpbb*
or something like?
To permanently remove a table, enter the following statement within the MySQL shell: DROP TABLE table1; Replace table1 with the name of the table you want to delete. The output confirms that the table has been removed.
SELECT CONCAT( 'DROP TABLE ', GROUP_CONCAT(table_name) , ';' ) AS statement FROM information_schema. tables WHERE table_name LIKE 'myprefix_%'; This will generate a DROP statement which you can than copy and execute to drop the tables.
The DROP TABLE statement deletes the specified table, and any data associated with it, from the database. The IF EXISTS clause allows the statement to succeed even if the specified tables does not exist. If the table does not exist and you do not include the IF EXISTS clause, the statement will return an error.
You can use this MySQL procedure:
DELIMITER $$
CREATE PROCEDURE drop_tables_like(pattern VARCHAR(255), db VARCHAR(255))
BEGIN
SELECT @str_sql:=CONCAT('drop table ', GROUP_CONCAT(table_name))
FROM information_schema.tables
WHERE table_schema=db AND table_name LIKE pattern;
PREPARE stmt from @str_sql;
EXECUTE stmt;
DROP prepare stmt;
END$$
DELIMITER ;
For dropping all tables starting with 'a' in 'test1' database you can run:
CALL drop_tables_like('a%', 'test1');
Reference: http://dev.mysql.com/doc/refman/5.5/en/drop-table.html
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With