mySql 如果不存在则删除列

mySql drop column if not exist

我正在尝试编写向下迁移 SQL 代码,并且我编写了以下代码。它不起作用,我收到一条错误消息:

Can't DROP 'column_name_arg'; check that column/key exists

这意味着我没有使用参数变量。

感谢任何解决此问题的帮助或提示,以及改进或简化它的反馈。我也想知道这是程序还是准备好的语句?

drop procedure if exists schema_change;

delimiter ';;'
create procedure schema_change(in table_name_arg VARCHAR(40), in column_name_arg VARCHAR(40))
begin
    if exists(select *
              from information_schema.columns
              where table_schema = schema()
                and table_name = table_name_arg
                and column_name = column_name_arg) then
        alter table TestResults
            drop column column_name_arg;
    end if;
end;;

delimiter ';'
call schema_change('TestResults', 'minScore');
call schema_change('TestResults', 'maxScore');

drop procedure if exists schema_change;

您可以使用准备好的语句来执行此操作。列名不能是变量。

创建程序:

drop procedure if exists schema_change;

delimiter //
create procedure schema_change(in table_name_arg VARCHAR(40), in column_name_arg VARCHAR(40))
begin
    if exists(select *
              from information_schema.columns
              where table_schema = schema()
                and table_name = table_name_arg
                and column_name = column_name_arg) then
            SELECT CONCAT('ALTER TABLE TestResults drop column ',column_name_arg) INTO @sqlv;
            PREPARE stmt FROM @sqlv;
            EXECUTE stmt;
            DEALLOCATE PREPARE stmt;
    end if;
end;
//
delimiter ;

在table之前显示:

MariaDB [bernd]> desc TestResults;
+-------+---------+------+-----+---------+-------+
| Field | Type    | Null | Key | Default | Extra |
+-------+---------+------+-----+---------+-------+
| x     | int(11) | YES  |     | NULL    |       |
| y     | int(11) | YES  |     | NULL    |       |
+-------+---------+------+-----+---------+-------+
2 rows in set (0.00 sec)

调用程序:

MariaDB [bernd]> call schema_change('TestResults', 'y');
Query OK, 0 rows affected (0.03 sec)

显示 table 之后:

MariaDB [bernd]> desc TestResults;
+-------+---------+------+-----+---------+-------+
| Field | Type    | Null | Key | Default | Extra |
+-------+---------+------+-----+---------+-------+
| x     | int(11) | YES  |     | NULL    |       |
+-------+---------+------+-----+---------+-------+
1 row in set (0.00 sec)

MariaDB [bernd]>