MySQL:如果列不存在,如何添加?

2021-11-27 00:00:00 mysql alter-table

我想向表中添加一列,但如果它已经添加到表中,我不希望它失败.我怎样才能做到这一点?

I want to add a column to a table, but I don't want it to fail if it has already been added to the table. How can I achieve this?

# Add column fails if it already exists 
ALTER TABLE `TableName` ADD `ColumnName` int(1) NOT NULL default '0';

推荐答案

在存储过程中使用以下内容:

Use the following in a stored procedure:

IF NOT EXISTS( SELECT NULL
            FROM INFORMATION_SCHEMA.COLUMNS
           WHERE table_name = 'tablename'
             AND table_schema = 'db_name'
             AND column_name = 'columnname')  THEN

  ALTER TABLE `TableName` ADD `ColumnName` int(1) NOT NULL default '0';

END IF;

参考:

  • INFORMATION_SCHEMA COLUMNS 表

相关文章