我想从包含一first_name列的每个表中输出数据。我将以下过程放在一起,但是在我的循环中,mysql从字面上解释表名,而不是评估变量table_name。解决办法是什么?
first_name
table_name
delimiter // drop procedure if exists hunt // create procedure hunt() begin DECLARE done int default false; DECLARE table_name CHAR(255); DECLARE cur1 cursor for SELECT TABLE_NAME FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_SCHEMA = "wholesale_production" and COLUMN_NAME LIKE "%first%" ; DECLARE CONTINUE HANDLER FOR NOT FOUND SET done = TRUE; open cur1; myloop: loop fetch cur1 into table_name; if done then leave myloop; end if; select * from `wholesale_production`.table_name where created_at >= '2012-10-01'; end loop; close cur1; end // delimiter ; call hunt();
尝试这个:
delimiter // drop procedure if exists hunt // create procedure hunt() begin DECLARE done int default false; DECLARE table_name CHAR(255); DECLARE cur1 cursor for SELECT TABLE_NAME FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_SCHEMA = "wholesale_production" and COLUMN_NAME LIKE "%first%" ; DECLARE CONTINUE HANDLER FOR NOT FOUND SET done = TRUE; open cur1; myloop: loop fetch cur1 into table_name; if done then leave myloop; end if; set @sql = CONCAT('select * from `wholesale_production`.', table_name, ' where created_at >= '2012-10-01'); prepare stmt from @sql; execute stmt; drop prepare stmt; end loop; close cur1; end // delimiter ; call hunt();