Oracle case when 详解

文章目录

1 概述

1. case when:条件判断语句
	(1) 相当于其它语言中的 if else
	(2) 部分情况下,等同于 decode()
2. case when 表达式用两种形式
    -- 简单 case 函数,要求:when 对象的类型 和 case 对象的类型一致
    -- 此时等同于 decode(sex, '1', '男', '2', '女')
    case sex
      when '1' then '男'
      when '2' then '女'
    else
      '其它'
    end;
   -- case 表达式
   case
     when sex = '1' then '男'
     when sex = '2' then '女'
   else
     '其它'
   end;
3. 注意:when 的执行顺序,当 '第一个' when 满足条件时,便结束查询
	   (不会继续判断其它的 when 条件) 
4. 建议:当 case when 和 decode 等价,且判断语句不超过 10 行时,
        使用 decode(语法简洁)

 
 

2 示例: when 执行顺序

示例1:根据 “成绩”,获取 "评分"

with t_score as (
  select 90 score, '瑶瑶' name from dual union all
  select 80 score, '倩倩' name from dual union all
  select 70 score, '优优' name from dual 
)
select t.name,
       t.score,
       (case
         when t.score >= 90 then
          '优秀'
         when t.score >= 80 then
          '良好'
         when t.score >= 60 then
          '及格'
         else
          '不及格'
       end) 评分
  from t_score t;

 
 

查询结果:(正确,符合实际需求)

    name score  评分
1	瑶瑶	  90	优秀
2	倩倩	  80	良好
3	优优	  70	及格

 
 

示例2(反例):

with t_score as (
  select 90 score, '瑶瑶' name from dual union all
  select 80 score, '倩倩' name from dual union all
  select 70 score, '优优' name from dual 
)
select t.name,
       t.score,
       (case
         when t.score >= 60 then
          '及格'
         when t.score >= 80 then
          '良好'
         when t.score >= 90 then
          '优秀'
         else
          '不及格'
       end) 评分
  from t_score t;

 
 

查询结果:(错误)

    name score  评分
1	瑶瑶	  90	及格
2	倩倩	  80	及格
3	优优	  70	及格

 
 

3 ORA-06592: 执行 CASE 语句时未找到 CASE

  • 在 Oracle 中,若省略 else 子句,当存在不符合的条件时,默认为 null
  • 在 PL/SQL 中,若省略 else 子句,当存在不符合的条件时,直接 报错
declare
   i integer := 6;
begin
   case
      when i <= 5 then
         dbms_output.put_line('小于等于 5');
      when i <= 1 then
         dbms_output.put_line('小于等于 1');
/*      else
         -- 解决办法,增加一个 else 分支
         dbms_output.put_line('case 中无符合的 i');*/
   end case;
exception
   when others then
      dbms_output.put_line(dbms_utility.format_error_backtrace);
      dbms_output.put_line(sqlerrm);
end;

 
 

输出结果:

ORA-06512: 在 line 4
ORA-06592: 执行 CASE 语句时未找到 CASE

 
 
  • 7
    点赞
  • 19
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值