一、流程語句講解
二、總結
一、流程語句講解
1.1 if語句講解
語法:
IF condition THENstatements;
ELSEIF condition THENstatements;
ELSEstatements;
END IF;
?題目示例:
# 判斷成績等級
# 輸入學生的編號,取出學生的第一門課,然后判斷當前的課程的等級
drop procedure if exists p2 delimiter $$
create procedure p2(in stuID int)
begin-- 定義局部變量declare myScore double default 0.0;declare myCname varchar(20);-- 查詢學生成績select score,sname into myScore,myCname from v4 where sid = stuIDorder by score desclimit 1;-- 根據局部變量做判斷if myScore>80 thenselect concat(myCname,'A') 課程情況;elseif myScore<80 and myScore>60 then select concat(myCname,'B') 課程情況;else select concat(myCname,'C') 課程情況;end if;
end$$
delimiter;call p2(1);注釋:
declare 定義局部變量
procedure 存儲過程
delimiter 定義結束符
call 調用
concat 將多個字符串連接成一個字符串v4是一個連表視圖
1.2 case條件語句
語法:
CASE XWHEN condition1 THEN statements1WHEN condition2 THEN statements2...ELSE statements
END CASE;
題目示例:
-- 查詢學生性別,將男女換成小伙子和小姑娘
drop procedure if exists p3;
delimiter $$
create procedure p3(in stuID int)
begin-- 定義局部變量declare mySname varchar(20);declare mySex varchar(20);-- 查詢學生性別select sname,ssex into mySname,mySex from v4 where sid = stuId limit 1;-- 根據局部變量做判斷case mySex when '男' then set mySex = '小伙子';when '女' thenset mySex = '小姑娘';else set mySex = '妖怪';end case;select mySname,mySex;
end$$
delimiter ;call p3(6);
1.3?LOOP循環語句
語法:
[loop_label:] LOOPstatements;IF condition THENLEAVE [loop_label];END IF;
END LOOP [loop_label];
題目示例:
-- 輸出10次Hello World
drop procedure if exists p4;delimiter $$
create procedure p4()
begin -- 定義局部變量declare n int default 0;-- 死循環myloop: loop select 'hello world';set n= n+1;if n >= 10 thenleave myloop;end if;end loop;
end$$
delimiter ;call p4();注釋:
leave 停止循環
myloop 給loop循環取別名,用來停止循環
1.4 while循環語句
語法:
[while_label:] WHILE condition DOstatements;
END WHILE [while_label];
題目示例:
-- while使用
drop procedure if exists p5;delimiter $$
create procedure p5()
begin-- 定義局部變量declare n int default 0;declare s int default 0;while n <= 10 do set s = s+n;set n = n+1;end while;select concat('結果是:',s) result;
end$$
delimiter ;call p5();
二、總結
- ?if(判斷多個區間)
- ?case(單個值的判斷)
- loop(死循環)
- while(循環)