循环在存储过程内的预准备语句查询的结果

时间:2017-01-24 21:08:51

标签: mysql loops stored-procedures prepared-statement stored-functions

我有一个存储函数,它的工作是从几个表中分析大量数据。虽然大多数表是静态的 - 我可以声明游标循环数据 - 但是有些表是事先不知道的,特别是语言集表(例如language_enlanguage_fr等)。也就是说,在写入存储函数时,我不知道哪些表存在。

在存储的函数本身中,我可以这样做:

declare cLang cursor for
    SELECT table_name FROM information_schema.tables
    WHERE table_schema=database() and table_name like 'language_%';

declare continue handler for not found set exit_loop = true;

open cLang;
set exit_loop = false;
cLang_loop: loop
    fetch cLang into str;

    ...
end loop;

这样,我可以遍历数据库中存在的所有语言表。然后我需要从每个数据中获取数据并循环执行我的分析。显然,我不能为每个声明一个游标,因为我不知道哪些表存在。我可以使用预备语句:

fetch cLang into tableName;

set @stmt_text = concat("SELECT t_code, t_string FROM ", str);
prepare stmt from @stmt_text;
execute stmt using @scId;

但是现在,我如何循环查询此查询的结果?

1 个答案:

答案 0 :(得分:0)

我最终做到这一点的方式就是这样。我没有创建动态游标来查询表,而是有一个预定义的临时表,并在该表上声明了一个光标。然后动态sql插入临时表,常规游标迭代它。像这样:

declare cLang cursor for
    SELECT table_name FROM information_schema.tables WHERE table_schema=database() and table_name like 'language_%';

declare cCode cursor for
    SELECT t_code, t_string FROM tmp_lang;

declare continue handler for not found set exit_loop = true;

open cLang;
set exit_loop = false;

cLang_loop: loop
    fetch cLang into str;
    if exit_loop then
        close cLang;
        leave cLang_loop;
    else
        create temporary table tmp_lang (t_code varchar(50), t_string varchar(2000));

        set @stmt_text = concat(
            'insert into tmp_lang (t_code, t_string) SELECT t_code, t_string
            from ', str);
        prepare stmt from @stmt_text;
        execute stmt;

        if (select count(1) from tmp_lang) > 0 then

            open cCode;

            cCode_loop: loop
                fetch cCode into lCode, lString;
                if exit_loop then
                    close cCode;
                    set exit_loop = false;
                    leave cCode_loop;
                else
                    -- now I can do whatever I need with the data
                end if;
            end loop;

        end if;

        deallocate prepare stmt;
        drop table tmp_lang;
    end if;
end loop;