小编典典

Mysql:如果存在则重命名表

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

阅读 748

收藏
2020-05-17

共1个答案

小编典典

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

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;
2020-05-17