我想从包含first_name
列的每个表中输出数据。我把以下过程放在一起,但在我的循环中,mysql按字面解释表名而不是评估变量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();
答案 0 :(得分:11)
试试这个:
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();
答案 1 :(得分:1)
对上面的一点编辑迭代所有表并选择它们。
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.TABLES
WHERE table_schema ='mbu4u';
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 `mbu4u`.',table_name);
prepare stmt from @sql;
execute stmt;
drop prepare stmt;
end loop;
close cur1;
end //
delimiter //
答案 2 :(得分:0)
table_name是保留令牌,使用“DECLARE table_name CHAR(255);”中的另一个变量名称。
答案 3 :(得分:-2)
在cur1中,您正在使用TABLE_NAME尝试使用表的真实姓名