在MySQL中使用游标时,从DECLARE语句调用存储过程
作者:互联网
我试图在MySQL中使用游标多次调用存储过程.我想多次调用它作为my_id的值存在于某个临时表中,并迭代这些id并连接结果.
无论如何,我在这部分过程中遇到了麻烦:
DECLARE curs CURSOR FOR
SELECT something FROM somewhere;
我不想从某个地方选择一些东西.我想要类似的东西
DECLARE curs CURSOR FOR
CALL storedproc(@an_id);
DECLARE语句可以用来调用存储过程吗?或者它必须仅与SELECT相关联?谷歌搜索,我担心后者是这样的.
解决方法:
使用游标需要一些标准的样板代码来包围它.
使用游标从表中为每组值调用存储过程需要基本相同的样板.您可以从要获取的值(可以是临时表,基表或视图,可以包括对存储函数的调用)中选择要传递的值,然后使用这些值调用过程.
我在下面编写了一个语法上有效的样板代码示例,并附有注释来解释每个组件正在做什么.除了被要求做一些“仅仅因为”之外,我不喜欢的事情很少 – 所以一切都(希望)得到了解释.
您提到使用多个值调用过程,因此本示例使用2.
请注意,由于某种原因,发生她的事件按特定顺序排列.必须首先声明变量,必须在继续处理程序之前声明游标,并且循环必须遵循所有这些.这给人的印象是,这里存在一些相当极端的不灵活性,但实际情况并非如此.您可以通过在过程体内的BEGIN … END块内嵌套附加代码来重置排序;例如,如果你需要在循环中使用第二个游标,你只需在循环中声明它,在另一个BEGIN … END中.
DELIMITER $$
DROP PROCEDURE IF EXISTS `my_proc` $$
CREATE PROCEDURE `my_proc`(arg1 INT) -- 1 input argument; you might not need one
BEGIN
-- from https://stackoverflow.com/questions/35858541/call-a-stored-procedure-from-the-declare-statement-when-using-cursors-in-mysql
-- declare the program variables where we'll hold the values we're sending into the procedure;
-- declare as many of them as there are input arguments to the second procedure,
-- with appropriate data types.
DECLARE val1 INT DEFAULT NULL;
DECLARE val2 INT DEFAULT NULL;
-- we need a boolean variable to tell us when the cursor is out of data
DECLARE done TINYINT DEFAULT FALSE;
-- declare a cursor to select the desired columns from the desired source table1
-- the input argument (which you might or might not need) is used in this example for row selection
DECLARE cursor1 -- cursor1 is an arbitrary label, an identifier for the cursor
CURSOR FOR
SELECT t1.c1,
t1.c2
FROM table1 t1
WHERE c3 = arg1;
-- this fancy spacing is of course not required; all of this could go on the same line.
-- a cursor that runs out of data throws an exception; we need to catch this.
-- when the NOT FOUND condition fires, "done" -- which defaults to FALSE -- will be set to true,
-- and since this is a CONTINUE handler, execution continues with the next statement.
DECLARE CONTINUE HANDLER FOR NOT FOUND SET done = TRUE;
-- open the cursor
OPEN cursor1;
my_loop: -- loops have to have an arbitrary label; it's used to leave the loop
LOOP
-- read the values from the next row that is available in the cursor
FETCH NEXT FROM cursor1 INTO val1, val2;
IF done THEN -- this will be true when we are out of rows to read, so we go to the statement after END LOOP.
LEAVE my_loop;
ELSE -- val1 and val2 will be the next values from c1 and c2 in table t1,
-- so now we call the procedure with them for this "row"
CALL the_other_procedure(val1,val2);
-- maybe do more stuff here
END IF;
END LOOP;
-- execution continues here when LEAVE my_loop is encountered;
-- you might have more things you want to do here
END $$
DELIMITER ;
标签:mysql,stored-procedures,cursors 来源: https://codeday.me/bug/20191002/1844931.html