游標的作用:游標提供了一種對從表中檢索出的數據進行操作的靈活手段。
通過使用游標,使SQL這種面向集合的語言有了面向過程開發的能力。
如何使用游標:
在MySQL數據庫中,可以在存儲過程、函數、觸發器、或者事件中使用游標。
使用時需要與handler一起,並且游標要在handler之前定義。
游標具有三個屬性:(1)Asensitive:數據庫也可以選擇不復制結果集;
(2)Read only:不可更新;
(3)Nonscrollable:游標只能向一個方向前進,並且不可以跳過任何一行數據。
使用時,首先定義一個游標變量:
然后打開定義好的游標變量:
接着就可以從游標中取得數據:
最后關閉游標:
通過一個例子演示如何在存儲過程中使用游標:
use datatest; set @counts = '3333'; set @eee = 'egy49xa'; call pp3(@counts, @eee); select @counts, @eee; drop procedure IF EXISTS pro_result; delimiter // create procedure pro_result(out sum bigint) BEGIN declare i int; declare done int default 0; declare did cursor for select id from demo1;-- 游標的定義 declare continue handler for not found set done = 1; set sum = 0; open did;-- 打開游標 xxx:LOOP fetch did into i;-- 游標里取得數據 if done = 1 THEN -- 設定退出條件 leave xxx; END IF; set sum = sum + i; END LOOP; close did; END // delimiter ; -- 調用 set @sum = 0; call pro_result(@sum); select @sum;
數據為十萬條結果