mysql只有在存在时才重命名表

时间:2014-02-07 01:59:33

标签: mysql

我想重命名一个表,只要它存在: 当我这样做并且表不存在时,我收到一个错误: RENAME TABLE my_tablemy_new_table;

当表不存在时,如何编写不返回错误的查询?

2 个答案:

答案 0 :(得分:1)

也许这会有所帮助!

   IF (EXISTS (SELECT * 
                     FROM INFORMATION_SCHEMA.TABLES 
                     WHERE TABLE_SCHEMA = 'TheSchema' 
                     AND  TABLE_NAME = 'TheTable'))
    BEGIN
        --Do Stuff
    END

答案 1 :(得分:1)

你可以试试这段代码:

<?php

$db = "databaseName";
$oldTable = "tableName";
$newTableName = "newTableName";
$isTableExist = mysql_query("SELECT count(*) FROM information_schema.tables WHERE table_schema = '$db' AND table_name = '$oldTable'");

if($isTableExist){
    if(mysql_query("RENAME TABLE $oldTable TO $newTableName")){
        echo "Table Renamed from " . $oldTable . " to " . $newTableName . ".";
    }
    else echo mysql_error();
}

?>

祝你好运,我希望这对你有所帮助。 : - )