Using ALTER to drop a column if it exists in MySQL

后端 未结 8 1798
别跟我提以往
别跟我提以往 2020-11-29 02:57

How can ALTER be used to drop a column in a MySQL table if that column exists?

I know I can use ALTER TABLE my_table DROP COLUMN my_column, but that wi

8条回答
  •  自闭症患者
    2020-11-29 03:32

    There is no language level support for this in MySQL. Here is a work-around involving MySQL information_schema meta-data in 5.0+, but it won't address your issue in 4.0.18.

    drop procedure if exists schema_change;
    
    delimiter ';;'
    create procedure schema_change() begin
    
        /* delete columns if they exist */
        if exists (select * from information_schema.columns where table_schema = schema() and table_name = 'table1' and column_name = 'column1') then
            alter table table1 drop column `column1`;
        end if;
        if exists (select * from information_schema.columns where table_schema = schema() and table_name = 'table1' and column_name = 'column2') then
            alter table table1 drop column `column2`;
        end if;
    
        /* add columns */
        alter table table1 add column `column1` varchar(255) NULL;
        alter table table1 add column `column2` varchar(255) NULL;
    
    end;;
    
    delimiter ';'
    call schema_change();
    
    drop procedure if exists schema_change;
    

    I wrote some more detailed information in a blog post.

提交回复
热议问题