正如西蒙在评论中指出的那样,您将需要使用存储过程和一些准备好的语句:
cat procedure.sql
DELIMITER $$
DROP PROCEDURE IF EXISTS alter_all $$
CREATE PROCEDURE alter_all()
BEGIN
DECLARE done INT DEFAULT 0;
DECLARE _schema VARCHAR(30);
DECLARE cur CURSOR FOR select SCHEMA_NAME from information_schema.SCHEMATA where SCHEMA_NAME like 'division_%';
DECLARE CONTINUE HANDLER FOR NOT FOUND SET done := 1;
OPEN cur;
alterLoop: LOOP
FETCH cur into _schema;
if done = 1 THEN
LEAVE alterLoop;
END IF;
SET @mystmt = concat('ALTER TABLE ', _schema, '.caching ADD COLUMN notes VARCHAR(4096)');
PREPARE stmt3 FROM @mystmt;
EXECUTE stmt3;
DEALLOCATE PREPARE stmt3;
END LOOP alterLoop;
CLOSE cur;
END $$
DELIMITER ;
有了它,让我们尝试一下(使用服务器版本:5.5.35-0ubuntu0.12.04.2 (Ubuntu)):
> create schema division_1 default character set 'UTF8';
> create table division_1.caching (id int not null auto_increment primary key, value varchar(10));
> create schema division_2 default character set 'UTF8';
> create table division_2.caching (id int not null auto_increment primary key, value varchar(10));
> use division_1;
> source procedure.sql
> CALL alter_all();
Query OK, 0 rows affected, 1 warning (0.05 sec)
> desc caching;
+-------+---------------+------+-----+---------+----------------+
| Field | Type | Null | Key | Default | Extra |
+-------+---------------+------+-----+---------+----------------+
| id | int(11) | NO | PRI | NULL | auto_increment |
| value | varchar(10) | YES | | NULL | |
| notes | varchar(4096) | YES | | NULL | |
+-------+---------------+------+-----+---------+----------------+
> desc division_2.caching
+-------+---------------+------+-----+---------+----------------+
| Field | Type | Null | Key | Default | Extra |
+-------+---------------+------+-----+---------+----------------+
| id | int(11) | NO | PRI | NULL | auto_increment |
| value | varchar(10) | YES | | NULL | |
| notes | varchar(4096) | YES | | NULL | |
+-------+---------------+------+-----+---------+----------------+