为什么Oracle的DECODE给我的价值与NVL不同? [英] Why is Oracle's DECODE giving me a different value than NVL?

查看:178
本文介绍了为什么Oracle的DECODE给我的价值与NVL不同?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

此查询:

select nvl(0.75,0) from dual

给我 0.75 (数字)但是这个查询:

gives me 0.75 (numeric) but this query:

select decode(1,0,null,0.75) from dual 

给了我'。75'(字符串)。

为什么?

我试图通过将第二个查询更改为:

I tried to fix this by changing the second query to:

select decode(1,0,null,to_char(0.75,'0.99')) from dual

但在我的实际代码0.75将是一个字段(NUMBER),可能有不同的小数位数,我不想添加/删除该值的任何内容。

but in my actual code the 0.75 will be a field (NUMBER) that may have a different number of decimal places and I'm not suppose to add/remove anything from that value.

关于如何修复缺失的零问题但仍然支持所有可能的小数长度的任何想法?

Any ideas on how to fix the missing zero issue but still support all possible decimal lengths?

推荐答案

这是因为3 解码语句的rd 参数为NULL;根据文档 1 (我的重点)。

It's because the 3rd parameter of your decode statement is NULL; as per the documentation1 (my emphasis).


Oracle自动将expr和每个搜索值转换为第一次搜索的数据类型比较前的值 ....如果第一个结果的数据类型为CHAR,或者如果第一个结果为空则为,则Oracle会将返回值转换为数据类型VARCHAR2

Oracle automatically converts expr and each search value to the data type of the first search value before comparing.... If the first result has the data type CHAR or if the first result is null, then Oracle converts the return value to the data type VARCHAR2.

在您的情况下,第一个结果为NULL,Oracle将其视为VARCHAR2。您的返回值被隐式转换为VARCHAR2。如果您将 DECODE()更改为以下内容,则会得到一个数字:

In your case the first result is NULL, which Oracle treats as a VARCHAR2. Your return value is being implicitly converted to a VARCHAR2. If you changed your DECODE() to the following you'd get a number:

select decode(1, 0, 0, 0.75)

你可以实现你的NULL使用 NULLIF() 功能:

and you could achieve your NULL by using the NULLIF() function:

select nullif(decode(1, 0, 0, 0.75), 0) ...

最好使用CASE语句,强制所有返回的数据类型都是相同:

It's better to use a CASE statement, which enforces that all returned datatypes are the same:

select case 1 when 0 then null
              else 0.75
       end ...

1。我也被抓住了。

这篇关于为什么Oracle的DECODE给我的价值与NVL不同?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