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

vsikbqxv  于 2021-06-25  发布在  Mysql
关注(0)|答案(2)|浏览(437)

我需要重命名我的数据库,并发现通过创建新的db并将表重命名为新的db name,可以重命名db
我跟着警察走 Renaming Tables with InnoDB 第节https://chartio.com/resources/tutorials/how-to-rename-a-database-in-mysql/ 链接。
但是我的许多表在创建触发器之前都有。这会引起错误 Trigger in wrong schema 在执行以下命令期间:
$mysql-u dbusername-p“dbpassword”catalog-sne'show tables'| while read table;do mysql-u dbusername-p“dbpassword”-sne“重命名表目录。$table到库。$table”;完成
mysql文档中甚至提到了这个问题-https://dev.mysql.com/doc/refman/5.7/en/rename-table.html
我怎样才能重新命名这些表呢?

ikfrs5lh

ikfrs5lh1#

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

4ngedf3f

4ngedf3f2#

我认为解决这个问题的唯一方法是在重命名表之前删除触发器,然后在新数据库上重新创建它。我写了一个简单的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());
}
}

希望这能有所帮助

相关问题