重命名具有带触发器的表的数据库

时间:2018-04-19 09:08:40

标签: mysql database table-rename

我需要重命名我的数据库,并想通过创建新的数据库并将表重命名为新的数据库名称,可以重命名数据库

我关注了https://chartio.com/resources/tutorials/how-to-rename-a-database-in-mysql/链接的var arr = ["john doe first", "robert way", "jason doe", "alex"]; var result = [].concat(...arr.map(e => e.split(' '))); console.log(result)部分。

但我的许多桌子都有before_create触发器。这会在执行以下命令期间引发ERROR Renaming Tables with InnoDB

  

$ mysql -u dbUsername -p“dbPassword”catalog -sNe'show tables'|读表; do mysql -u dbUsername -p“dbPassword”-sNe“RENAME TABLE catalog。$ table TO library。$ table”;完成

MySql文档中提到了这个问题 - https://dev.mysql.com/doc/refman/5.7/en/rename-table.html

如何重命名此类表格?

2 个答案:

答案 0 :(得分:0)

您可以将数据库复制到新数据库,然后将其删除 看着 https://dev.mysql.com/doc/refman/5.7/en/mysqldump-copying-database.html

答案 1 :(得分:0)

我认为解决此问题的唯一方法是在重命名表之前删除触发器,然后在新数据库上重新创建它。 我写了简单的PHP脚本来做到这一点 您可以使用任何编程语言采用相同的方法

$oldDb = "source_db"; //source database name
$newDb = "targer_db";//target database name
$tables = mysql_query('show tables from '.$oldDb);// get all tables in source database
//loop through batabase tables
while($table = mysql_fetch_row($tables)){
//get all triggers related to table
$getTriggers = 'show triggers from '.$oldDb.' where `table` = "'.$table[0].'"';
$getTriggersResult = mysql_query($getTriggers)or die("error getTriggers not done ".mysql_error());
$tableTriggers = array();//array to hold triggers sql 
//loop through table triggers
while($trigger = mysql_fetch_array($getTriggersResult)){
//get sql created the trigger
$getTriggerSql = 'show create trigger '.$oldDb.'.'.$trigger['Trigger'];
$getTriggerSqlResult = mysql_query($getTriggerSql)or die("error getTriggerSql not done ".mysql_error());
$row = mysql_fetch_row($getTriggerSqlResult);
array_push($tableTriggers,$row[2]);//store the sql in array
$dropTriggerQuery = 'drop trigger '.$oldDb.'.'.$trigger['Trigger'];//drop the trigger
$dropTriggerResult = mysql_query($dropTriggerQuery)or die("error dropTriggerQuery not done ".mysql_error());
}
//now all trigger related to table have been droped and you can rename the table
$moveTable = 'rename table '.$oldDb.'.'.$table[0].' to '.$newDb.'.'.$table[0];
$moveTableResult = mysql_query($moveTable)or die("error moveTable not done ".mysql_error());
//loop through array that holds the dropped trigger sql
foreach($tableTriggers as $trigger){
//replace old source database name with the target database from the sql
$createTriggerQuery = str_replace("`".$oldDb."`","`".$newDb."`",$trigger);
//run trigger sql to recreate it in the target database
$createTrigger = mysql_query($createTriggerQuery)or die("error createTriggerQuery not done ".mysql_error());
}
}
希望这可以帮助