mysql -- 创建存储过程 往数据表中新增字段

需求:

  往某数据库的某个表中新增一个字段(若该字段已存在,则不做操作;若该字段不存在,则新增)

百度了n久,没有符合要求的例子,只有参考加自己琢磨,最终终于给弄出来了,以下是几个版本的更迭

第一版:

DELIMITER $$
CREATE PROCEDURE insert_column()
BEGIN
IF NOT EXISTS(SELECT 1 FROM information_schema.columns 
WHERE table_schema='ltivalley' AND table_name='t_luck' 
AND column_name='sss'  ) THEN 
alter table ltivalley.t_luck add sss varchar(255) not Null;
end if;
END
$$
DELIMITER ;

此存储过程可以做到往ltivalley数据库的t_luck表中新增一个sss的字段,但写死了,毫无灵活性,故没用!

 

第二版:

DELIMITER $$

CREATE PROCEDURE insert_column(in dbname varchar(255),in tbname varchar(255),in colname varchar(255))
set @sql_1= concat("IF NOT EXISTS(SELECT 1 FROM 
information_schema.columns WHERE table_schema=",dbname," 
AND table_name=",tbname," AND column_name=",colname,") 
THEN 
alter table ",dbname,".",tbname," add ",colname," 
varchar(255) not null;
end if;");
PREPARE stmt FROM @sql_1;

EXECUTE stmt;
DEALLOCATE PREPARE stmt;
END
$$
DELIMITER ;

创建存储过程没有问题,但当调用的时候就会出错,报 "IF"左右出错,原因是在mysql中IF只能存在于存储过程中,此处用EXECUTE stmt来执行,等于是不在存储过程里面执行if语句,所以报错,执行不了!故没用!

 

第三版

DELIMITER $$

CREATE PROCEDURE insert_column(in dbname varchar(255),in tbname varchar(255),in colname varchar(255))
BEGIN
SET @selec=CONCAT('SELECT 1  FROM information_schema.columns WHERE table_schema="',dbname,'" AND table_name="',tbname,'" AND column_name="',colname,'"');
PREPARE selec FROM @selec;   

SET @addcol=CONCAT('ALTER TABLE ',dbname,'.',tbname,' ADD ',colname,' VARCHAR(255)');
PREPARE addcol FROM @addcol;  

IF NOT EXISTS(EXECUTE selec;)THEN
EXECUTE addcol;
END IF;

END
$$
DELIMITER ;

无法创建存储过程,原因是在IF NOT EXISTS()中,不能执行EXECUTE selec语句,原因未知。故没用!

 

终极版

 

DROP PROCEDURE IF EXISTS insert_column;

DELIMITER $$
CREATE PROCEDURE insert_column(in dbname varchar(255),in tbname varchar(255),in colname varchar(255))
BEGIN
set @iscolexists = 0;
SET @selec=CONCAT('SELECT count(*) into @iscolexists  FROM information_schema.columns WHERE table_schema="',dbname,'" AND table_name="',tbname,'" AND column_name="',colname,'"');
PREPARE selec FROM @selec;   
EXECUTE selec;
DEALLOCATE PREPARE selec;

SET @addcol=CONCAT('ALTER TABLE ',dbname,'.',tbname,' ADD ',colname,' VARCHAR(255)');
PREPARE addcol FROM @addcol;  

IF(@iscolexists=0)THEN
EXECUTE addcol;
END IF;

END
$$
DELIMITER ;

 

 

 

最终的结果,先执行EXECUTE selec,将结果存放到一个变量@iscolexists中,然后再在IF()中判断@iscolexists的值,做相应操作。可用!

posted @ 2015-06-30 18:08  goodup  阅读(3615)  评论(0编辑  收藏  举报

如有不对之处,欢迎指出,一起成长