如何在phpmyadmin中声明游标?

时间:2018-05-29 20:06:44

标签: mysql cursor procedure declare

当我添加此代码时出现错误,我无法修复它。

DECLARE c1 cursor FOR SELECT i FROM integers;
OPEN c1;
FETCH c1 INTO L1;
FETCH c1 INTO L2;
FETCH c1 INTO L3;
FETCH c1 INTO L4;
FETCH c1 INTO L5;
FETCH c1 INTO L6;
CLOSE c1;    

以下是完整代码。如果没有上面的代码,过程执行并返回六行,整数表中没有重复的数字,我想写入L1,L2,L3,L4,L5,L6,然后插入表kupony。 '的howmany'是IN过程参数。

DELIMITER $$

CREATE PROCEDURE addTickets (IN howMany INT)
BEGIN

DECLARE L1 INT default 0;
DECLARE L2 INT default 0;
DECLARE L3 INT default 0;
DECLARE L4 INT default 0;
DECLARE L5 INT default 0;
DECLARE L6 INT default 0;
DECLARE count1 INT;
set count1 = 0;


while count1 < howMany DO
DECLARE c1 FOR SELECT i FROM integers WHERE i BETWEEN 1 AND 49 ORDER BY RAND() LIMIT 6;
OPEN c1;
FETCH c1 INTO L1;
FETCH c1 INTO L2;
FETCH c1 INTO L3;
FETCH c1 INTO L4;
FETCH c1 INTO L5;
FETCH c1 INTO L6;
CLOSE c1;    
INSERT INTO kupony VALUES(NULL, 1, L1, L2, L3, L4, L5, L6, -1, '2018-01-01', -1);
set count1 = count1 + 1;
end while;

END$$

DELIMITER ;

1 个答案:

答案 0 :(得分:0)

您必须在嵌套游标周围放置一个BEGIN ... END;块。

DELIMITER $$

CREATE PROCEDURE addTickets (IN howMany INT)
BEGIN

DECLARE L1 INT default 0;
DECLARE L2 INT default 0;
DECLARE L3 INT default 0;
DECLARE L4 INT default 0;
DECLARE L5 INT default 0;
DECLARE L6 INT default 0;
DECLARE count1 INT default 0;


while count1 < howMany DO
BEGIN
DECLARE c1 CURSOR FOR SELECT i FROM integers WHERE i BETWEEN 1 AND 49 ORDER BY RAND() LIMIT 6;
OPEN c1;
FETCH c1 INTO L1;
FETCH c1 INTO L2;
FETCH c1 INTO L3;
FETCH c1 INTO L4;
FETCH c1 INTO L5;
FETCH c1 INTO L6;
CLOSE c1;    
INSERT INTO kupony VALUES(NULL, 1, L1, L2, L3, L4, L5, L6, -1, '2018-01-01', -1);
set count1 = count1 + 1;
END;
end while;

END$$

DELIMITER ;