Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MYSQL nested loop stored procedure issue

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;
like image 953
medium Avatar asked Feb 04 '10 14:02

medium


People also ask

How the performance of the nested loop and block nested loop procedure can be further improved?

Instead of using disk blocks in the block nested-loop join algorithm, we can use the biggest size that could fit into memory and also leave enough space for the buffers of the inner relation s and its output. As a result, it will reduce the number of scans of the inner relation and also minimizes the cost.

How do I stop an infinite loop in MySQL?

Using LEAVE statement in loopsThe LEAVE statement allows you to terminate a loop. The general syntax for the LEAVE statement when using in the LOOP , REPEAT and WHILE statements. The LEAVE causes the current loop specified by the label to be terminated.

What is nested loop in MySQL?

Nested-Loop Join Algorithm A simple nested-loop join (NLJ) algorithm reads rows from the first table in a loop one at a time, passing each row to a nested loop that processes the next table in the join. This process is repeated as many times as there remain tables to be joined.


1 Answers

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

like image 143
ggiroux Avatar answered Oct 10 '22 22:10

ggiroux