Thursday, March 31, 2011

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)' );
From stackoverflow
  • Short answer: No.

    Long answer: Why? Your data model should not be as fluid as you seem to think you want it to be. Lock it down. Normalize it. If you need arbitrary columnar values, use a User Defined Field pattern. Don't go messing with your tables at a whim. Not a good idea.

    Dr.Dredel : thanks! I was just trying to prevent seeing a bunch of "error column already exists" as we run the script across multiple DBs, if it's accidentally run multiple times on the same box.
    Randolpho : So this is for an install script of some sort? I wouldn't bother worrying about whether or not it's run multiple times. Handle that issue in documentation.
    Quassnoi : It's actually possible, see my post.
  • 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;
    //
    
    Randolpho : Wow, talk about SQL injection!
    Quassnoi : It's in no way what I'd advise my children to do, but it's still possible :)

0 comments:

Post a Comment