2013-02-07 43 views
0

我已經試過在MySQL一個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 

創建下列過程的結果有沒有辦法可以從第一個循環得到的結果是第二個循環中的變量?

+0

你試過宣佈第一循環 – CHill60

+0

DECLARE內第二光標在「OPEN curs_event_id;」之後不允許使用統計信息所以它不能這樣做 – yaniv

+0

嵌套遊標應該在MySQL中可用 - 請參閱http://rpbouman.blogspot.com/2005/10/nesting-mysql-cursor-loops.html – CHill60

回答

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