简体   繁体   中英

Nested loop in mysql stored procedure

I am having a simple nested while loop in stored procedure , but it's giving an error. The loop does not nothing great, just for learning purpose i created two loops.

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 ;

Below is the error

#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

Thanks.

Try this:

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 ;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM