开发者

MySQL: How to add a column if it doesn't already exist?

开发者 https://www.devze.com 2023-01-07 05:49 出处:网络
I want to add a colu开发者_JS百科mn 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?

I want to add a colu开发者_JS百科mn 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;

Reference:

  • The INFORMATION_SCHEMA COLUMNS Table
0

精彩评论

暂无评论...
验证码 换一张
取 消