简体   繁体   English

是否可以通过存储过程更改mySql中的表?

[英]Is it possible to alter a table in mySql via stored procedures?

here's what I'd like to do in mySQL... I'm getting the feeling that this is simply not feasible, but would love to be wrong... 这就是我想在mySQL中做的事情...我觉得这根本不可行,但是我想爱错...

create procedure foo(IN MYTABLE varchar(50) , IN COLNAME varchar (50), IN MYTYPE varchar(50)) 
begin 
IF (select count(*) from information_schema.columns where table_name =MYTABLE and column_name = COLNAME) = 0 
THEN
alter table MYTABLE add column MYNAME MYTYPE; 
end;

call foo( 'table_foo' , 'column_bar' , 'varchar(100)' );

Don't know why on Earth you would want it, but it's possible: 不知道为什么在地球上你会想要它,但它有可能:

DELIMITER //
DROP PROCEDURE foo//
CREATE PROCEDURE foo(IN MYTABLE varchar(50) , IN COLNAME varchar (50), IN MYTYPE varchar(50))
BEGIN
  SET @ddl = CONCAT('alter table ', MYTABLE, ' add column (', COLNAME, ' ', MYTYPE, ')');
  PREPARE STMT FROM @ddl;
  EXECUTE STMT;
END;
//

Short answer to why I'd do it. 简短的回答为什么我这样做。

Updating a deployed database when the version of your schema changes in a released product. 在已发布产品中更改架构版本时更新已部署的数据库。 Shell scripting is a bad option for cross-platform code so scripting in SQL is great, just remember to drop the procedures after use. 对于跨平台代码来说,Shell脚本是一个糟糕的选择,因此SQL中的脚本很棒,只需记住在使用后删除这些程序。 If I have deployed 1.1 but am at 1.4 at time of update, i just run the 1.1->1.2, 1.2->1.3, and the 1.3->1.4 scripts in order. 如果我已经部署了1.1但是在更新时是1.4,我只是按顺序运行1.1-> 1.2,1.2-> 1.3和1.3-> 1.4脚本。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM