您的位置首页生活百科

oracle中case when的用法[oracle技術]

oracle中case when的用法[oracle技術]

的有关信息介绍如下:

oracle中case when的用法[oracle技術]

在oracle数据库开发中需要用到各种各样的sql函数和语句来提高自己的开发效率。今天介绍下case when的用法。

case when 有两种用法,一种是case后面有表达式和case后面没有表达式的。case后面有表达式的方法和decode的功能差不多,case后面没有表达式的话适合一些不以固定值作为判断的写法。请看下面两个例子。

case when的功能有点像decode但是又比decode的功能强大。

例如:

select

case a

when 1

then 'a is 1'

when 2

then 'a is 2'

else

'others'

end

from table1;

select decode(a,1,'a is 1',2,'a is 2','others') from dual 实现的功能是一样的。这种用法可以参考官方的解说:

倘若是一些复杂的判断的话decode是胜任不了的。

select

case

when (select count(*) from table2 where id=table1.id)>0 then

'table2 and table1 is related'

when (select count(*) from table3 where id=table1.id)>0 then

'table3 and table1 is related'

else

'no table related with table1'

end

from table1

像这样的功能decode就不能实现。随手case when写的复杂一些,但是思路还是非常清晰的。

关于表达式方面你可以根据实际情况去写,有时候简单有时候复杂。上面的语句中我就写了相对复杂的表达式,表达式是一个select语句。有时候还是比较有用的,如果能用decode解决的话还是用decode比较好,毕竟用case when感觉比较臃肿。反正力求高效简洁吧。

好了case when的用法就先这样吧,如果你有更好的建议非常欢迎留言!