6

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?

1

2 Answers 2

16

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

Sign up to request clarification or add additional context in comments.

Comments

0

Just to add to the above answer, MYSQL returns an error ERROR 1046 (3D000): No database selected if no database is selected before beginning the procedure. So prepend this statement use <<db_name>>; to the above answer. The revised solution would be:

use <<db_name>>;    
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 ;
CALL drop_tables_like('a%', '<<db_name>>');

Make sure you replace <> with the actual name of the database. Cheers!

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.