Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

drop tables using regex - MySQL

Tags:

mysql

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?

like image 253
cybertextron Avatar asked Oct 28 '12 15:10

cybertextron


People also ask

How do I drop a table in MySQL?

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.

How do you use the prefix to drop a table?

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.

What is DROP TABLE if exists?

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.


1 Answers

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

like image 192
Roozbeh Zabihollahi Avatar answered Sep 29 '22 06:09

Roozbeh Zabihollahi