oracle中的控制語(yǔ)句
一霎奢、條件語(yǔ)句
條件語(yǔ)句包含if else蠕蚜、case when
1.01扣囊、if else
語(yǔ)法:if之后 跟條件表達(dá)式乎折,當(dāng)該條件返回真時(shí),將執(zhí)行其后的語(yǔ)句如暖,否則執(zhí)行else后面的語(yǔ)句
例如:
set serveroutput on
declare num number;
begin
select count(*) into num from employee where emp_salary>5000;
if num>0 then
dbms_output.put_line('存在工資高于5000的員工');
else
dbms_output.put_line('不存在工資高于5000的員工');
end if;
end;
備注:set serveroutput on用于打開打印輸出笆檀,默認(rèn)的狀態(tài)下是關(guān)閉的,若含有兩種以上的情況盒至,可以用elsif……then
1.02、case ?when
例如:
set serveroutput on
declare num number;
begin
select count(*) into num from employee where emp_salary>5000;
case
when num>0 then
dbms_output.put_line('存在工資高于5000的員工');
when ?num=0 then
dbms_output.put_line('不存在工資高于5000的員工');
end case;end;
備注:case when 的另一個(gè)用法
select name,sum(case when subject='數(shù)學(xué)' then score else 0 end) "數(shù)學(xué)" from scores group by name;二、循環(huán)語(yǔ)句
循環(huán)語(yǔ)句包含:無(wú)條件循環(huán)枷遂、while循環(huán)和for循環(huán)
2.01樱衷、?無(wú)條件循環(huán)
例如:
set serveroutput on
declare num number:=0;
v_name varchar2(20);
begin
loop
if num>4 then
exit;
end if;
num:=num+1;
select emp_name into v_name from employee where emp_id=num;
dbms_output.put_line(num||'號(hào)員工是'|| v_name);
end loop;
end;
結(jié)果:
1號(hào)員工是張三
2號(hào)員工是李四
3號(hào)員工是趙飛
4號(hào)員工是韓明
5號(hào)員工是王蘭2.02、while循環(huán)
while循環(huán)也是利用loop循環(huán)的形式酒唉,只是在loop前加了條件
語(yǔ)句:
set serveroutput on
declare num number:=0;
v_name varchar2(20);
begin
while num<=4 loop
num:=num+1;
select emp_name into v_name from employee where emp_id=num;
dbms_output.put_line(num||'號(hào)員工是'|| v_name);
end loop;end;
結(jié)果:
1號(hào)員工是張三
2號(hào)員工是李四
3號(hào)員工是趙飛
4號(hào)員工是韓明5號(hào)員工是王蘭2.03矩桂、for循環(huán)
for循環(huán)適用于循環(huán)次數(shù)確定的情況下
語(yǔ)句:
set serveroutput on
declare num number;
v_name varchar2(20);
begin
select count(*) into num from employee where emp_salary>5000;
for i in 1..num loop
select emp_name into v_name from employee where emp_id=i;
dbms_output.put_line(i||'號(hào)員工是'|| v_name);
end loop;end;
結(jié)果:
1號(hào)員工是張三2號(hào)員工是李四