2015-01-26 44 views
0

感謝您的期待和幫助!MySQL中的遊標

我已經寫了這個非常簡單的遊標,但由於某種原因,但這並沒有想工作:

drop table if exists t1; 
drop procedure if exists simple_loop; 
create temporary table values ('chris'),('peter'),('brian'),('stewie'),('meg'); 
create procedure simple_loop() 
begin 
declare finished int default false; 
declare n varchar(45); 
declare c cursor for select name from t1; 
declare continue handler for not found set finished = true; 
open c; 
c_loop: loop 
    fetch c into n; 
    --if finished then leave c_loop; 
    select n; 
end loop; 
end 

正如你所看到的,我有評論指出,說要離開的時候環行結果完成了。這是因爲整個程序腳本不會執行。

如果行是存在的,它不會抱怨該行造成的問題,但最終的:

...權syntac使用近「循環;結束」錯誤代碼:1064

我不知道這是爲什麼。 MySQL文檔似乎沒有多大幫助。如果我還添加行'close c;'它也行不通,但指出整個結局是一個錯誤。

任何指針非常讚賞。

Ubuntu上的MySQL版本是5.5。

謝謝,克里斯

+0

爲我工作:[SQL小提琴(http://sqlfiddle.com/#!9/ 3b0f6/1)。 – wchiquito 2015-01-26 20:01:30

回答

0

這似乎是固定的!我忘了終止if語句:

drop table if exists t1; 
drop procedure if exists simple_loop; 
create temporary table values ('chris'),('peter'),('brian'),('stewie'),('meg'); 
create procedure simple_loop()begin 
declare finished int default false; 
declare n varchar(45); 
declare c cursor for select name from t1; 
declare continue handler for not found set finished = true; 
open c; 
c_loop: loop 
    fetch c into n; 
    if finished then leave c_loop; end if; 
    select n; 
end loop; 
end 

看看以前註釋掉行:

if finished then leave c_loop; END IF;