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;


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM