一尘不染

MySQL遍历表

mysql

我想从包含一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();

阅读 297

收藏
2020-05-17

共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.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();
2020-05-17