使用存储过程:
drop procedure if exists useCursor;
如果在mysql终端使用为命令终止符号,代替分号,因为分号在begin...end中会用到;
-> delimiter $$
CREATE PROCEDURE useCursor()
BEGIN
DECLARE oneAddr varchar(255) default '';
DECLARE allAddr varchar(40) default '';
DECLARE done INT DEFAULT 0;
DECLARE curl CURSOR FOR select table_name from information_schema.tables where table_schema='shard1' and table_name like 'chat_%';
DECLARE CONTINUE HANDLER FOR NOT FOUND SET done = 1;
OPEN curl;
REPEAT
FETCH curl INTO oneAddr;
IF not done THEN
set @sql=concat('alter table ',oneAddr,' add chat_id MEDIUMINT(8) UNSIGNED NOT NULL DEFAULT 0');
PREPARE stmt from @sql;
execute stmt;
END IF;
UNTIL done END REPEAT;
select allAddr;
CLOSE curl;
END;
$$
call useCursor()$$
最后在还原最终符号delimiter ;