21

I'm getting this error while trying to create a procedure in MySQL:

Error Code: 1337
Variable or condition declaration after cursor or handler declaration

even after doing a lot of Googling I found no relevant solution to my problem. My procedure is as below:

DELIMITER //
CREATE PROCEDURE emp_dates(IN startDate DATE, IN endDate DATE)
BEGIN
DECLARE fromDt DATETIME;
DECLARE toDt DATETIME;
DECLARE done INT DEFAULT FALSE;
DECLARE employees CURSOR FOR SELECT empid FROM employees;
DECLARE CONTINUE HANDLER FOR NOT FOUND SET done=TRUE;
DECLARE emp VARCHAR(20);
SET fromDt=startDate;
SET toDt=endDate;

OPEN employees;

WHILE fromDt<=toDt DO
REPEAT
    FETCH employees INTO emp;
    IF NOT done THEN
    INSERT INTO new_attendance_2(attid,empid,dt) VALUES(DEFAULT,emp,fromDt);
    END IF
UNTIL done END REPEAT;
SET fromDt=DATE_ADD(fromDt, INTERVAL 1 DAY);
LOOP
CLOSE employees;
END
DELIMITER ;

The purpose is to create a procedure which will take two dates as input and insert records in other table for every day that comes in between of those two. Somebody please help! I appreciate any little help. Thanks a lot in advance.

4

2 回答 2

27

它抱怨:

Variable or condition declaration after cursor or handler declaration

所以我会看那个位置,你确实在游标和处理程序之后声明了变量:

   DECLARE employees CURSOR FOR SELECT empid FROM employees;
   DECLARE CONTINUE HANDLER FOR NOT FOUND SET done=TRUE;
>> DECLARE emp VARCHAR(20);

如果您因此修改您的声明,应该没问题:

DECLARE fromDt DATETIME;
DECLARE toDt DATETIME;
DECLARE done INT DEFAULT FALSE;
DECLARE emp VARCHAR(20);

DECLARE employees CURSOR FOR SELECT empid FROM employees;

DECLARE CONTINUE HANDLER FOR NOT FOUND SET done=TRUE;

订单必须是,按照这里

游标声明必须出现在处理程序声明之前以及变量和条件声明之后。

于 2013-09-13T07:55:43.337 回答
4

您需要重新排序您的声明。

Cursor declarations must appear before handler declarations 
and after variable and condition declarations.

http://dev.mysql.com/doc/refman/5.1/en/cursors.html

于 2013-09-13T07:55:15.183 回答