- Restore both the databases as it is.
- Use the following stored procedure to move all the tables from one DB to another DB after adding the prefix.
- After moving delete the source database.
This stored procedure gets the table list from MySQL's inmemory tables in information_schema
and automatically moves to another DB using the RENAME
command.
DELIMITER $$
USE `db`$$
DROP PROCEDURE IF EXISTS `renameDbTables`$$
CREATE DEFINER=`db`@`%` PROCEDURE `renameDbTables`(
IN from_db VARCHAR(20),
IN to_db VARCHAR(30),
IN to_name_prefix VARCHAR(20)
)
BEGIN
/*
call db.renameDbTables('db1','db2','db_');
db1.xxx will be renamed to db2.db_xxx
*/
DECLARE from_state_table VARCHAR(20) DEFAULT '';
DECLARE done INT DEFAULT 0;
DECLARE b VARCHAR(255) DEFAULT '';
DECLARE cur1 CURSOR FOR SELECT TABLE_NAME FROM information_schema.TABLES
WHERE TABLE_SCHEMA=from_db;
DECLARE CONTINUE HANDLER FOR SQLSTATE '02000' SET done = 1;
OPEN cur1;
REPEAT
FETCH cur1 INTO from_state_table;
IF NOT done THEN
-- select from_state_table;
SET @QUERY = '';
SET @QUERY = CONCAT(@QUERY,'RENAME TABLE ',from_db,'.', from_state_table,' TO ',to_db,'.', to_name_prefix, from_state_table,';');
-- SELECT @query;
PREPARE s FROM @QUERY;
EXECUTE s;
DEALLOCATE PREPARE s;
END IF;
UNTIL done END REPEAT;
CLOSE cur1;
END$$
DELIMITER ;