通过运行sql文件增加mysql不存在的列

来源:互联网 发布:广州pm2.5实时数据 编辑:程序博客网 时间:2024/06/06 12:49
表中增加字段的sql语句为:
ALTER TABLE `mytable` ADD COLUMN `param1`  int(4) NULL DEFAULT 0 COMMENT 'test' ;
重复执行会报错,如果项目通过运行sql文件来改变数据库结构,就有可能因为这样的语句导致运行中断,理所当让的就想通过判断需要添加的字段是否不存在在执行上述语句,
写成如下:
if not exists(SELECT 1 from information_schema.COLUMNS where TABLE_SCHEMA="dbtest" and TABLE_NAME="mytable" and COLUMN_NAME="param1") then        
     ALTER TABLE `mytable` ADD COLUMN `param1`  int(4) NULL DEFAULT 0 COMMENT 'test' ;
end if;
但是执行报错,貌似不能在sql文件中些if not exist或者if exist这样的语句,无奈,改成先创建一个存储过程,然后执行存储过程,最后在删除存储过程的方式绕道实现:
CREATE PROCEDURE `g_tmp_test`()
BEGIN
    if not exists(SELECT 1 from information_schema.COLUMNS where TABLE_SCHEMA="dbtest" and TABLE_NAME="mytable" and COLUMN_NAME="param1") then        
        ALTER TABLE `mytable` ADD COLUMN `param1`  int(4) NULL DEFAULT 0 COMMENT 'test' ;
    end if;

END;

CALL `g_tmp_test`();

DROP PROCEDURE `g_tmp_test`;

不知道有什么更加简单的实现
原创粉丝点击