【问题标题】:Using a cursor in a stored procedure to loop rows MySQL在存储过程中使用游标循环行 MySQL
【发布时间】:2019-04-29 03:16:48
【问题描述】:

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

问题:我的第一个过程在我自己调用它时运行良好。我的第二个过程是抛出一些我不知道如何修复的语法错误。

Obs:我已经在这里查看了有关此主题的其他答案 例如 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 ;

问题:关于如何解决此问题的任何想法?

【问题讨论】:

  • 所有declare 语句必须出现在任何代码之前,例如set @dateval = wanted_date`;
  • @Nick 光标呢?实际上,我只是移动了语句。同样的错误。
  • 来自manual:DECLARE 只允许在 BEGIN ... END 复合语句中,并且必须位于其开头,在任何其他语句之前。
  • @Nick 我刚刚将我的设置更改为在所有声明之后。仍然遇到同样的错误
  • 哦,是的,应该是text,而不是string

标签: mysql sql loops stored-procedures cursor


【解决方案1】:

您的程序中有几个问题。首先,如manual中所述:

DECLARE 只能在 BEGIN ... END 复合语句中使用,并且必须位于其开头,在任何其他语句之前。

所以你需要移动你的

set @dateval = `wanted_date`;

毕竟DECLAREs(包括光标和继续处理程序)。

其次,你对colval的声明不正确,string不是有效的数据类型,应该换成text

declare colval text default null;

【讨论】:

    猜你喜欢
    • 2011-03-14
    • 2013-09-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-10-23
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多