mysql循環語句:
本文總結了mysql常見的三種循環方式:while、repeat和loop循環。還有一種goto,不推薦使用。
一、while循環 delimiter // #定義標識符為雙斜杠 drop procedure if exists test; #如果存在test存儲過程則刪除 create procedure test() #創建無參存儲過程,名稱為test begin declare i int; #申明變量 set i = 0; #變量賦值 while i < 10 do #結束循環的條件: 當i大於10時跳出while循環 insert into test values (i); #往test表添加數據 set i = i + 1; #循環一次,i加一 end while; #結束while循環 select * from test; #查看test表數據 end // #結束定義語句 call test(); #調用存儲過程
二、repeat循環 delimiter // #定義標識符為雙斜杠 drop procedure if exists test; #如果存在test存儲過程則刪除 create procedure test() #創建無參存儲過程,名稱為test begin declare i int; #申明變量 set i = 0; #變量賦值 repeat insert into test values (i); #往test表添加數據 set i = i + 1; #循環一次,i加一 until i > 10 end repeat; #結束循環的條件: 當i大於10時跳出repeat循環 select * from test; #查看test表數據 end // #結束定義語句 call test(); #調用存儲過程 三、loop循環 delimiter // #定義標識符為雙斜杠 drop procedure if exists test; #如果存在test存儲過程則刪除 create procedure test() #創建無參存儲過程,名稱為test begin declare i int; #申明變量 set i = 0; #變量賦值 lp : loop #lp為循環體名,可隨意 loop為關鍵字 insert into test values (i); #往test表添加數據 set i = i + 1; #循環一次,i加一 if i > 10 then #結束循環的條件: 當i大於10時跳出loop循環 leave lp; end if; end loop; select * from test; #查看test表數據 end // #結束定義語句 call test(); #調用存儲過程
原文:https://blog.csdn.net/yangzjchn/article/details/82705565