Mysql - add a column to a table if not exists

在mysql中我们可以在create table之前判断这个table是不是已经存在,如果已经存在则不创建,从而避免报错。
但是mysql并没有提供原生的方法在添加一个列之前判断这个列是否已经存在。
在实际项目中,我们可能需要判断列是否存在,如果不存在则添加某列,比如在一个项目的初始化sql脚本中。

我们可以创建一个存储过程来实现,如下:

drop procedure if exists AddColumnUnlessExists;
create procedure AddColumnUnlessExists(
    IN dbName tinytext,
    IN tableName tinytext,
    IN fieldName tinytext,
    IN fieldDef text)
begin
    IF NOT EXISTS (
        SELECT * FROM information_schema.COLUMNS
        WHERE column_name=fieldName
        and table_name=tableName
        and table_schema=dbName
        )
    THEN
        set @ddl=CONCAT('ALTER TABLE ',dbName,'.',tableName,
            ' ADD COLUMN ',fieldName,' ',fieldDef);
        prepare stmt from @ddl;
        execute stmt;
    END IF;
end;

使用方法:

call AddColumnUnlessExists(DATABASE(), 'test', 'name', 'varchar(50) NULL');
call AddColumnUnlessExists('test', 'test', 'name2', 'varchar(50) NULL');
-- 对一些特殊的字段名(如order)、数据库名或表名(如含有-_等特殊字符),使用你``引起来
call AddColumnUnlessExists('`db-test`', '`t_test`', '`order`', 'varchar(50) NULL');

使用完后如果不再需要可删除:

drop procedure AddColumnUnlessExists;

或者,更简单粗暴地,你可以在初始化数据库时直接忽略错误:

<!-- 在初始化数据库时,遇到错误是否继续,默认false -->
spring.datasource.continue-on-error=true
发布了67 篇原创文章 · 获赞 70 · 访问量 16万+

猜你喜欢

转载自blog.csdn.net/fukaiit/article/details/88764252