case表达式

case表达式

目录导航

介绍

介绍case语句的不同的表达式及作用、用法。

分类

在sql中主要有两种:简单case和搜索case,在plsql中还有两种case 语句,与decode 类似。(有一定的区别)

简单的case:

语法:case exp when comexp then returnvalue

..when comexp then returnvalue

Else

Returnvalue

End

使用规则case简介。

Case到end之间相当于一个具体的值,可以做运算,取别名,嵌套case 等等。只要把case到end当作一个运算结果的表达式就可以了。

《注意,中间一直到end 都没有其他标点符号》

搜索case:

搜索case例子

比较操作,可以使用like,between … and ..,!=,<,>=等操作符以及其他返回boolean类型的操作符。

简单case和searched case之间的区别:

1. 简单case只能是when后面的表达式完全匹配case后的表达式,相当于 =,所以也不能匹配null。

2. searched case可以作为比较条件,那么可以使用like,!=,between ..and,<,=,is null,is not null等,比简单case的使用更加广泛,完全可以替代简单case。

用法

1.Case 表达式返回的是一个确定的value,如果没有else,若前面的都不匹配,则返回null。<else 不是必须的,都没有匹配返回null,这与pl/sql 中的case 语句不同,case 语句如果不写else,都没有匹配,则报case_not_found异常>

2.简单case 中的表达式,when 后面的表达式类型应该全部保持一致。如:

select case 'a' when 'a' then 1 when 9 then 3 end from dual;--所有的when 类型必须与第case之后的表达式值类型保持一致,资料的9应该是’9’,没有自动转换成char,和一般的sql中自动转换不同。

3.所有的then 后面的return_value类型要保持一致

select case 'a' when 'a' then '1' when '9' then '3' else 3 end from dual;--红色部分类型应该保持一致,没有自动转换,else后面的3应该是’3’.

4.对于简单case 表达式,也就是case 表达式 when…那么when null 总是取不到。也就是case 后面的表达式如果值为null,不会与when null 匹配,只会与else 匹配。如:

select case null when null then 'null' else 'not matched!' end from dual;--case的null不会与when后面的null匹配,只会返回else的结果。

关于这点,如果case 后面的表达式有可能为null,如果需要匹配null,那么可以使用decode 和searched case。

Decode:

decode(exp,

value1,res1,

value2,res2,….,

valuen resn,

elsevalue)。

如果其中有存在exp为null,那么如果valuei中有null,则会匹配,返回resi。如:

select decode(null,'a1','1','a2','2',null,'null','not know!') from dual;--返回字符串null

searched case:

case when

condition_1 then value1

when condition_2 then value2…

when condtion_i then valuei

else

elsevalue

end

如果要匹配null,只需要 case when exp is null then ..就可以了

5.对于searched case来说,有自动类型转换,只要条件成立就可以。如:select case when 1='1' then 1 end from dual;--1=’1’条件成立

6.参数最高限制255 个。包括case exp 中的exp 和else 中的,以及when exp1 value 1 算两个参数。如果语句复杂,超过这个限制,可以考虑使用嵌套case。

其它例子

select case (select count(*) as s1 from t1 where a = 1)

when (select count(*) as s2

from t1, t2

where t1.a = t2.a

and t2.a = 1) then

'相等'

else

'不相等'

end

from dual;

相关百科
返回顶部
产品求购 求购