標籤:style blog io color ar os 使用 for sp
一、建立遊標
遊標用declare語句建立。如下面的例子所示:
create procedure test2()begin declare cursorTest cursor for select * from allIntersection;end;
二、開啟、關閉遊標
三、使用遊標資料
在一個遊標被開啟後,可以使用FETCH語句分別訪問它的每一行。FETCH語句指定檢索什麼資料(所需的列),檢索出來的資料存放區在什麼地方。它還向前移動遊標中的內部行指標,使下一條FETCH語句檢索下一行(不重複讀取同一行)。
create procedure test3()begin declare o int; -- 聲明一個局部變數 declare cursorTest3 cursor -- 聲明一個遊標 for select ID from allintersection; open cursorTest3; -- 開啟遊標 fetch cursorTest3 into o; -- 擷取IntersectionName close cursorTest3; -- 關閉遊標end;
其中FETCH用來檢索當前行的IntersectionName列(將自動從第一行開始)到一個名為o的局部聲明的變數中。對檢索出的資料部做任何處理
四、式例
create procedure test4()begin declare done boolean default 0; declare o int; -- 聲明一個局部變數 declare cursorTest4 cursor -- 聲明一個遊標 for select ID from allintersection; declare continue handler for sqlstate ‘02000‘ set done=1; open cursorTest4; -- 開啟遊標 -- 遍曆所有的行 repeat fetch cursorTest4 into o; -- 擷取IntersectionName until done end repeat; -- 結束迴圈 close cursorTest4; -- 關閉遊標end;
MySQL 預存程序遊標