13

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

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

1 回答 1

18

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

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;

参考:

于 2010-07-13T22:38:38.250 回答