An instance of using a cursor in an mysql stored procedure
- 2020-06-12 10:47:23
- OfStack
DELIMITER $$
DROP PROCEDURE IF EXISTS getUserInfo $$
CREATE PROCEDURE getUserInfo(in date_day datetime)
--
-- The instance
-- MYSQL Stored procedure name: getUserInfo
-- Parameters as follows: date_day The date format :2008-03-08
--
BEGIN
declare _userName varchar(12); -- The user name
declare _chinese int ; -- Chinese language and literature
declare _math int ; -- mathematics
declare done int;
-- Define the cursor
DECLARE rs_cursor CURSOR FOR SELECT username,chinese,math from userInfo where datediff(createDate, date_day)=0;
DECLARE CONTINUE HANDLER FOR NOT FOUND SET done=1;
-- Get yesterday's date
if date_day is null then
set date_day = date_add(now(),interval -1 day);
end if;
open rs_cursor;
cursor_loop:loop
FETCH rs_cursor into _userName, _chinese, _math; -- Take the data
if done=1 then
leave cursor_loop;
end if;
-- Update the table
update infoSum set total=_chinese+_math where UserName=_userName;
end loop cursor_loop;
close rs_cursor;
END$$
DELIMITER ;