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;
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.
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.
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.
Roland Bouman has written a nice article explaining the pitfalls and workarounds of nested cursors here: link text
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With