2012-04-24 104 views
1

我在存儲過程中有一個簡單的嵌套while循環,但它給出了一個錯誤。 循環沒有什麼了不起,只是爲了學習目的我創建了兩個循環。mysql存儲過程中的嵌套循環

delimiter $$ 
create procedure getSum(in input int , out output int) 
begin 

set output = 0; 
while input >= 1 do 

    declare tmp int default 1; 
    while tmp <= 5 do 
     set output = output + input ; 
     set tmp = tmp + 1; 
    end while ; 

set input = input - 1 ; 

end while; 

end $$ 
delimiter ; 

下面是錯誤

#1064 - You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'declare tmp int default 1; while tmp <= 5 do set output = output + inpu' at line 7

感謝。

回答

0

試試這個:

delimiter $$ 
create procedure getSum(in input int , out output int) 
begin 
declare tmp int default 1; 
set output = 0; 
while input >= 1 do 

    set tmp = 1; 
    while tmp <= 5 do 
     set output = output + input ; 
     set tmp = tmp + 1; 
    end while ; 

set input = input - 1 ; 

end while; 

end $$ 
delimiter ; 
+0

什麼是錯我的代碼?我每次都必須聲明局部變量嗎? – 2012-04-24 13:34:08

+0

我將'declare'移動到塊的開頭,並添加了'set tmp = 1;'以與您初始化的值保持一致。 – Ryan 2012-04-24 13:36:28

+0

局部變量是相對於'BEGIN ... END'塊定義的。通常,在塊的開頭定義它們可以消除像這樣的錯誤。我認爲這是一個要求,在塊中定義它們的第一件事,就像在舊的過程語言中一樣......但我可能是錯的。 – Ryan 2012-04-24 13:41:39