MySQL procedure loop stops after one iteration - mysql

I am working on a MySQL procedure that creates a summary of one of my tables. The procedure retrieves a dataset and loops through it using a cursor. For each iteration of the loop, the procedure updates another table. The problem I'm having is the loop ends after a single iteration, event though I know that the query I'm running retrieves more than one row.
BEGIN
# Variable declaration section omitted for brevity
DECLARE cur CURSOR FOR SELECT
t.result_id,
t.athlete_id, t.`first`, t.middle, `last`, t.pref, t.birth,t.uss,
t.club_id,t.code,t.club_name,
t.meet_name,t.meet_id,t.`start`,t.`end`,
MIN(t.time) as time,t.age,t.type
FROM sometable t GROUP BY club_id ORDER BY time asc,t.start desc,club_id;
DECLARE CONTINUE HANDLER FOR NOT FOUND SET done = 1;
OPEN cur;
read_loop: LOOP
FETCH cur INTO result_id,athlete_id, first_name, middle, last_name, pref, birth,uss,
club_id,club_code,club_name,
meet_name,meet_id,start_date,end_date,
result_time,age,type;
IF done=1 THEN
LEAVE read_loop;
END IF;
SET last_time = result_time;
INSERT INTO toptimes(`result_id`,`club_id`,`agegroup`,`sex`,`distance`,`course`,`stroke`,`data`,`published`)
VALUES(result_id,club_id,AgeGroupID,sex,distance,course,stroke,json,0);
END LOOP read_loop;
CLOSE cur;
END
I'm not clear what the problem is. When I run the select query manually, I get back several rows. Is there a problem running an insert statement inside the loop?

Your code chunk looks good to me.
How do you know that it's running only one iteration (i'm not seeing any
print or select statement for debug purpose)?
Are you getting any error while executing the stored procedure?
I tried to replicate the similar code with "sakila" database (mysql sample db). It's working perfectly. Please check this sql code sample, if it helps you.
DROP PROCEDURE IF EXISTS usp_select_dummy_data ;
DELIMITER $$
CREATE DEFINER=`root`#`localhost` PROCEDURE usp_select_dummy_data()
BEGIN
-- Declare your variables
Declare _var_actor_id int default 0;
DECLARE _var_film_id int default 0;
-- Declare variable used for cursor and loop control
DECLARE done int;
DECLARE loop_counter INT DEFAULT 0;
-- Declare the cursor
DECLARE cur CURSOR FOR
SELECT
actor_id, film_id
FROM film_actor;
-- Declare handlers
DECLARE CONTINUE HANDLER FOR NOT FOUND SET done = 1;
-- Open the cursor
OPEN cur ;
-- Start the loop
read_loop: LOOP
FETCH cur
INTO _var_actor_id, _var_film_id ;
-- break out of the loop if
-- 1. if there is no rows or
-- 2. we've processed them all
IF done = 1 THEN
CLOSE cur ;
LEAVE read_loop ;
END IF;
-- Count the number of times looped
SET loop_counter = loop_counter + 1 ;
END LOOP read_loop ;
-- print the loop count
select loop_counter;
END

Related

Nested Cursor Into Mysql

I am creating cursor within cursor and first cursor getting unique value and second cursor is generating details number of rows. I found second cursor is running one time and not populating rows against every row id. Please guide
DELIMITER $$
USE `dum_data`$$
DROP PROCEDURE IF EXISTS `sp_process_gen`$$
CREATE DEFINER=`test`#`%` PROCEDURE `sp_process_gen`()
BEGIN
DECLARE cur1_done,cur2_done INT DEFAULT 0;
DECLARE v_thread_id, v_id,v_tab,v_event_time INT;
DECLARE v_stime,v_etime DATETIME;
-- declaring cursor
DECLARE cur1 CURSOR FOR
SELECT thread_id
FROM general_log
-- WHERE thread_id in (306710429,306711335)
GROUP BY thread_id;
DECLARE CONTINUE HANDLER FOR NOT FOUND SET cur1_done = 1;
OPEN cur1;
cur1_loop: LOOP
FETCH cur1 INTO v_thread_id;
-- INSERT INTO aa VALUES(NULL,v_thread_id,NULL,NULL);
block2: BEGIN
DECLARE cur2 CURSOR FOR
SELECT id , event_time
FROM general_log
WHERE thread_id = v_thread_id
ORDER BY id;
DECLARE CONTINUE HANDLER FOR NOT FOUND SET cur2_done = 1;
OPEN cur2;
cur2_loop: LOOP
FETCH cur2 INTO v_id,v_stime;
IF cur2_done THEN
-- set cur1_done = 0;
CLOSE cur2;
LEAVE cur2_loop;
END IF;
-- INSERT INTO aa VALUES(v_id,v_thread_id,v_stime,v_stime);
INSERT INTO aa(thread_id) VALUES(v_thread_id);
-- FETCH cur2 INTO v_id,v_stime;
END LOOP cur2_loop;
END block2;
IF cur1_done THEN
CLOSE cur1;
LEAVE cur1_loop;
END IF;
INSERT INTO aa(thread_id) VALUES(999999);
-- FETCH cur1 INTO v_thread_id;
END LOOP cur1_loop;
-- CLOSE cur;
END$$
DELIMITER ;
I suspect your problem is the two CONTINUE HANDLER FOR NOT FOUND structures.
The second cursor will get it's first NOT FOUND at the end its loop, trigger both handlers... causing both loops to exit.
The way around this is to have a second stored procedure that contains the inner loop, and call that procedure from the outer loop. That way your handlers are in separate contexts.

