如果你前面看過mysql函數,會發現無法使用返回多行結果的語句。但如果你又確實想要使用時,就需要使用到游標,游標可以幫你選擇出某個結果(這樣就可以做到返回單個結果)。 另外,使用游標也可以輕易的取出在檢索出來的行中前進或后退一行或多行的結果。 游標可以遍歷返回的多行結果。 補充: Mysql中游標只適用于存儲過程以及函數。 創建游標: 語法: 1.定義游標:declare 游標名 cursor for select語句; 2.打開游標:open 游標名; 獲取結果:fetch 游標名 into 變量名[,變量名]; 關閉游標:close 游標名; create procedure p1() begin declare id int; declare name varchar(15); -- 聲明游標 declare mc cursor for select * from class; -- 打開游標 open mc; -- 獲取結果 fetch mc into id,name; -- 這里是為了顯示獲取結果 select id,name; -- 關閉游標 close mc;
end;
create procedure p2() begin declare id int; declare name varchar(15); -- 聲明游標 declare mc cursor for select * from class; -- 打開游標 open mc; -- 獲取結果 loop -- 循環,將表的內容都轉移到class2中 fetch mc into id,name; -- 這里是為了顯示獲取結果 insert into class2 values(id,name); -- 關閉游標 end loop; close mc;
end;
使用游標: 游標每一次fetch都是獲取一行結果,可以使用變量來獲取fetch到的每一列的值 create procedure p2() begin declare id int; declare name varchar(15); -- 聲明游標 declare mc cursor for select * from class; -- 打開游標 open mc; -- 獲取結果 loop -- 循環,將表的內容都轉移到class2中 fetch mc into id,name; -- 這里是為了顯示獲取結果 insert into class2 values(id,name); -- 關閉游標 end loop; close mc;
create procedure p3() begin declare id int; declare name varchar(15); declare flag int default 0; -- 聲明游標 declare mc cursor for select * from class; declare continue handler for not found set flag = 1; -- 打開游標 open mc; -- 獲取結果 l2:loop
fetch mc into id,name; if flag=1 then -- 當無法fetch會觸發handler continue leave l2; end if; -- 這里是為了顯示獲取結果 insert into class2 values(id,name); -- 關閉游標 end loop; close mc;
end;
call p3();-- 不報錯 select * from class2; 以上就是關于如何使用mysql游標的內容,如果你們有學習到知識或者技能,可以把它分享出去讓更多的人看到。