mysql游標(biāo)的原理與用法實(shí)例分析
本文實(shí)例講述了mysql游標(biāo)的原理與用法。分享給大家供大家參考,具體如下:
本文內(nèi)容: 什么是游標(biāo) 創(chuàng)建游標(biāo) 使用游標(biāo)首發(fā)日期:2018-04-18
什么是游標(biāo): 如果你前面看過(guò)mysql函數(shù),會(huì)發(fā)現(xiàn)無(wú)法使用返回多行結(jié)果的語(yǔ)句。但如果你又確實(shí)想要使用時(shí),就需要使用到游標(biāo),游標(biāo)可以幫你選擇出某個(gè)結(jié)果(這樣就可以做到返回單個(gè)結(jié)果)。 另外,使用游標(biāo)也可以輕易的取出在檢索出來(lái)的行中前進(jìn)或后退一行或多行的結(jié)果。 游標(biāo)可以遍歷返回的多行結(jié)果。補(bǔ)充: Mysql中游標(biāo)只適用于存儲(chǔ)過(guò)程以及函數(shù)。創(chuàng)建游標(biāo): 語(yǔ)法: 1.定義游標(biāo):declare 游標(biāo)名 cursor for select語(yǔ)句; 2.打開(kāi)游標(biāo):open 游標(biāo)名; 獲取結(jié)果:fetch 游標(biāo)名 into 變量名[,變量名]; 關(guān)閉游標(biāo):close 游標(biāo)名;create procedure p1()begin declare id int; declare name varchar(15); -- 聲明游標(biāo) declare mc cursor for select * from class; -- 打開(kāi)游標(biāo) open mc; -- 獲取結(jié)果 fetch mc into id,name; -- 這里是為了顯示獲取結(jié)果 select id,name; -- 關(guān)閉游標(biāo) close mc; end;
create procedure p2()begin declare id int; declare name varchar(15); -- 聲明游標(biāo) declare mc cursor for select * from class; -- 打開(kāi)游標(biāo) open mc; -- 獲取結(jié)果 loop -- 循環(huán),將表的內(nèi)容都轉(zhuǎn)移到class2中 fetch mc into id,name; -- 這里是為了顯示獲取結(jié)果 insert into class2 values(id,name); -- 關(guān)閉游標(biāo) end loop; close mc; end;使用游標(biāo): 游標(biāo)每一次fetch都是獲取一行結(jié)果,可以使用變量來(lái)獲取fetch到的每一列的值
create procedure p2()begin declare id int; declare name varchar(15); -- 聲明游標(biāo) declare mc cursor for select * from class; -- 打開(kāi)游標(biāo) open mc; -- 獲取結(jié)果 loop -- 循環(huán),將表的內(nèi)容都轉(zhuǎn)移到class2中 fetch mc into id,name; -- 這里是為了顯示獲取結(jié)果 insert into class2 values(id,name); -- 關(guān)閉游標(biāo) end loop; close mc; end;
上面的代碼會(huì)有一個(gè)報(bào)錯(cuò),不斷循環(huán)的話(huà),始終會(huì)達(dá)到表的末尾,到了末尾就無(wú)法繼續(xù)fetch,一般來(lái)說(shuō)都要避免報(bào)錯(cuò),到了末尾前會(huì)有一個(gè)mysql定義的
create procedure p3()begin declare id int; declare name varchar(15); declare flag int default 0; -- 聲明游標(biāo) declare mc cursor for select * from class; declare continue handler for not found set flag = 1; -- 打開(kāi)游標(biāo) open mc; -- 獲取結(jié)果 l2:loop fetch mc into id,name; if flag=1 then -- 當(dāng)無(wú)法fetch會(huì)觸發(fā)handler continue leave l2; end if; -- 這里是為了顯示獲取結(jié)果 insert into class2 values(id,name); -- 關(guān)閉游標(biāo) end loop; close mc; end;call p3();-- 不報(bào)錯(cuò)select * from class2;
更多關(guān)于MySQL相關(guān)內(nèi)容感興趣的讀者可查看本站專(zhuān)題:《MySQL查詢(xún)技巧大全》、《MySQL事務(wù)操作技巧匯總》、《MySQL存儲(chǔ)過(guò)程技巧大全》、《MySQL數(shù)據(jù)庫(kù)鎖相關(guān)技巧匯總》及《MySQL常用函數(shù)大匯總》
希望本文所述對(duì)大家MySQL數(shù)據(jù)庫(kù)計(jì)有所幫助。
相關(guān)文章:
1. 用腳本和查詢(xún)主動(dòng)監(jiān)視Oracle 9i性能2. DB2數(shù)據(jù)庫(kù)更新執(zhí)行計(jì)劃的幾個(gè)常見(jiàn)的方法3. 實(shí)例講解Oracle數(shù)據(jù)庫(kù)自動(dòng)增加ID的sql4. 全面解析IBM DB2 9中的查詢(xún)優(yōu)化新特性5. SQL Server 2005日志文件損壞的處理方法6. IBM DB2 Connect簡(jiǎn)介(1)7. Mysql入門(mén)系列:MYSQL創(chuàng)建、刪除和選擇數(shù)據(jù)庫(kù)8. DB2 9的九大新特性9. MySQL如何解決幻讀問(wèn)題10. sql server刪除數(shù)據(jù)庫(kù)文件的方法
