views:

151

answers:

2

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)' );
A: 

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.

Randolpho
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.
Dr.Dredel
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.
Randolpho
It's actually possible, see my post.
Quassnoi
A: 

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;
//
Quassnoi
Wow, talk about SQL injection!
Randolpho
It's in no way what I'd advise my children to do, but it's still possible :)
Quassnoi