需求描述:
现数据库有好多个分表统一命名t_new_开头,业务需要给每个表增加一个字段city_id 。
各项参数:
参数项 | 参数 |
---|---|
数据库名: | mydatabase |
表名 | t_new_1 , t_new_2, t_new_3, t_new_4 , … |
搜索办法 | t_new_% |
排除表 | t_new_101 |
新建字段 | city_id int(8) DEFAULT NULL |
执行 | CALL customerAddField(); |
DELIMITER //
drop procedure if exists customerAddField//
CREATE PROCEDURE customerAddField()
BEGIN
DECLARE tableName varchar(100) default '';
DECLARE done INT DEFAULT 0;
DECLARE taskCursor CURSOR FOR select table_name from information_schema.tables where table_schema='mydatabase' and table_name like 't_new_%' and table_name != 't_new_101' ;
DECLARE CONTINUE HANDLER FOR NOT FOUND SET done = 1;
OPEN taskCursor;
REPEAT
FETCH taskCursor INTO tableName;
IF not done THEN
set @sql2=concat('ALTER TABLE ',tableName,' ADD city_id int(8) DEFAULT NULL');
PREPARE stmt from @sql2;
execute stmt;
END IF;
UNTIL done END REPEAT;
CLOSE taskCursor;
END
//
DELIMITER;
CALL customerAddField();