循环 MariaDB 的隐式游标似乎不起作用

Implicit cursor for loop MariaDB doesn't seem to work

我必须在我的数据库中搜索一个 table 名称,其中存在指定的列值。 列名是 "Nummer",我想将该值作为过程的参数。 我使用的 DBMS 是 MariaDB 10.3

我的想法是首先 select 每个 Table 列 'Nummer' 存在,然后遍历这些 table 并检查该值是否存在。 然后我想 "return" 找到值的 table 名称。

我已经找到所有 "Nummer" 列存在的 table:

select table_name from information_schema.columns where column_name = 'Nummer'

现在我认为使用 for 循环并遍历每个 table 来搜索值会很有用:

create or replace procedure Forloop (
    in param_nummer int unsigned 
    )
    for i in (select table_name from information_schema.columns where column_name = 'Nummer')
    do 
        -- if exists (select * from i where 'Nummer' = param_nummer);
        -- return i (table_name) ?
    end for;
end//

delimiter;
call forloop();

问题是,当我执行程序时,MariaDB 似乎没有在 select 语句中使用隐式游标 "i"。 我收到错误 "dbName.i" not found,或类似的错误。 我怎样才能做到这一点?

这是您需要的代码的 部分

在你的尝试中,你做了 SELECT table_name ...。而不仅仅是 table_name,构建您需要执行的查询。使用凌乱的 CONCAT(...)(我将在下面提供)来执行此操作。

SELECT CONCAT("select 'table_name', nummer = param_nummer FROM table_name")
         from information_schema.columns
         where column_name = 'nummer'

在下一步之前,观察 select 的输出。应该是像

这样的几行
select 'some_table', nummer = 123 FROM some_table
select 'another_table', nummer = 123 FROM another_table

然后你必须prepareexecute找到每一行。这会给你

some_table    1
another_table 0

其中 1 表示真,0 表示假。

好的,现在我将修复 CONCAT 使其工作。请记住,sql 与许多其他语言一样, 没有 通往 "interpolate" 的途径。也就是说,我们需要完全依赖CONCAT.

SELECT CONCAT("select 'table_name', nummer = param_nummer FROM table_name")

-->

SELECT CONCAT("select '", table_name, "', nummer = ", param_nummer, " FROM ", table_name)