MySQL遊標的使用 mysql
A simple cursor of mysql sql
step1: oop
新建表tb_test; fetch
create table tb_test( code
id int it
); table
insert into tb_test values ('1'); class
insert into tb_test values ('2'); test
insert into tb_test values ('3'); select
step2:
聲明存儲過程sp_test;
delimiter $$
create procedure sp_test()
BEGIN
declare tmp int default 0;
declare sum int default 0;
declare done int default -1;
/* 聲明遊標 */
declare myCursor cursor for select id from tb_test;
/* 當遊標到達尾部時,mysql自動設置done=1 */
declare continue handler for not found set done=1;
/* 打開遊標 */
open myCursor;
/* 循環開始 */
myLoop: LOOP
/* 移動遊標並賦值 */
fetch myCursor into tmp;
if done = 1 then
leave myLoop;
end if;
/* do something */
set sum = sum + tmp;
/* 循環結束 */
end loop myLoop;
insert into tb_test values(sum);
/* 關閉遊標 */
close myCursor;
END
$$
delimiter ;
step3:
call sp_test();
select * from tb_test();
+----+
| id |
+----+
| 1 |
| 2 |
| 3 |
| 6 |
+----+