因为要升级程序,需要根据店铺代码,增加表 ks_goods 一个字段,存储过程如下:
DELIMITER //
DROP PROCEDURE IF EXISTS `checkTabColumns`;
CREATE PROCEDURE checkTabColumns()
BEGIN
#定义变量
declare CurrentDatabase VARCHAR(100);
declare rs char(4);
declare mdstr char(10);#这个变量的值就是我想增加的字段名!
declare cursor_finished int(1);
#定义游标
declare cursor_store CURSOR for select storeSymbol from ks_store;
declare CONTINUE HANDLER FOR NOT FOUND SET cursor_finished = 1; set CurrentDatabase = database();
open cursor_store;
loop1:loop
fetch cursor_store into rs;
if cursor_finished=1 then
leave loop1;
end if;
set  mdstr = CONCAT("md_",rs);#我想要的字段名格式是: md_SA
select mdstr;#这里mdstr的确已经赋值为我想的要格式!
#检查是否已经有了该字段
if not exists (select * from information_schema.columns where TABLE_SCHEMA=CurrentDatabase AND TABLE_NAME='ks_goods' AND COLUMN_NAME=mdstr) then
alter table `ks_goods` add column  mdstr tinyint(1) NOT NULL DEFAULT 0 COMMENT '1:本商品属于该代码门店,0:不属于' after `isvalid`;
#这一句,虽然增加了一个新字段,但字段名不是md_SA,而就是mdstr???为什么?怎么才能让增加的字段名是md_SA?
end if; 
end loop loop1;
close cursor_store;
END//
DELIMITER ;
CALL checkTabColumns();实际增加的字段如下图: