本文主要目的在於讓讀者瞭解PL/SQL中的流程控制語句,並能快速的應用在日常工作中。
在使用流程控制語句之前,可以先問問自己,要用選擇還是循環,選擇的話有幾種判斷幾種選擇,循環的話看有沒有限制循環次數以及是先循環再判斷還是先判斷再循環。無論是選擇語句還是循環語句都需要判斷,選擇語句的判斷是如何選,循環語句的判斷是是否循環。
PL/SQL中的流程控制語句分爲兩大類:
- 選擇語句
- 循環語句
選擇語句4種
- if…then…end if;【1種判斷1種選擇】【做與不做】
-- 比較兩個字符串的長度
set serveroutput on
declare
a varchar2(10):='ALEN';
b varchar2(10):='BLENGTH';
begin
if length(a)<length(b) then
dbms_output.put_line('a的長度比b短');
end if;
end;
/
- if…then…else…end if;【1種判斷2種選擇】【做這個還是做另一個】
-- 比較兩個字符串的長度
set serveroutput on
declare
a varchar2(10):='ALEN';
b varchar2(10):='BLENGTH';
begin
if length(a)<length(b) then
dbms_output.put_line('a的長度比b短');
else
dbms_output.put_line('a的長度不比b短');
end if;
end;
/
- if…then…elsif…then…else…end if;【多種判斷多種選擇】【做哪一個】
-- 比較兩個字符串的長度
set serveroutput on
declare
a varchar2(10):='ALEN';
b varchar2(10):='BLENGTH';
begin
if length(a)<length(b) then
dbms_output.put_line('a的長度比b短');
elsif length(a)>length(b) then
dbms_output.put_line('a的長度比b長');
else
dbms_output.put_line('a的長度和b一樣長');
end if;
end;
/
- case…when…then…when…then…else…end case;【至少2種選擇的判斷,選擇器判斷,1則執行語句1,2則執行語句2,…,n則執行語句n,都不滿足則執行語句n+1】【多選擇的判斷建議使用case】
set serveroutput on
declare
i int:=2;
begin
case i
when 1 then
dbms_output.put_line('現在是春季!');
when 2 then
dbms_output.put_line('現在是夏季!');
when 3 then
dbms_output.put_line('現在是秋季!');
when 4 then
dbms_output.put_line('現在是冬季!');
else
dbms_output.put_line('輸入數字有錯,請重新輸入');
end case;
end;
/
循環(loop)語句3種
- loop…exit when … end loop;【先循環,後判斷,至少循環1次】
-- 求前100個自然數的和
set serveroutput on
declare
n_sum int:=0;
n int:=0;
begin
loop
n:=n+1;
n_sum:=n_sum+n;
exit when n=100;
end loop;
dbms_output.put_line('前100個自然數的和爲'||n_sum);
end;
/
- while…loop…end loop;【先判斷,再循環,可能循環0次】
-- 求前100個自然數的和
set serveroutput on
declare
n_sum int:=0;
n int:=1;
begin
while n<=100 loop
n_sum:=n_sum+n;
n:=n+1;
end loop;
dbms_output.put_line('前100個自然數的和爲'||n_sum);
end;
/
- for x in 1…n l… end loop;【先判斷,再循環,限定循環次數】
-- 求前100個自然數的和
set serveroutput on
declare
n_sum int:=0;
n int:=1;
begin
for n in 1..100 loop
n_sum:=n_sum+n;
end loop;
dbms_output.put_line('前100個自然數的和爲'||n_sum);
end;
/