Using ALTER to drop a column if it exists in MySQL

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

    You can use this script, use your column, schema and table name

     IF EXISTS (SELECT *
                             FROM INFORMATION_SCHEMA.COLUMNS
                             WHERE TABLE_NAME = 'TableName' AND COLUMN_NAME = 'ColumnName' 
                                                 AND TABLE_SCHEMA = SchemaName)
        BEGIN
           ALTER TABLE TableName DROP COLUMN ColumnName;
        END;
    
    0 讨论(0)
  • 2020-11-29 03:55

    Chase Seibert's answer works, but I'd add that if you have several schemata you want to alter the SELECT thus:

    select * from information_schema.columns where table_schema in (select schema()) and table_name=...
    
    0 讨论(0)
提交回复
热议问题