Oracle Decode函数的使用

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

语法:

Oracle Decode函数的使用

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

 

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

selectname,value

  from v$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

Oracle Decode函数的使用

其查询结果如下:

Oracle Decode函数的使用

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

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

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

  from v$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;

Oracle Decode函数的使用

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

 Oracle Decode函数的使用

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

·         If expr and search are character data, then Oracle compares them using nonpadded comparison semantics. expr, search, and result can be any of the data types CHAR, VARCHAR2, NCHAR, or NVARCHAR2.The string returned is of VARCHAR2 data type and is in the same character set as the first result parameter.

·         If the first search-result pair are numeric, then Oracle compares all search-result expressions and the first expr to determine the argument with the highest numeric precedence, implicitly converts the remaining arguments to that data type, and returns that data type.

 

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

 

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

 

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

Oracle Decode函数的使用