mysql - 在存储过程中使用游标循环行 MySQL

标签 mysql sql loops stored-procedures cursor

场景:我有一个存储过程,它根据两个输入从表中获取数据:日期和字符串(这是列名称)。第一个过程是从另一个过程调用的,该过程使用游标循环遍历表的行并将每一行传递给第一个过程的字符串(要检查的列名称)。我对第二个过程(即直接调用的过程)的输入是日期。

问题:当我单独调用第一个程序时,它运行良好。我的第二个过程引发了一些我不知道如何修复的语法错误。

观察:我已经在此处查看了有关此主题的一些其他答案 如Using Cursor in a Loop of a stored procedureHow can I loop through all rows of a table? (MySQL) 。实际上,我的第二个过程现在是我在 SE https://dba.stackexchange.com/questions/138549/mysql-loop-through-a-table-running-a-stored-procedure-on-each-entry 上找到的查询的修改版本。

问题:目前,代码在我的 @colval 声明中的第 5 行抛出错误。

代码:

-- Procedure for looping through rows of `wanted_columns` table:
delimiter $$
drop procedure if exists `data_check_loop` $$
create procedure `data_check_loop`(`wanted_date` date)
begin

set @dateval = `wanted_date`;
declare colval string default null;

-- boolean variable to indicate cursor is out of data
declare done tinyint default false;

-- declare a cursor to select the desired columns from the desired source table
declare cursor1
    cursor for
        select t1.c1
        from `wanted_columns` t1; 

-- catch exceptions
        declare continue handler for not found set done = true;

-- open the cursor
        open cursor1;
            my_loop: 
            loop
                fetch next from cursor1 into colval;
                if done then 
                    leave my_loop; 
                else  
                    call `set_column_stats`(colval, dateval);
                end if;
            end loop;
        close cursor1;

end $$
delimiter ;

问题:关于如何解决此问题有什么想法吗?

最佳答案

您的程序中存在一些问题。首先,如manual中所述:

DECLARE is permitted only inside a BEGIN ... END compound statement and must be at its start, before any other statements.

所以你需要移动你的

set @dateval = `wanted_date`;

在所有DECLARE之后(包括光标和继续处理程序)。

其次,您的 colval 声明不正确,string 不是有效的数据类型,应替换为 text:

declare colval text default null;

关于mysql - 在存储过程中使用游标循环行 MySQL,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53498706/

相关文章:

mysql - 尝试构建类似选择的 MySQL 查询失败

php - 使用 MySQL 数据库中的 PHP 显示 HTML 友好的特殊字符

同一属性的 SQL 数据库多个值 - 最佳实践?

sql - 为什么没有在此 select 语句中设置变量?

c# - 为什么是 i++ "unreachable code"?

loops - Ansible - 同时使用 with_items 和 with_sequence

mysql - 使用 MYSQL 触发器根据另一列更改列值

php - 我的删除查询不会从 mysql 中删除任何内容

LEFT JOIN后MySQL查询计算问题

android - 如何从字符串数组中随机获取文本?