在SQL中重命名数据库表错误

时间:2013-12-29 23:38:07

标签: mysql dynamic-sql

我正在尝试使用此处给出的答案重命名我的数据库表:

How To have Dynamic SQL in MySQL Stored Procedure

但是当我尝试在phpMyAdmin SQL选项卡中运行以下内容时出现sql错误:

delimiter // 
CREATE PROCEDURE dynamic(IN tbl CHAR(64), IN col CHAR(64))
BEGIN
    SET @s = CONCAT('SELECT 'RENAME TABLE ', 
             GROUP_CONCAT('', TABLE_SCHEMA, ''.'', TABLE_NAME,
             ' TO ', TABLE_SCHEMA, ''='.osx_''', TABLE_NAME, '')) AS q
             FROM 
             information_schema.Tables WHERE TABLE_SCHEMA='my_database'';;'
    PREPARE stmt FROM @s;
    EXECUTE stmt;
    DEALLOCATE PREPARE stmt;
END
//
delimiter ;

错误如下:

#1064 - 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  
'RENAME TABLE ', GROUP_CONCAT('', TABLE_SCHEMA, ''.'', TABLE_NAME,' at line 3

我没有看到错误,有人能发现它吗?

- 编辑 -

在查看Max的答案后,我使用反引号重新格式化了查询:

CREATE PROCEDURE dynamic(IN tbl CHAR(64), IN col CHAR(64))
BEGIN
    SET @s = SELECT
             CONCAT('RENAME TABLE ', 
             GROUP_CONCAT('`', TABLE_SCHEMA, '`.`', TABLE_NAME, 
             '` TO `', TABLE_SCHEMA, '`.`osx_', TABLE_NAME, '`')) AS q
             FROM 
             `information_schema`.`Tables` WHERE TABLE_SCHEMA=`my_database`;
    PREPARE stmt FROM @s;
    EXECUTE stmt;
    DEALLOCATE PREPARE stmt;
END

从我发现的另一个例子(见下文),我仍然得到sql错误:

#1064 - 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 'SELECT
             CONCAT('RENAME TABLE ', 
             GROUP_CONCAT('`', TABLE_SCHEMA, '`.`',' at line 3 

我也尝试过另一个例子:

SELECT 
    CONCAT('RENAME TABLE ', 
    GROUP_CONCAT('`', TABLE_SCHEMA, '`.`', TABLE_NAME, 
    '` TO `', TABLE_SCHEMA, '`.`osx_', TABLE_NAME, '`')) AS q
FROM 
    `information_schema`.`Tables` WHERE TABLE_SCHEMA='my_database';

执行但会产生以下警告:

This table does not contain a unique column. 
Grid edit, checkbox, Edit, Copy and Delete features are not available.

并且对db没有任何作用。

HELP!

1 个答案:

答案 0 :(得分:0)

'SELECT 'RENAME

您已使用单引号打开CONCAT()的参数,当MySQL看到另一个参数时,它需要下一个参数。
您可以转义引号或使用双引号作为字符串文字。

CONCAT('SELECT "RENAME TABLE ", GROUP_CONCAT( ...