MYSQL中的嵌套游标,游标无法正常工作

时间:2019-07-15 06:36:49

标签: mysql

我在MYSQL中创建了一个SP,以通过传感器按日期获取值。我的SP正确执行了内部游标,但未执行外部游标(第一个游标)。也就是说,我只有1天的数据,dateTable有一周的数据。

CREATE PROCEDURE `Analysis`()
BEGIN
declare v_date datetime;
declare v_sensor varchar(50);
DECLARE datecursHandler,sensorCursHandler BOOLEAN DEFAULT FALSE;

Block1: BEGIN 
declare datecursor CURSOR for 
select  distinct date from dateTable;
DECLARE CONTINUE HANDLER FOR NOT FOUND SET datecursHandler = TRUE;

Open datecursor;
datecurs: loop

FETCH datecursor into date;
IF datecursHandler THEN
        CLOSE datecursor;
        LEAVE datecurs;
END IF;

        Block2: BEGIN 

        declare sensorCursor CURSOR for
        select distinct sensor from sensorTable ;
        DECLARE CONTINUE HANDLER FOR NOT FOUND SET sensorcur = TRUE;

        Open sensorCursor;
        senscurs: loop
        FETCH  sensorCursor into sensor;

        IF sensorcur THEN
                SET sensorcur = False;
                CLOSE sensorCursor;
                LEAVE senscurs;
                END IF;

        Insert into temptable(
        sensorValue,
        DateID,
        TimeID, 
        TotalCount,
        TotalDistinctCount
        )
        SELECT 
            sensor AS sensorValue,
            DATE_FORMAT(firstdate, '%Y%m%d') AS DateID,
            HOUR(firstdate) + 1 AS TimeID,
            COUNT(*) AS totalcount,
            COUNT(DISTINCT sensor) AS sensordistinctcount
        FROM
            (SELECT 
                    sensor AS sensor,
                    first_seen AS DeviceFirstSeen,
                    last_seen AS DeviceLastSeen,
                    DATE_FORMAT(FROM_UNIXTIME(first_seen), '%Y/%m/%d %k:%i:%s.%f') AS firstdate,
                    DATE_FORMAT(FROM_UNIXTIME(last_seen), '%Y/%m/%d %k:%i:%s.%f') AS lastdate,          
            FROM
                sensorTable
            INNER JOIN sensorTable2 ON sensorTable.ID = sensorTable2.ID
            WHERE sensorTable.DeviceFirstSeen BETWEEN date_format(date_sub(date,interval 1 day),'%Y-%m-%d 15:00:00') AND date_format(date,'%Y-%m-%d 14:59:59')) a
        GROUP BY DATE_FORMAT(firstdate, '%Y%m%d') , HOUR(firstdate) + 1;

        end loop Maccurs;


        END Block2;
END loop datecurs;
END Block1;
END

有人可以帮我调试我的代码吗?我已经研究过了,但是到目前为止,根据我的研究,我的代码看起来是正确的,但不能按预期工作。

必需的输出: 获取从dateTable中选择的每小时中每一天的所有传感器的计数。

1 个答案:

答案 0 :(得分:1)

尝试以下步骤,因为问题可能是游标关闭不正确。

host.docker.internal