Mysql:如果存在则重命名表

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/9279619/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-31 12:07:53  来源:igfitidea点击:

Mysql: RENAME TABLE IF EXISTS

mysql

提问by Somebody

This DROP TABLE IF EXISTSworks, too bad that RENAME TABLE IF EXISTSdoesn't work.

DROP TABLE IF EXISTS行得通,太糟糕了,RENAME TABLE IF EXISTS行不通。

Can anyone suggest a solution for this query?

任何人都可以为此查询提出解决方案吗?

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

query:

询问:

RENAME TABLE IF EXISTS video_top_day TO video_top_day_for_delete

回答by Schiavini

I've managed to execute a code that always works and generates no errors when the table doesn't exist:

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

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;

When you don't want to replace [DATABASE NAME]manually you can use the following variable

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

SELECT DATABASE() INTO @db_name FROM DUAL;

回答by vulkanino

First create table IF NOT EXISTS. Then RENAMEit, so it will always exist!

首先创建表IF NOT EXISTS。那么RENAME它,所以它永远存在!

Otherwise, rename the table, and if it doesn't exist just handle the error.

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

It is obvious, but it works.

这是显而易见的,但它有效。

回答by Martin.

There's no official solution yet. There has been feature requestsubmitted in 2004, never closed

目前还没有官方解决方案。2004年已经提交过功能请求,从未关闭

回答by triclosan

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

回答by Damonio

If you don't want to keep variables you can do also this:

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

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 ;

You can even further create a function if you want to reuse it

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

回答by rkosegi

If you are familiar with PL/SQL, then you can check for existence of table by querying information_schema.columns and based on this perform rename

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

回答by user2677579

rename table oldtablename to newtablename

将表 oldtablename 重命名为 newtablename