if語句
oracle: elsif java: else if
if (條件) then
pl/sql或sql語句
[elsif (條件) then ]
...可以有多個elsif
[else]
end if; ---必須寫 結束大括号
例:
--完成根據員工的編号檢視員工需要交的稅的情況 大于等于3000交1% 大于等于1500交 0.5%,低于1500的不要交稅
declare
v_empno emp.empno%type;
v_sal emp.sal%type;
v_name emp.ename%type;
v_rate emp.sal%type; --需要交的稅
begin
v_empno :='&請輸入員工編号';
select ename,sal into v_name,v_sal from emp where empno = v_empno;
if v_sal >= 3000 then
v_rate := v_sal*0.01;
elsif v_sal >= 1500 then
v_rate := v_sal*0.005;
else
v_rate := 0;
end if;
dbms_output.put_line('編号為'||v_empno||'的員工姓名:' || v_name
||',薪水:'||v_sal||',需要交的稅:'||v_rate);
end;
swicth結構:oracle 的case -decode 是對case的簡寫
case 等值判斷
類似于java的switch
case 表達式
when 值1 then
...
when 值2 then
...
...
else
...
end case ;
例:
--查詢員工的崗位, 顯示的中文的
declare
v_empno emp.empno%type := '&請輸入員工的編号';
v_job emp.job%type;
v_cJob emp.job%type;
begin
select job into v_job from emp where empno = v_empno;
case v_job
when 'CLERK' then
v_cJob :='文員';
when 'SALESMAN' then
v_cJob :='銷售';
when 'MANAGER' then
v_cJob :='主管';
when 'ANALYST' then
v_cJob :='研發';
when 'PRESIDENT' then
v_cJob :='董事長';
else
v_cJob := '未知';
end case;
dbms_output.put_line(v_cJob);
end;
case 範圍判斷,等值(類似if)
case
when 條件 then
...
when 條件 then
...
...
else
...
end case;
例:
declare
v_empno emp.empno%type;
v_sal emp.sal%type;
v_name emp.ename%type;
v_rate emp.sal%type; --需要交的稅
begin
v_empno :='&請輸入員工編号';
select ename,sal into v_name,v_sal from emp where empno = v_empno;
/*
if v_sal >= 3000 then
v_rate := v_sal*0.01;
elsif v_sal >= 1500 then
v_rate := v_sal*0.005;
else
v_rate := 0;
end if;
*/
case
when v_sal >= 3000 then
v_rate := v_sal*0.01;
when v_sal >= 1500 then
v_rate := v_sal*0.005;
else
v_rate := 0;
end case;
dbms_output.put_line('編号為'||v_empno||'的員工姓名:' || v_name
||',薪水:'||v_sal||',需要交的稅:'||v_rate);
end;
if ,case if不能再sql語句中使用, case 可以在sql語句中使用
--查詢員工的資訊,以及 >=3000 高新, >=1500 中等收入, <1500 底薪 收入情況
-- 注意: *** sql語句中使用case, 不能使用end case, 使用end;
-- 而pl/sql塊, case 的結束是一定使用 end case;
--decode() 函數, 在sql使用, 簡化 case等值判斷,
-- 在sql中使用範圍判斷, 使用case
select e.*, case
when e.sal >=3000 then '高新'
when e.sal >=1500 then '中等收入'
else '底薪'
end 收入情況
from emp e;