七:流程控制
定義變量
declare 變量名 類型 default 值; 例如: declare i int default 0;
if語句的使用
# 語法 if 條件 then 語句; end if; 第二種 if elseif if 條件 then 語句1; elseif 條件 then 語句2; else 語句3; end if; # 案例:編寫過程 實現 輸入一個整數type 范圍 1 - 2 輸出 type=1 or type=2 or type=other; create procedure showType(in type int,out result char(20)) begin if type = 1 then set result = "type = 1"; elseif type = 2 then set result = "type = 2"; else set result = "type = other"; end if; end
CASE語句(選擇語句)
大體意思與Swtich一樣的 你給我一個值 我對它進行選擇 然后執行匹配上的語句
# 語法 create procedure caseTest(in type int) begin CASE type when 1 then select "type = 1"; when 2 then select "type = 2"; else select "type = other"; end case; end
LOOP循環
沒有條件,需要自己定義結束語句
# 語法 create procedure showloop() begin declare i int default 0; aloop: LOOP select "hello loop"; set i = i + 1; if i > 9 then leave aloop; end if; end LOOP aloop; end
REPEAT循環
#類似do while #輸出10次hello repeat create procedure showRepeat() begin declare i int default 0; repeat select "hello repeat"; set i = i + 1; until i > 9 end repeat; end #輸出0-100之間的奇數 create procedure showjishu() begin declare i int default 0; aloop: loop set i = i + 1; if i >= 101 then leave aloop; end if; if i % 2 = 0 then iterate aloop; end if; select i; end loop aloop; end