数据库中有一个表:如下
SELECT id, descs FROM table_learn WHERE id>0 and id<4;
结果如下:
下面是一个demo,可以直接按照这个结果循环操作:
delimiter //
drop procedure if exists sp_name //
create procedure sp_name()
begin
DECLARE done INT DEFAULT FALSE;
DECLARE v_id int;
DECLARE v_descs varchar(100);
#declare cursor
DECLARE cur1 CURSOR FOR SELECT id, descs
FROM table_learn
WHERE id>0 and id<4;
#declare handle
DECLARE CONTINUE HANDLER FOR NOT FOUND SET done = TRUE;
drop table if exists tmp_table;
create temporary table tmp_table(id int, descs varchar(100));
#open cursor
OPEN cur1;
#starts the loop
the_loop: LOOP
#get the values of each column into our variables
FETCH cur1 INTO v_id,v_descs;
IF done THEN
LEAVE the_loop;
END IF;
#Do some post processing
IF v_id IS NOT NULL THEN
SET v_descs = "haha";
END IF;
#Insert it
INSERT INTO tmp_table (id, descs)
VALUES (v_id, v_descs);
END LOOP the_loop;
CLOSE cur1;
select * from tmp_table;
end;
//
delimiter ;
call sp_name();
本文介绍了一个使用MySQL存储过程和游标处理数据库记录的具体案例。通过一个示例展示了如何从table_learn表中读取id大于0且小于4的数据,并通过存储过程更新descs字段,最后将处理后的数据插入到临时表中。
174万+

被折叠的 条评论
为什么被折叠?



