简体   繁体   中英

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...

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. 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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