MySQL - 在存储过程中更改表语法

时间:2013-06-24 07:07:30

标签: mysql stored-procedures parameter-passing alter-table

我已经创建了一个存储过程来更改列名,如下所示。

表格结构:

CREATE TABLE ``procedurecheck`` ( ``id`` int(10) NOT NULL AUTO_INCREMENT, ``colname`` varchar(50) NOT NULL, ``proccheck1`` varchar(50) NOT NULL, PRIMARY KEY (``id``) ) ENGINE=InnoDB DEFAULT CHARSET=latin1

This is a test code only to check procedures.

DELIMITER $$
CREATE PROCEDURE updateColumn(IN COLNAME varchar (50), IN NEWCOLNAME varchar (50))
BEGIN
  SET @ddl = CONCAT('alter table procedurecheck CHANGE (', COLNAME, ' ', NEWCOLNAME, ' VARCHAR(50) NOT NULL)');
  PREPARE STMT FROM @ddl;
  EXECUTE STMT;
END $$
DELIMITER ;

当我使用:

调用此函数时

CALL updateColumn('proccheck','newproccheck');

我收到错误,如下:

#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 '(proccheck newproccheck VARCHAR(50) NOT NULL)' at line 1

任何指针都会有所帮助。

由于

3 个答案:

答案 0 :(得分:1)

删除(),例如。

CONCAT('alter table procedurecheck CHANGE ', COLNAME, ' ', NEWCOLNAME, ' VARCHAR(50) NOT NULL');

答案 1 :(得分:0)

DROP PROCEDURE IF EXISTS pl_updateColumnName;
DELIMITER $$
CREATE PROCEDURE pl_updateColumnName(IN tblName varchar (50), IN COLNAME varchar (50), IN NEWCOLNAME varchar (50))
BEGIN
  SET @ddl = CONCAT(' alter table ', tblName  ,' CHANGE ', COLNAME, ' ', NEWCOLNAME, ' VARCHAR(50) NOT NULL');
  PREPARE STMT FROM @ddl;
  EXECUTE STMT;
END $$
DELIMITER ;

答案 2 :(得分:-2)

您可以尝试此存储过程:

DROP PROCEDURE IF EXISTS pl_alterColumnName;
DELIMITER $$
CREATE PROCEDURE pl_alterColumnName(IN tblName varchar (50), IN COLNAME varchar (50), IN NEWCOLNAME varchar (50))
BEGIN
  SET @ddl = CONCAT(' alter table ', tblName  ,' CHANGE ', COLNAME, ' ', NEWCOLNAME, ' VARCHAR(50) NOT NULL');
  PREPARE STMT FROM @ddl;
  EXECUTE STMT;
END $$
DELIMITER ;