Unfortunately – and probably for good reason – the RENAME DATABASE command had a short life in Mysql for safety precaution reasons.
After doing some research, it appears that the best approach is as follows as it works well for both MyISAM and InnoDB table types:
- Create new database
- Perform RENAME TABLE command that includes the table and database from the old one to the newly created database
- Repeat once for each table
In all of the examples I didn't find an automated script – time to make one I thought!
Here is the stored procedure that I was able to come up with and successfully execute. I even went the extra effort to accept parameters for the database name!
Next, you simply need to call the stored procedure. Before executing the stored procedure, simply make sure that the new database has been created and execute as follows:
Note: Being sure to replace NEW_DATABASE_NAME with the actual name of the database. Published on Sep 28, 2012 Tags: SQL Tutorials for Beginners, Intermediate and Advanced Users
| rename database
| stored procedure
Did you enjoy this article? If you did here are some more articles that I thought you will enjoy as they are very similar to the article
that you just finished reading.
No matter the programming language you're looking to learn, I've hopefully compiled an incredible set of tutorials for you to learn; whether you are beginner
or an expert, there is something for everyone to learn. Each topic I go in-depth and provide many examples throughout. I can't wait for you to dig in
and improve your skillset with any of the tutorials below.
The first challenge is to retrieve a list of the tables in the database. Once I have this list, it's as simple as looping through the items via a CURSOR and executing the RENAME TABLE command dynamically with the table name.
DELIMITER //
DROP PROCEDURE IF EXISTS `RenameDatabase` //
CREATE PROCEDURE `RenameDatabase`(
new_database VARCHAR(255)
)
BEGIN
DECLARE done INT DEFAULT FALSE;
DECLARE num_rows INT;
DECLARE i INT;
DECLARE the_name VARCHAR(255);
DECLARE ren VARCHAR(255);
DECLARE table_names CURSOR FOR SELECT DISTINCT table_name FROM information_schema.columns WHERE table_schema = DATABASE();
DECLARE CONTINUE HANDLER FOR NOT FOUND SET done = TRUE;
OPEN table_names;
read_loop: LOOP
FETCH table_names INTO the_name;
IF done THEN
LEAVE read_loop;
END IF;
SET @ren = concat("RENAME TABLE `", DATABASE(), "`.", the_name, " TO `", new_database, "`.", the_name);
PREPARE ren FROM @ren;
EXECUTE ren;
END LOOP;
CLOSE table_names;
END //
DELIMITER ;
call RenameDatabase('NEW_DATABASE_NAME');
Related Posts
Tutorials
Learn how to code in HTML, CSS, JavaScript, Python, Ruby, PHP, Java, C#, SQL, and more.