游標巢狀使用時,@@fetch_status的值有時會從內部游標影響到外部的游標,使外部的游標只迴圈一次。這時要檢查游標的使用方法。要先移動游標,然後就開始判斷,為真進行進行業務邏輯處理,然後移動游標,這樣就沒問題了。示例如下:
也就是說,外層游標每移動一行,就要重複進行內層游標定義,開啟,迴圈,關閉,釋放等操作,然後才能再向下移動行。這樣就不會有影響。declare 外層游標
open 外層游標
fetch next ...提取外層游標行
while @@fetch_status = 0
begin
declare 內層游標
open 內層游標
fetch next ...提取內層游標行
while @@fetch_status = 0
begin
.....業務邏輯處理處理內層游標
fetch next ....內層游標向下移動一行
endclose 內層游標
deallocate 內層游標
fetch next ....內層游標處理結束後,外層游標才繼續向下移動一行
end
close 外層游標
deallocate 外層游標
巢狀游標的原理
fetch status 屬於任何游標的,只要任何乙個游標被提取了,這個提取成功與否的狀態就會儲存到 fetch status中.巢狀游標的原理類似這樣 declare 外層游標 open 外層游標 fetch next 提取外層游標行 while fetch status 0 begin decl...
mysql 游標巢狀使用
解決方案 從a表取乙個欄位的值和從b表取乙個欄位的值一一組合作為插入資料來源。drop procedure if exists test team user create procedure test team user begin declare done int default 0 declar...
sql 雙層游標巢狀
建立儲存資料臨時表 create table temp dep temp depid varchar 50 temp depname varchar 50 temp name varchar 5000 向臨時表中插入前三列資料 insert into temp dep temp depid,temp...