PL/SQL與SQL(Oracle)Case語句

(使用scott賬戶下的表)
1.Oracle SQL語句的case語句寫法:

--sql中的case用於分支判斷並返回某個值。
select empno , ename, deptno ,  
case deptno
  when 10 then '總經辦'
  when 20 then '綜管部'
  when 30 then '市場部'
  else '其他'
end
from emp;

select empno , ename, deptno ,  
case 
  when deptno=10 then '總經辦'
  when deptno=20 then '綜管部'
  when deptno=30 then '市場部'
  else '其他'
end
from emp;

2.PL/SQL語句的case語句寫法:

plsql中語法1:

case 字段|變量
       when 比對值 then 執行語句...;
       [when 比對值 then 執行語句...;]
       [else 執行語句... ;]

plsql中語法2:

case 
       when 表達式 then 執行語句...;
       [when 表達式 then 執行語句...;]
       [else 執行語句... ;]
   end case;

PLSQL中的case可用於分支判斷並<返回>,也可以用於分支判斷<執行>
用case判斷,並把返回值賦給某變量


declare
  v_dname varchar(20);
  v_deptno int:=10;
begin
  v_dname := 
  case v_deptno
  when 10 then '總經辦' --返回值不要分號
  when 20 then '綜管部'
  when 30 then '市場部'
  else '其他'
  end;   --case結束時只用end
  dbms_output.put_line(v_dname);  
end;

declare
  v_dname varchar(20);
  v_deptno int:=10;
begin
  v_dname := 
  case 
  when v_deptno=10 then '總經辦'
  when v_deptno=20 then '綜管部'
  when v_deptno=30 then '市場部'
  else '其他'
  end;
  dbms_output.put_line(v_dname);  
end;

用case判斷,並在分支中給某變量賦值

declare
  v_dname varchar(20);
  v_deptno int:=10;
begin
  case v_deptno
  when 10 then v_dname:='總經辦'; --分支判斷中執行,分號結束
  when 20 then v_dname:='綜管部';
  when 30 then v_dname:='市場部';
  else v_dname:='其他';
  end case; -- case結束時要end case;
  dbms_output.put_line(v_dname);  
end;

declare
  v_dname varchar(20);
  v_deptno int:=10;
begin
  case 
  when v_deptno=10 then v_dname:='總經辦';
  when v_deptno=20 then v_dname:='綜管部';
  when v_deptno=30 then v_dname:='市場部';
  else v_dname:='其他';
  end case; 
  dbms_output.put_line(v_dname);  
end;

有待完善….

發佈了19 篇原創文章 · 獲贊 27 · 訪問量 8萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章