mysql 5.7 cursor not returning any values

Mysql (version 5.7) cursor not working. I tried many times and checked online could not find what is wrong.
It is looping through correctly as many records in the currency table. But when I try to read from the cursor it is only returning null and not the actual values from the table currency. The currency table has data.
DROP PROCEDURE IF EXISTS proc2;
CREATE PROCEDURE proc2()
BEGIN
DECLARE finished INTEGER DEFAULT 0;
DECLARE code VARCHAR(255);
DECLARE myCursor CURSOR FOR SELECT code FROM currency;
DECLARE CONTINUE HANDLER FOR NOT FOUND SET finished = 1;
OPEN myCursor;
delete from dummy;
read_loop: LOOP
FETCH myCursor INTO code;
IF finished = 1 THEN
LEAVE read_loop;
END IF;
insert into dummy(name) values(code);
END LOOP read_loop;
CLOSE myCursor;
End;
At last, it worked with below change to the script. (i.e. after adding table alias.)
For some reason, the column I tried out 'code' expects an alias. Maybe a reserved keyword, not sure.
DECLARE myCursor CURSOR FOR SELECT c.code FROM currency c;

Get Columns Single Record in Stored Procedure Mysql

I have my procedure and is working, but my question is the following,
with the cursor is working correctly, but before the cursor I need a Single Record with several columns, I donĀ“t know if I need another cursor just for one record.
Which would be the right way to get the columns of that single row without a cursor.
The query to execute is:
'SELECT id,anio,fec_iniciointeres FROM mytable WHERE id=3 '
DELIMITER $$
DROP PROCEDURE IF EXISTS db.cal_intereses$$
CREATE DEFINER=`root`#`localhost` PROCEDURE `cal_intereses`()
BEGIN
DECLARE factura_id INT UNSIGNED;
DECLARE val_avaluo DECIMAL(16,2);
DECLARE fec_actual DATE;
DECLARE done INT;
DECLARE cur CURSOR FOR SELECT fac_facturas.id AS factura_id, fac_facturas.val_avaluo FROM fac_facturas WHERE fac_facturas.vigencia_id<=26 AND fac_facturas.estado=1 AND fac_facturas.val_avaluo>0 LIMIT 10;
DECLARE CONTINUE HANDLER FOR NOT FOUND SET done=1;
SET fec_actual=(SELECT CURDATE());
SET done = 0;
OPEN cur;
ciclo: LOOP
FETCH cur INTO factura_id,val_avaluo;
IF done=1 THEN LEAVE ciclo; END IF;
DELETE FROM val_interesaux;
IF fec_actual>='2006-07-29' THEN
INSERT INTO val_interesaux(factura_id,fec_inicio) VALUES(factura_id,fec_actual);
END IF;
END LOOP ciclo;
CLOSE cur;
END$$
DELIMITER ;

using cursor last returned row is repeated

