【发布时间】:2017-06-09 21:25:07
【问题描述】:
我有一个存储函数,它的工作是遍历并分析来自多个表的大量数据。虽然大多数表都是静态的——我可以声明游标来遍历数据——但有些表是事先不知道的,特别是语言集表(例如language_en、language_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;
但是现在,我如何循环遍历这个查询的结果?
【问题讨论】:
-
选项可以是动态游标,见MariaDB/MySQL: Cursors for Dynamic SQL。
标签: mysql loops stored-procedures prepared-statement stored-functions