定義游標 declare fetchSeqCursor cursor for select seqname, value from sys_sequence;
使用游標 open fetchSeqCursor; fetch數據 fetch cursor into _seqname, _value;
關閉游標 close fetchSeqCursor; 不過這都是針對cursor的操作而已,和PL/SQL沒有什么區別吧,不過光是了解到這個是根本不足以寫出Mysql的fetch過程的,還要了解其他的更深入的知識,我們才能真正的寫出好的游標使用的procedure 首先fetch離不開循環語句,那么先了解一下循環吧。 我一般使用Loop和while覺得比較清楚,而且代碼簡單。
這里使用Loop為例
復制代碼 代碼如下:
fetchSeqLoop:Loop fetch cursor into _seqname, _value; end Loop;
現在是死循環,還沒有退出的條件,那么在這里和oracle有區別,Oracle的PL/SQL的指針有個隱性變量%notfound,Mysql是通過一個Error handler的聲明來進行判斷的, declare continue handler for Not found (do some action); 在Mysql里當游標遍歷溢出時,會出現一個預定義的NOT FOUND的Error,我們處理這個Error并定義一個continue的handler就可以叻,關于Mysql Error handler可以查詢Mysql手冊定義一個flag,在NOT FOUND,標示Flag,在Loop里以這個flag為結束循環的判斷就可以叻。
復制代碼 代碼如下:
declare fetchSeqOk boolean; ## define the flag for loop judgement declare _seqname varchar(50); ## define the varient for store the data declare _value bigint(20); declare fetchSeqCursor cursor for select seqname, value from sys_sequence;## define the cursor declare continue handler for NOT FOUND set fetchSeqOk = true; ## define the continue handler for not found flag set fetchSeqOk = false; open fetchSeqCursor; fetchSeqLoop:Loop if fetchSeqOk then leave fetchSeqLoop; else fetch cursor into _seqname, _value; select _seqname, _value; end if; end Loop; close fetchSeqCursor;