I have a table named as TRY like this....
try(name,sal) values('tony',10000),('david',20000),('rony',30000),('sami',40000)
Now I'm using cursor in a procedure to show all the values of the salary column through a variable.Doing this I'm trying to make out that hoe a cursor works as I'm new to cursor and I have come to know that cursor fetches every selected row one by one.I'm doing this following code...
delimiter ;;
create procedure me()
begin
declare done int default 0;
declare var int;
declare cur cursor for select sal from try;
declare continue handler for not found set done=1;
open cur;
curloop:loop
if done=1 then
leave curloop;
end if;
fetch cur into var;
select var;
end loop;
close cur;
end;;
Using this I'm getting all the values of SAL column correctly but the problem is that it's returning an extra row which is duplicate of the last value of SAL column,i.e. I'm getting the last value repeated.
Please solve my problem.Thanks in advance.
You need to change the function a little, check done just after FETCH operation -
CREATE PROCEDURE me()
BEGIN
DECLARE done int DEFAULT 0;
DECLARE var int;
DECLARE cur CURSOR FOR SELECT sal FROM try;
DECLARE CONTINUE HANDLER FOR NOT FOUND SET done = 1;
OPEN cur;
curloop:
LOOP
FETCH cur INTO var;
IF done THEN
LEAVE curloop;
END IF;
SELECT var;
END LOOP;
CLOSE cur;
END

mysql stored proc is not working from mysqlworkbench or java code

I have written a stored proc in mysql when i am running it through hopper it is working fine but when i am trying to run it from mysql workbench or java it is not returning any result and also not showing any exception
I will request you to please help me on this
-- --------------------------------------------------------------------------------
-- Routine DDL
-- Note: comments before and after the routine body will not be stored by the server
-- --------------------------------------------------------------------------------
DELIMITER $$
CREATE DEFINER=`root`#`localhost` PROCEDURE `issueitem`()
BEGIN
DECLARE done INT DEFAULT 0;
DECLARE inventoryids INT DEFAULT 0;
DECLARE batch varchar(39);
DECLARE resultstr varchar(3000) DEFAULT '';
DECLARE exp DATE;
DECLARE mfgdate DATE;
DECLARE availableunit INT;
DECLARE quantity INT DEFAULT 100;
DECLARE oldest_date DATETIME;
DECLARE cur_count INT;
DECLARE que_size INT DEFAULT 0;
DECLARE curs CURSOR FOR SELECT inventoryid,batch,exp,availableunit FROM aashramdata.inventory where itemid=1 ORDER BY exp ASC;
DECLARE CONTINUE HANDLER FOR NOT FOUND SET done = 1;
OPEN curs;
SET cur_count=quantity;
read_loop: LOOP
FETCH curs INTO inventoryids,batch,exp,availableunit;
IF done THEN
LEAVE read_loop;
END IF;
SET que_size = que_size + availableunit;
IF cur_count >= availableunit THEN
set cur_count=cur_count-availableunit;
set resultstr=CONCAT(resultstr,batch,' - ',exp,' - ',availableunit,' - ');
update aashramdata.inventory set `availableunit`=0 where inventoryid=inventoryids;
END IF;
IF cur_count < availableunit THEN
update aashramdata.inventory set `availableunit`=availableunit-cur_count where inventoryid=inventoryids;
set resultstr=CONCAT(resultstr,batch,' - ',exp,' - ',availableunit-cur_count,' - ');
set cur_count=0;
END IF;
IF que_size >= quantity then
LEAVE read_loop;
END IF;
END LOOP;
CLOSE curs;
select resultstr;
END
Since the procedure is apparently syntactically valid, it's impossible to answer what the problem might be, without some knowledge of the data.
The easiest way to debug a stored procedure is by peppering it with unbounded SELECT statements (that is, selects that are not part of a subquery and not part of an INSERT ... SELECT or SELECT ... INTO) and then running it from the MySQL command line client, which handles multiple result sets from stored procedures much more gracefully than most graphical clients.
For example:
...
SET cur_count=quantity;
SELECT cur_count; -- add this
read_loop: LOOP
FETCH curs INTO inventoryids,batch,exp,availableunit;
SELECT inventoryids,batch,exp,availableunit; -- add this
SELECT done; -- add this
IF done THEN
...
When run from the command line client...
mysql> CALL issueitem();
...output will start rolling out of the console at you, showing you the internal values the procedure is encountering as it iterates the loop.
This, or other SELECT statements like this added elsewhere, will expose the internal variables and this should help you find the problem. You'll need to remove them before you call the procedure from code or even the GUI since the GUI may not handle them well -- it may start opening new tabs or splitting panes or just ignoring everything after the first SELECT.
Note that the last iteration of the loop, you may see the values from the previous iteration repeated since the failed read from the cursor may not reset the variables, but "done" will also transition from 0 to 1 indicating that the cursor has run out of rows and fired the CONTINUE HANDLER, so those values won't actually have been processed twice.