MySql必知必會實戰練習(六)遊標
阿新 • • 發佈:2018-11-28
遊標主要用於互動式應用,滾動螢幕上的資料,並對資料進行瀏覽或做出更改
看一下下面的例子:
drop procedure IF EXISTS processorders; create procedure processorders( out ordernum int ) begin select order_num from orders into ordernum; end; call processorders(@ordernum); select ordernum;
輸出:
由於結果為多行無法顯示,這時我們就需要使用遊標來操作
1. 遊標基本方法
(1)建立遊標
create procedure processorders() begin declare ordernums cursor for select order_num from orders; end;
(2)開啟遊標
open ordernums;
(3)關閉遊標
close ordernums;
在一個遊標關閉後,如果沒有重新開啟,則不能使用它。
使用申明過的遊標不需要再次宣告,用open語句開啟它就可以了。
2.遊標使用示例
drop procedure IF EXISTS processorders; create procedure processorders(out numbers int, out custid int ) begin #宣告遊標 declare ordernums cursor for select order_num,cust_id from orders; #開啟遊標 open ordernums; #用來檢索當前行的order_num(自動從第一行開始) fetch ordernums into numbers, custid; #關閉遊標 close ordernums; end; call processorders(@numbers,@custid);select @numbers,@custid;
會看到只輸出了第一行的order_num和cust_id:
繼續,接下來將迴圈檢索資料,從第一行到最後一行:
drop procedure IF EXISTS processorders; create procedure processorders( out numbers int, out custid int ) begin declare done boolean default 0; #宣告遊標 declare ordernums cursor for select order_num,cust_id from orders; #宣告CONTINUE HANDLER declare CONTINUE HANDLER FOR SQLSTATE '02000' SET done = 1; #開啟遊標 open ordernums; #開始迴圈 REPEAT #用來檢索當前行的order_num(自動從第一行開始) fetch ordernums into numbers, custid; #.....這裡可以對每次檢索出來的資料進行處理 #結束迴圈 UNTIL done END REPEAT; #關閉遊標 close ordernums; end; call processorders(@numbers,@custid); select @numbers,@custid;
我們會看出輸出最後一行的order_num和cust_id
這樣就實現了資料的迴圈檢索,我們可以在 (#.....這裡可以對每次檢索出來的資料進行處理)註釋處對每次檢索出來的資料進行處理
注意:上面我們定義了一個COUNtINUE HANDLEr,它是在條件出現時執行的程式碼,它指出SQLSTATE '02000'出現時set done = 1,最開始SQLSTATE '02000'是一個未找到的條件,只有當repeat沒有更多的行供迴圈時才會出現SQLSTATE '02000'