1. 游标---可以看成mysql中的for循环一样的存在
场景:如果需要对表的每一行分门别类的操作,则可以考虑使用游标,但是游标性能不太好;
比如现在有两张表A B 字段都是id num 但是A表中有数据,B表中没有数据,如果想把A表中的num +id 的值给B表对应的num字段的值填充,应该怎么操作(使用游标 对表的行分门别类的操作)
2. 代码实现
drop procedure p5; -- 删除存储过程 create table A( id int not null auto_increment primary key, num int not null); insert into A(num) values(10),(20),(30),(40); create table B( id int not null auto_increment primary key, num int not null); select * from A; select * from B; delimiter \ create procedure p5() begin declare row_id int; declare row_num int; declare done int default 0; declare temp int; declare my_cursor CURSOR for select id,num from A; declare continue handler for not found set done=1; open my_cursor; xxoo:loop fetch my_cursor into row_id,row_num; if done THEN leave xxoo; end if; set temp=row_id+row_num; insert into B(num) values(temp); end loop xxoo; close my_cursor; end \ delimiter ; call p5(); select * from B;
运行结果: