第一种情况:
按照 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 结束为标 ,可以做运算。