0

我试图在mysql中创建以下过程

    PROCEDURE fix()
BEGIN

  DECLARE event_id_ INT;
  DECLARE gate_number INT;

  DECLARE l_done          INT DEFAULT  0;
  DECLARE curs_event_id CURSOR FOR SELECT DISTINCT event_id FROM history_15min;
  DECLARE curs_gate_number CURSOR FOR SELECT DISTINCT gate_number 
                                         FROM history_15min WHERE event_id =event_id_;
 ( -- HERE IS THE PROBLEM - event_id_ IS BLANK THERE FOR  THE INNER LOOP RETURNS NO RESULTS ....)            

  DECLARE CONTINUE HANDLER FOR NOT FOUND SET l_done=1;  

    OPEN curs_event_id;
    event_loop : LOOP
    FETCH curs_event_id INTO event_id_;
    IF l_done=1 THEN LEAVE event_loop;
    END IF;

        OPEN curs_gate_number;
        gate_loop : LOOP
        FETCH curs_gate_number INTO gate_number;
        IF l_done=1 THEN LEAVE gate_loop;
        END IF;

insert into t value ('1');

        END LOOP gate_loop;
        CLOSE curs_gate_number;
        SET l_done=0;

    END LOOP event_loop;
    CLOSE curs_event_id;

END

有没有办法让第一个循环的结果成为第二个循环中的变量?

4

1 回答 1

0

感谢 CHill60 ,您的链接有我正在寻找的答案

这是执行嵌套循环的正确方法:

PROCEDURE fix()
BLOCK1: BEGIN

  DECLARE colA_ INT;

  DECLARE l_done INT DEFAULT 0;
  DECLARE curs_colA CURSOR FOR SELECT DISTINCT colA FROM tableA;

  DECLARE CONTINUE HANDLER FOR NOT FOUND SET l_done=1;  

    OPEN curs_colA;
    first_loop : LOOP
    FETCH curs_colA INTO colA_;
    IF l_done=1 THEN LEAVE first_loop;
    END IF;

        BLOCK2: BEGIN
              DECLARE calB_ INT;
              DECLARE l_done INT DEFAULT 0;
              DECLARE curs_calB CURSOR FOR SELECT DISTINCT calB FROM tableB WHERE colA = colA_;

              DECLARE CONTINUE HANDLER FOR NOT FOUND SET l_done=1;  

                    OPEN curs_calB;
                    second_loop : LOOP
                    FETCH curs_calB INTO calB_;
                    IF l_done=1 THEN LEAVE second_loop;
                    END IF;

insert into tmp value ('1');

                    END LOOP second_loop;
                    CLOSE curs_calB;
                    SET l_done=0;
            END BLOCK2; 

    END LOOP first_loop;
    CLOSE curs_colA;

END BLOCK1
于 2013-02-12T08:47:36.407 回答