第24章 使用游標(biāo)
24.1 游標(biāo)
游標(biāo),是一個select語句的查詢結(jié)果集,用于交互式應(yīng)用,如:滾動屏幕上的數(shù)據(jù),瀏覽和修改數(shù)據(jù)。
在mysql中,游標(biāo)只能用于存儲過程和函數(shù)。
24.2 使用游標(biāo)
使用游標(biāo)的步驟:
1、聲明游標(biāo):一次聲明游標(biāo)后,可多次打開和關(guān)閉游標(biāo)。
2、打開游標(biāo):從服務(wù)器檢索出數(shù)據(jù)結(jié)果集。一次打開游標(biāo)后,可多次取出數(shù)據(jù)。
3、取出數(shù)據(jù):按條件篩選、顯示數(shù)據(jù)。
4、關(guān)閉游標(biāo)
注意順序:declare創(chuàng)建局部變量,要放在declare創(chuàng)建游標(biāo)之前。
例:創(chuàng)建存儲過程,查詢所有訂單含稅合計金額,結(jié)果存儲到一個表里:
delimiter //
create procedure processorders()
begin
-- 聲明局部變量local variables
declare done boolean ?default 0; #變量名done(意思為:完成)
declare o int; #變量o(訂單)
declare t decimal(8,2); #變量t(訂單合計數(shù))
-- 創(chuàng)建游標(biāo),定義游標(biāo)內(nèi)容為檢索所有訂單編號。
declare ordernumbers cursor?for?select order_num from orders;
-- 創(chuàng)建條件處理器
declare continue handler for sqlstate '02000' set done=1; #sql錯誤代碼(sqlstate '02000')
-- 創(chuàng)建表,用于存儲結(jié)果集。
create table if not exists ordertotals(order_num int,total decimal(8,2));
-- 打開游標(biāo),檢索出數(shù)據(jù)放到內(nèi)存。
open ordernumbers;?
-- 遍歷所有行l(wèi)oop through all rows
repeat
? ? ? ? -- 取出數(shù)據(jù)訂單編號
? ? ? ? fetch ordernumbers into o;
? ? ? ? -- 取得訂單合計金額,調(diào)用上一章的存儲過程
? ? ? ? call ordertotal(o,1,t);? #(訂單編號,是否含稅,訂單合計金額)
? ? ? ? -- 將前面取得的 訂單編號和訂單合計金額寫入表
? ? ? ? insert into ordertotals(order_num,total) values(o,t);
-- 遍歷循環(huán)結(jié)束
until done end repeat;
-- 關(guān)閉游標(biāo),釋放內(nèi)存和資源。
close ordernumbers;
-- 隱含關(guān)閉,mysql到達(dá)end語句時,會自動關(guān)閉游標(biāo)。
end//
delimiter ;

例:執(zhí)行存儲過程,并顯示所有訂單含稅合計金額:
call processorders;
select * from ordertotals order by order_num;


《mysql必知必會》是一本好書,是一本sql語言入門書,豆瓣評分很高。
作者是英國的Ben Forta,世界知名的技術(shù)作家,由人民郵電出版社發(fā)行,我覺得原作名: MySQL Crash Course,直譯為:《MYSQL速成》更具暢銷書潛質(zhì),只是比較俗吧,呵呵。
書中從介紹簡單的數(shù)據(jù)檢索開始,逐步深入一些復(fù)雜的內(nèi)容,包括聯(lián)結(jié)的使用、子查詢、正則表達(dá)式和基于全文本的搜索、存儲過程、游標(biāo)、觸發(fā)器、表約束,等等。
前三章是基礎(chǔ)概念,講了SQL和數(shù)據(jù)庫的基本概念,Mysql數(shù)據(jù)庫的概念和使用方法,第四章開始SQL實操練習(xí),這里是本書的一些實操練習(xí)筆記,有興趣的話可以按這個練習(xí)幾遍,相信對新手會很有幫助,讓你不經(jīng)意間功力大增。