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

前端 未结 1 1620
轻奢々
轻奢々 2020-12-06 01:47

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 a         


        
相关标签:
1条回答
  • 2020-12-06 02:12

    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 讨论(0)
提交回复
热议问题