第一種情況:
按照 case 的條件順序選擇關聯的第一個表達式作爲結果。
CASE expression
WHEN result1 THEN
statements1
WHEN result2 THEN
statements2
...
ELSE
statements_else
END CASE;
例句:
declare
name varchar2(10) := 'dj';
begin
case name
when 'd' then
dbms_output.put_line('right1');
when 'dj' then
dbms_output.put_line('the name is dj');
else
dbms_output.put_line('i don''t know');
end case;
end;
按照 boolean 條件來順序選擇表達式結果作爲值。
CASE
WHEN expression1 THEN
statements1
WHEN expression2 THEN
statements2
...
ELSE
statements_else
END CASE;
例句:
declare
name varchar2(10) := 'dj';
begin
case
when name = 'd' then
dbms_output.put_line('right1');
when name = 'dj' then
dbms_output.put_line('the name is dj');
else
dbms_output.put_line('i don''t know');
end case;
end;
case語句也可以嵌套
DECLARE
salary number := 50000;
BEGIN
CASE
WHEN salary >= 10000 THEN
CASE
WHEN salary <= 20000 THEN
give_bonus(employee_id, 1500);
WHEN salary > 40000 THEN
give_bonus(employee_id, 500);
WHEN salary > 20000 THEN
give_bonus(employee_id, 1000);
END CASE;
--內部 case 結束
WHEN salary < 10000 THEN
give_bonus(employee_id, 0);
END CASE;
END;
第三種情況:
case表達式
與 case 語句不一樣,case 表達式返回的是一個值,而不是一條語句。另外就是 then 中是結果的值,並且沒有分號結束,而且結束 case 是直接用單個的 end,而不是 case 語句中的 end case。 case 表達式可以用在很多場合, 也就是把 case 表達式的結果當成一個已經有值的變量使用就可以了。
select s.name,
case s.sex
when 0 then
'男'
when 1 then
'女'
end
from student s;
select s.name,
case
when s.sex = 0 then
'男'
when s.sex = 1 then
'女'
end
from student s;
最後,case 語句和 case 表達式的比較:
1.語句的每個 then 之後是語句,故有分號結束,而 case 表達式是返回值,故沒有分號結束
2.case 語句的 case 結束是 end case,而 case 表達式結束是單個的 case。
3.case 語句中若沒有 else,則整個過程中匹配不到會報 case_not_found 異常,而 case 語句沒
有 else 不會報異常,只是返回值爲 null 而已。
4.case 表達式以 end 結束爲標 ,可以做運算。