Search code examples
mysqlstored-proceduresduplication

Duplicate a mysql database from within mysql?


This is probably a longshot but.. is it possible to duplicate a whole database layout (tables, view, procedures, everything) with a query or multiple queries in a stored procedure?

Basically looking for the same functionality as if I would use mysqldump like this

# mysqldump -u root -ppassword --no-data --routines dbname > file
  //create database copyofdbname
# mysql -u root -ppassword copyofdbname < file

Is it possible to do this in a mysql procedure without any external tools?

I guess I could do the tables by using 'show tables' and then a iterate over the results to get the 'create table' statatements for each table and forward them into the new database.
This is just speculation though, no idea how I would copy the stored procedures from the database this way.


Solution

  • Basically no, MYSql does not have a duplicate database feature. Some external tools might, but none that I'm aware of. I did this process using php, but I'm sure it can be done using stored procedures or anything other middle tier application. Here's the steps I followed in high level. I assume you know the details of how to do each step.

    1. Create the new DB
    2. Query all the tables of that db, I had access to information_schema so I just did a select from there.
    3. Loop over the tables.
      1. run something like this CREATE TABLE dbnew.tableA LIKE dbold.tableA It will duplicate the structure of the table perfectly
      2. Insert Select into your new db/table selecting * from old db/table
    4. have lunch or, depending on your database size, watch a movie or re-runs of "the IT crowd"
    5. enjoy your copied database.

    Amendment: In my research doing this before, I found that there was a version of mySql that had a duplicate database command, but it was buggy and taken out in future versions. Even if you are running the version with that command available, you are still better off following these steps than using that command.