views:

357

answers:

1

I am trying to do a simple stored procedure in mysql which has a nested loop. The idea is to check to see if the table has any values and if not then insert them. below is the code of the stored proc. I have tested all parts of the code and if i comment out the nested loop it will loop through all the values for the _my_curs_ fine. But when I place the nested loop in there it will only loop over the first value of _my_curs_ then when it completes it does not seem to get to the next value. The nested loop seems to loop over all values fine.

DECLARE _my_id_ INT;
DECLARE _your_id_ INT;
DECLARE _found_id_ INT;

DECLARE _my_curs_ CURSOR FOR SELECT my_id FROM my_ref;
DECALRE _your_curs_ CURSOR FOR SELECT _your_id FROM your_ref;

OPEN _my_curs_;
loop_MY_CURSOR_:LOOP

FETCH _my_curs_ INTO _my_id_;

OPEN _your_curs_;
loop_YOUR_CURSOR_:LOOP

  FETCH _your_curs_ INTO _your_id_;

  SET _found_id_ = (SELECT COUNT(id) 
                  FROM access WHERE my_id = _my_id_ AND your_id = _your_id_);

  IF _found_id_ = 0 THEN
      INSERT INTO access(my_id, your_id)
      VALUES(_my_id_, _your_id_);
  END IF;

  END LOOP loop_YOUR_CURSOR;
  CLOSE _your_curs_;

END LOOP loop_MY_CURSOR;
CLOSE _my_curs_;

END $$

DELIMITER;
+1  A: 

Roland Bouman has written a nice article explaining the pitfalls and workarounds of nested cursors here: link text

ggiroux
thank you this is exactly the type of documentation I have been looking for..
mysql_quest