Using ALTER to drop a column if it exists in MySQL

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

    I realise this thread is quite old now, but I was having the same problem. This was my very basic solution using the MySQL Workbench, but it worked fine...

    1. get a new sql editor and execute SHOW TABLES to get a list of your tables
    2. select all of the rows, and choose copy to clipboard (unquoted) from the context menu
    3. paste the list of names into another editor tab
    4. write your query, ie ALTER TABLE x DROP a;
    5. do some copying and pasting, so you end up with separate query for each table
    6. Toggle whether the workbench should stop when an error occurs
    7. Hit execute and look through the output log

    any tables which had the table now haven't any tables which didn't will have shown an error in the logs

    then you can find/replace 'drop a' change it to 'ADD COLUMN b INT NULL' etc and run the whole thing again....

    a bit clunky, but at last you get the end result and you can control/monitor the whole process and remember to save you sql scripts in case you need them again.

提交回复
热议问题