Mysql:RENAME TABLE IF EXISTS

时间:2012-02-14 15:31:51

标签: mysql

DROP TABLE IF EXISTS有效,但RENAME TABLE IF EXISTS不起作用。

有人可以为此查询提出解决方案吗?

You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'IF EXISTS video_top_day TO video_top_day_for_delete' at line 1

查询:

RENAME TABLE IF EXISTS video_top_day TO video_top_day_for_delete

10 个答案:

答案 0 :(得分:30)

我设法执行一个始终有效的代码,当表不存在时不会产生错误:

SELECT Count(*)
INTO @exists
FROM information_schema.tables 
WHERE table_schema = [DATABASE_NAME]
    AND table_type = 'BASE TABLE'
    AND table_name = 'video_top_day';

SET @query = If(@exists>0,
    'RENAME TABLE video_top_day TO video_top_day_for_delete',
    'SELECT \'nothing to rename\' status');

PREPARE stmt FROM @query;

EXECUTE stmt;

如果您不想手动替换[DATABASE NAME],可以使用以下变量

SELECT DATABASE() INTO @db_name FROM DUAL;

答案 1 :(得分:10)

还没有正式的解决方案。 2004年提交了feature request,从未关闭

答案 2 :(得分:10)

首先创建表IF NOT EXISTS。然后RENAME它,所以它将永远存在!

否则,重命名表,如果不存在则只处理错误。

很明显,但它确实有效。

答案 3 :(得分:2)

create table table2 like table1;
insert into table2 select * from table1;
drop table table1;

答案 4 :(得分:0)

如果您熟悉PL / SQL,那么您可以通过查询information_schema.columns并基于此执行重命名来检查表是否存在

答案 5 :(得分:0)

如果您不想保留变量,也可以这样做:

DELIMITER $$
IF EXISTS (SELECT *
                     FROM INFORMATION_SCHEMA.TABLES
                     WHERE TABLE_SCHEMA = database()
                     AND  TABLE_NAME = 'oldname')
THEN
    RENAME TABLE oldname to newname;
END if;
$$
DELIMITER ;

如果要重用它,甚至可以进一步创建一个函数

答案 6 :(得分:0)

问题八年后,MariaDB在版本10.5.2中添加了所需的确切语法:https://mariadb.com/kb/en/rename-table/

IF EXISTS
从10.5.2开始的MariaDB
如果使用此指令,则在不存在要重命名的表的情况下不会出错。

答案 7 :(得分:0)

解决方法:

CREATE TABLE IF NOT EXISTS video_top_day;
RENAME TABLE video_top_day TO video_top_day_for_delete

如果不存在则创建一个空表!

答案 8 :(得分:0)

DELIMITER ;;
DROP PROCEDURE IF EXISTS renameTableIfExists;;
CREATE PROCEDURE renameTableIfExists(IN tbl VARCHAR(255), IN toTbl VARCHAR(255))
BEGIN
SELECT DATABASE() INTO @db_name;
SELECT Count(*) INTO @exists FROM information_schema.tables 
  WHERE table_schema = @db_name
    AND table_type = 'BASE TABLE'
    AND TABLE_NAME = tbl;

IF @exists > 0 THEN
   SET @dropToTbl = CONCAT("DROP TABLE IF EXISTS ", toTbl); PREPARE dropToTbl FROM @dropToTbl; EXECUTE dropToTbl;
   SET @renameTbl = CONCAT("RENAME TABLE ", tbl, " to ",  toTbl); PREPARE renameTbl FROM @renameTbl; EXECUTE renameTbl;
   SELECT @tbl, @toTbl;
ELSE   
   SELECT 'Table not exists';
END IF;
END;;
DELIMITER ;

CALL renameTableIfExists('Tags', 'Tags2');

答案 9 :(得分:-3)

将表oldtablename重命名为newtablename