更改列名

时间:2017-12-22 11:26:59

标签: mysql sql

我需要创建一个动态过程,以便每当我需要重命名表的一列时,我都会传递所需的参数,并且它会毫无错误地执行。所以验证IF。

此代码生成的错误如下:

  

您的SQL语法有错误;检查手册   对应于您的MySQL服务器版本,以便使用正确的语法   附近' IF EXISTS(SELECT * FROM information_schema.columns WHERE   table_name ='人物''在第1行

DROP PROCEDURE IF EXISTS `change_column_name`;

DELIMITER ;;
CREATE PROCEDURE `change_column_name`(IN tableName VARCHAR(100), IN columnName VARCHAR(100), IN newColumnName VARCHAR(100), IN columnType VARCHAR(20), IN defaultValue VARCHAR(100))
BEGIN
    SET @query = CONCAT('IF EXISTS (SELECT * FROM information_schema.columns WHERE table_name = \'', tableName, '\' AND column_name = \'', columnName, '\') THEN
                                ALTER TABLE \'', tableName, '\' CHANGE COLUMN \'', columnName, '\' \'', newColumnName, '\' ', columnType, ' DEFAULT ', defaultValue, ';
                        END IF;');

    PREPARE stmt1 FROM @query;
    EXECUTE stmt1;
    DEALLOCATE PREPARE stmt1;
END ;;
DELIMITER ;

CALL `change_column_name`('People', 'Nme', 'Name', 'VARCHAR(50)', 'NULL');

1 个答案:

答案 0 :(得分:0)

解决了,步骤的方式是错误的。

DROP PROCEDURE IF EXISTS `change_column_name`;

DELIMITER ;;
CREATE PROCEDURE `change_column_name`(IN tableName VARCHAR(100), IN columnName VARCHAR(100), IN newColumnName VARCHAR(100), IN columnType VARCHAR(20), IN defaultValue VARCHAR(100))
BEGIN
    IF EXISTS (SELECT * FROM information_schema.COLUMNS WHERE table_name = tableName AND column_name = columnName) THEN
        SET @query = CONCAT('ALTER TABLE `', tableName, '` CHANGE COLUMN `', columnName, '` `', newColumnName, '` ', columnType, ' DEFAULT ', defaultValue, ';');
        PREPARE stmt1 FROM @query;
        EXECUTE stmt1;
        DEALLOCATE PREPARE stmt1;
    END IF;    
END ;;
DELIMITER ;

CALL `change_column_name`('People', 'Nme', 'Name', 'VARCHAR(50)', 'NULL');