Using ALTER to drop a column if it exists in MySQL

后端 未结 8 1855
别跟我提以往
别跟我提以往 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:50

    I know this is an old thread, but there is a simple way to handle this requirement without using stored procedures. This may help someone.

    set @exist_Check := (
        select count(*) from information_schema.columns 
        where TABLE_NAME='YOUR_TABLE' 
        and COLUMN_NAME='YOUR_COLUMN' 
        and TABLE_SCHEMA=database()
    ) ;
    set @sqlstmt := if(@exist_Check>0,'alter table YOUR_TABLE drop column YOUR_COLUMN', 'select ''''') ;
    prepare stmt from @sqlstmt ;
    execute stmt ;
    

    Hope this helps someone, as it did me (after a lot of trial and error).

提交回复
热议问题