1. 程式人生 > 其它 >MySQL指令碼中的三種迴圈

MySQL指令碼中的三種迴圈

-- MySQL中的三中迴圈 while 、 loop 、repeat  求  1-n 的和


   -- 第一種 while 迴圈 
   -- 求 1-n 的和
   /*  while迴圈語法:
   while 條件 DO
               迴圈體;
   end while;
   */
    create procedure sum1(a int) 
    begin
        declare sum int default 0;  -- default 是指定該變數的預設值
        declare i int default 1;
    while i<=a DO -- 迴圈開始
        set sum=sum+i;
        set i=i+1;
    end while; -- 迴圈結束
    select sum;  -- 輸出結果
    end;
    -- 執行儲存過程
    call sum1(100);
    -- 刪除儲存過程
    drop procedure if exists sum1;
	

第二種

-- 第二種 loop 迴圈
  /*loop 迴圈語法:
  loop_name:loop
          if 條件 THEN -- 滿足條件時離開迴圈
               leave loop_name;  -- 和 break 差不多都是結束訓話
       end if;
  end loop;
  */
create procedure sums(a int)
begin
        declare sum int default 0;
        declare i int default 1;
        loop_name:loop -- 迴圈開始
            if i>a then 
                leave loop_name;  -- 判斷條件成立則結束迴圈  好比java中的 boeak
            end if;
            set sum=sum+i;
            set i=i+1;
        end loop;  -- 迴圈結束
        select sum; -- 輸出結果
end;
 -- 執行儲存過程
call sums(100);
-- 刪除儲存過程
drop procedure if exists  sums;

第三種


-- 第三種 repeat 迴圈
  /*repeat 迴圈語法
  repeat
      迴圈體
  until 條件 end repeat;
  */


  -- 例項;
  create procedure sum55(a int)
  begin
       declare sum int default 0;
      declare i int default 1;
       repeat -- 迴圈開始
           set sum=sum+i;
           set i=i+1;
       until i>a end repeat; -- 迴圈結束
       select sum; -- 輸出結果
  end;

  -- 執行儲存過程
     call sum55(100);
  -- 刪除儲存過程
  drop procedure if exists sum55;