【发布时间】:2019-04-29 03:16:48
【问题描述】:
场景:我有一个存储过程,它根据 2 个输入从表中获取数据:日期和字符串(这是列名)。第一个过程从另一个过程调用,该过程使用游标循环遍历表的行并将每一行传递给第一个过程的字符串(要检查的列名)。我对第二个过程(直接调用)的输入是日期。
问题:我的第一个过程在我自己调用它时运行良好。我的第二个过程是抛出一些我不知道如何修复的语法错误。
Obs:我已经在这里查看了有关此主题的其他答案 例如 Using Cursor in a Loop of a stored procedure 和 How 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