RENAME TABLE

语法

RENAME TABLE tbl_name 
  [WAIT n | NOWAIT]
  TO new_tbl_name
    [, tbl_name2 TO new_tbl_name2] ...

描述

该语句可以重命名一个或多个表或视图,但不会改变它们相关的权限。

rename操作是原子性的,这意味着其他会话无法访问正在执行的rename语句所涉及的表。无法重命名为已存在的表或视图,但可以通过小技巧来实现。例如,如果已存在一个表old_table,可以创建另一个具有相同结构的空表new_table,然后使用该空表替换已存在的表(假定不存在backup_table表):

CREATE TABLE new_table (...);
RENAME TABLE old_table TO backup_table, new_table TO old_table;

tbl_name可以指定为db_name.tbl_name。见Identifier Qualifiers。这使得RENAME可以将表从一个数据库移动到另一个数据库下(只要两个数据库在同一文件系统下):

RENAME TABLE db1.t TO db2.t;

注意,如果已经存在涉及表的触发器,则无法跨数据库移动,如果这么做,将报如下错误信息:

ERROR 1435 (HY000): Trigger in wrong schema

视图同样无法跨数据库移动:

ERROR 1450 (HY000): Changing schema from 'old_db' to 'new_db' is not allowed.

RENAME TABLE无法操作临时表,可以使用ALTER TABLE来实现:

CREATE TEMPORARY TABLE t1 (c INT);

ALTER TABLE t1 RENAME TO t2;

如果RENAME TABLE重命名了多于一个表且其中一个命名失败时,所有的包括已经执行命名操作的表都会回滚,因为rename操作是原子性的。

rename操作按照语句中指定的顺序对表进行重命名。鉴于此,可以交换两表之间的数据:

RENAME TABLE t1 TO tmp_table,
    t2 TO t1,
    tmp_table TO t2;
MariaDB starting with 10.3.0

WAIT/NOWAIT

可以设置锁等待超时时间。见WAIT and NOWAIT

Comments

Comments loading...
Content reproduced on this site is the property of its respective owners, and this content is not reviewed in advance by MariaDB. The views, information and opinions expressed by this content do not necessarily represent those of MariaDB or any other party.