MySQL的流程控制語句
(1)IF語句
IF search_condition THEN statement_list
[ELSEIF search_condition THNE statement_list]
[ELSE statement_list]
END IF
(2)CASE語句
CASE case_value
WHEN when_value THEN statement_list
[WHEN when_value THEN statement_list]...
[ELSE statement_list]
END CASE
或者
CASE
WHEN search_conditon THEN statement_llist
[WHEN search_condition THEN statement_list]...
[ELSE statement_list]
END CASE
例句:
case
when i_staff_id =2 then
set @[email protected]+d_amount;
else
set @[email protected]
end case;
(3)Loop
[begin_label:] Loop
statement_list
END LOOP [end_label]
(4)LEAVE語句
用於從標註的流程構造中退出
示例:
CREATE PROCEDURE actor_insert()
BEGIN
set @x=0;
ins : LOOP
set @x = @x +1 ;
IF @x= 100 then
leave ins;
END IF;
INSERT INTO actor(first_name,last_name) VALUES ('TEST','201');
END LOOP ins;
END ;
$$
(5)ITERATE 語句
該語句必須用在迴圈中,作用是跳過當前迴圈的剩下的語句,直接進入下一輪迴圈。
CREATE PROCEDURE actor_insert()
BEGIN
set @x=0;
ins: LOOP
set @[email protected]+1;
IF @x=10 then
leave ins;
ELSEIF mod(@x,2)=0 then
ITERATE ins;
END IF;
INSERT INTO actor(actor_id,first_name,last_name) VALUES (@x+200 , 'Test', @x);
END LOOP ins;
end;
(6) REPEAT 語句
[begin_label:] REPEAT
statement_list
UNTIL search_condition
END REPEAT [end_label]
示例:
REPEAT
FETCH cur_payment INTO i_staff_id,d_amount;
if i_staff_id =2 then
set @[email protected] + d_amount;
else
set @[email protected] + d_amount;
end if;
UNTIL 0 END REPEAT;
(7)WHERE語句
[begin_label:]WHILE search_condition DO
statement_list
END WHILE [end_label]
示例:
CREATE PROCEDURE loop_demo()
BEGIN
set @x=1 ,@x1=1;
REPEAT
set @[email protected]+1;
UNTIL @x> 0 end repeat;
while @x1<0 do
set @[email protected] +1;
end while;
END;