要在MySQL中批量刪除數據庫,您可以使用循環和動態SQL語句。這里是一個示例存儲過程,用于刪除以特定前綴開頭的所有數據庫:
DELIMITER $$
CREATE PROCEDURE drop_databases_with_prefix(IN db_prefix VARCHAR(255))
BEGIN
DECLARE done INT DEFAULT 0;
DECLARE db_name VARCHAR(255);
DECLARE cur CURSOR FOR SELECT SCHEMA_NAME FROM INFORMATION_SCHEMA.SCHEMATA WHERE SCHEMA_NAME LIKE CONCAT(db_prefix, '%');
DECLARE CONTINUE HANDLER FOR NOT FOUND SET done = 1;
OPEN cur;
read_loop: LOOP
FETCH cur INTO db_name;
IF done THEN
LEAVE read_loop;
END IF;
SET @sql = CONCAT('DROP DATABASE ', db_name);
PREPARE stmt FROM @sql;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;
END LOOP;
CLOSE cur;
END$$
DELIMITER ;
要使用此存儲過程,請按照以下步驟操作:
test_
開頭的所有數據庫,請運行以下命令:CALL drop_databases_with_prefix('test_');
注意:在執行此操作之前,請確保您已備份所有重要數據,因為此操作將永久刪除數據庫及其內容。