mysql的三種循環while 、 loop 、repeat與oracle的三種loop的


-- 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;

 

================================

================================

Oracle中三種循環

--1.loop

Declare
vcount number := 51;
begin
loop
insert into test (id, name) values (vcount, 'loop');
vcount := vcount + 1;
exit when vcount = 61;
end loop;
commit;
end;

select * from test

--2.while loop

Declare
vcount number := 61;
begin
while vcount <= 70 loop
insert into test (id, name) values (vcount, 'loop');
vcount := vcount + 1;
end loop;
commit;
end;

--3.for loop

Declare
vcount number;
begin
for vcount in 71 .. 75 loop
insert into test (id, name) values (vcount, 'loop');
end loop;
commit;
end;

 


免責聲明!

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



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