decode函数oracle,Oracle Decode函数的使用

DECODE函数的可以根据用户给定的判定条件给定想要的结果

语法:

7d2580383e4cccf63b22dffbc45d6b48.gif

DECODE(expr,{search,result,}….,default)这里给的search,result可以是多个,而括号里所有元素的组合最多是255个.

今天在写一个语句的时候有一个简单的想法,就是遇到数值的进行自动换算,遇到字符返回原值

selectname,value

fromv$parameter

wherenamein('control_file_record_keep_time',

'db_block_size',

'db_cache_advice',

'db_cache_size',

'db_file_multiblock_read_count',

'db_flashback_retention_target',

'db_recovery_file_dest_size',

'job_queue_processes',

'optimizer_index_cost_adj',

'optimizer_mode',

'processes',

'sort_area_size')

比如查询v$parameter视图时候,value的类型是varchar2

3ee1314e688e92f90ffa71f26c471be9.png

其查询结果如下:

b261a700ee682f13c547efc8e184d5d2.png

很明显这样显示是不够人性的,所以我试图把value值表示大小的转化为人类可读的情况,已知该视图根据value的类型进行了分类,可以看一下TYPE这个列

问题到这里就出现了。发现文字类型的是无法被转换的,我用下面这条语句尝试报错

selectname,decode(type,6,round(value/1024/1024,2),3,value,value)

fromv$parameter

wherenamein('control_file_record_keep_time',

'db_block_size',

'db_cache_advice',

'db_cache_size',

'db_file_multiblock_read_count',

'db_flashback_retention_target',

'db_recovery_file_dest_size',

'job_queue_processes',

'optimizer_index_cost_adj',

'optimizer_mode',

'processes',

'sort_area_size')

orderbyname;

5c254b0d3c082c182bb947f8e716f93b.png

无效的数值?明明是字符类型的,什么时候被转换成数值类型的?反复尝试发现问题就出在VALUE是字符的参数项上,这点确实有点困惑,反过来尝试成功了。

97ad9831fe95a433ba36a366556eeaf4.png

查看官方文档中有如下两句话:

·Ifexprandsearchare character data, then Oracle compares them using nonpadded comparison semantics.expr,search, andresultcan be any of the data typesCHAR,VARCHAR2,NCHAR, orNVARCHAR2.The string returned is ofVARCHAR2data type and is in the same character set as the firstresultparameter.

·If the firstsearch-resultpair are numeric, then Oracle compares allsearch-resultexpressions andthe firstexprto determine the argument with the highest numeric precedence, implicitly converts the remaining arguments to that data type, and returns that data type.

内容提到DECODE中的进行比较时,如果expr和search是字符类的,那么后续的结果可能会是任意字符类型的,这个类型根据第一个result返回的字符类型来确定,也就是说如果首个expr和search比对后,返回的result是varchar2类型,那么后续的结果将都会以varchar2类返回。

另外如果首个比对的expr和search是具有更高优先级的数值型数据,其结果就会把后续的所有参数转化为数值类型。

根据对上述内容理解,我进行类型转化如下,发现语句果然能正确执行了:

1a33b2e78bb8f6d45e57b53efb124741.png

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值