How to drop multiple databases based on a prefix string
example_ or e_
I want to drop all databases that match the prefix e_, so that e_database1, e_database2 and so forth ar开发者_运维知识库e dropped.
Commands that do not work:
mysql drop database e_% mysql drop database e_*
I'm not looking for all the tables in a given database, but all the databases in a given MySQL server.
You could do this with a stored proc like this:
/* Start stored proc */
DELIMITER //
DROP PROCEDURE IF EXISTS db_clean_up //
CREATE PROCEDURE db_clean_up
(
)
BEGIN
declare done bit default false;
declare deleted varchar(255);
-- Drop DBs
DECLARE cur1 CURSOR FOR SELECT
SCHEMA_NAME
FROM information_schema.SCHEMATA
WHERE SCHEMA_NAME LIKE 'db_prefix%';
DECLARE CONTINUE HANDLER FOR NOT FOUND SET done = TRUE;
OPEN cur1;
createLoop: LOOP
FETCH cur1 INTO deleted;
IF done THEN
LEAVE createLoop;
END IF;
SET @query = CONCAT('DROP DATABASE `', deleted, '`;');
PREPARE stmt1 FROM @query;
EXECUTE stmt1;
END LOOP createLoop;
CLOSE cur1;
END //
delimiter ;
/* End stored proc */
精彩评论