Skip to content

Instantly share code, notes, and snippets.

@ckng
Forked from michaelmior/rename-db.sh
Created August 9, 2012 07:38
Show Gist options
  • Save ckng/3302044 to your computer and use it in GitHub Desktop.
Save ckng/3302044 to your computer and use it in GitHub Desktop.
MySQL rename database. Simple script to move all tables from one database to another. Also, RENAME table doesn't work on views, so they won't be migrated.
#!/bin/bash
OLD_DB=$1
NEW_DB=$2
USER=root
read -s -p "MySQL $USER Password: " PASS
echo "CREATE DATABASE $2 DEFAULT CHARACTER SET utf8 DEFAULT COLLATE utf8_general_ci;" | mysql -u $USER --password=$PASS
TABLES=`echo "SHOW TABLES IN $1;" | mysql -NB -u $USER --password=$PASS`
for TABLE in $TABLES; do
$(echo "RENAME TABLE \`$1\`.\`$TABLE\` TO \`$2\`.\`$TABLE\`;" | mysql -u $USER --password=$PASS)
done
@tuomassalo
Copy link

Please note that this will not work for views. You cannot rename views to make them jump from a database to another. Use DROP VIEW and CREATE VIEW instead. Clumsy, yes. You might want to do a mysqldump to move the views, after first moving all the tables. Also note that SHOW TABLES will show tables AND views, so beware.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment