嵌套Cursor调用仅在MYSQL中调用内部游标一次

时间:2014-04-10 22:54:51

标签: mysql database cursor

有2个程序。单独测试时,它们执行正常。 当第一个SP呼叫第二个SP时,在第一个呼叫后不会调用它。 请帮助解决问题。 第一个光标:

    BEGIN
DECLARE vAttendEmpid,vNoOfDays, vempid INT DEFAULT 0;
DECLARE processed BOOLEAN DEFAULT FALSE;
DECLARE curEmp CURSOR FOR Select distinct empid as d1 from  rawattendance where DATE_FORMAT(     indatetime,'%m') =  process_month and DATE_FORMAT( indatetime,'%Y') = process_year order by     empid;

DECLARE CONTINUE HANDLER FOR NOT FOUND SET processed = TRUE ;

    OPEN curEmp;
    loopemp: LOOP
    FETCH FROM curEmp INTO vEmpid;

        IF processed THEN
            CLOSE curEmp;
            LEAVE loopemp;
        END IF;
        --select vEmpid;
        CALL sp_attendance(vEmpid,process_month,process_year);
    END LOOP loopemp;
END

第二个光标..嵌套光标

BEGIN
DECLARE  vInDateTime, vOutDateTime,vTempInDateTime, vTempOutDateTime DATETIME ;
DECLARE vAttendEmpid ,vDiffHr INT DEFAULT 0;
DECLARE  eprocessed BOOLEAN DEFAULT FALSE;
DECLARE curAttendance CURSOR FOR Select empid, indatetime ,outdatetime from  rawattendance     where    empid=vEmpid and DATE_FORMAT( indatetime, '%m' ) =  process_month and DATE_FORMAT( indatetime, '%Y' ) = process_year 
    order by indatetime;

    OPEN curAttendance;
    att_loop:LOOP
    FETCH curAttendance INTO vAttendEmpid, vInDateTime,vOutDateTime;

    select concat ('In Time 0 ==',vInDateTime, ' out ==', vOutDateTime, ' Empid=',vAttendEmpid);
            select 'looping';

IF eprocessed THEN
    select 'loop end';
    select concat ('In Time 4 ==',vTempInDateTime, ' out ==', vTempOutDateTime, ' Empid=',vAttendEmpid);
        SET vDiffHr =TIMESTAMPDIFF(HOUR,vTempInDateTime,vTempOutDateTime);

    insert into emp_attendance_processed(empid,in_date_time, out_date_time, workedhr) 
        values(vAttendEmpid,vTempInDateTime,vTempOutDateTime, vDiffHr);
        SET vTempOutDateTime=vOutDateTime;
        CLOSE curAttendance;
    END IF;
END LOOP att_loop;  
END

1 个答案:

答案 0 :(得分:0)

尝试在调用内部过程后重置continue处理程序变量processed

SET processed = FALSE;

问题是,如果第一个过程中的游标没有返回任何行,而且嵌套的HANDLER FOR NOT FOUND没有返回任何行,则不仅会执行SELECT。并且由于您的第二个过程包含SELECT个语句,我相信其中一个语句至少返回一个空集。如果不是这样,可能与分配的错误参数有关。

OPEN curEmp;
loopemp: LOOP
FETCH FROM curEmp INTO vEmpid;

    IF processed THEN
        CLOSE curEmp;
        LEAVE loopemp;
    END IF;
    --select vEmpid;
    CALL sp_attendance(vEmpid,process_month,process_year);
    SET processed = FALSE;
END LOOP loopemp;