我正在阅读 Oracle decode()
documentation 。据我所知,当调用 decode(expr, search1, value1, search2, value2...)
时,Oracle 会强制转换 expr
、search2
和search3
为 search1
的类型并进行比较。
因此,如果 search1
为 NULL
,那么 search2
、search3
等将被转换为什么?
示例:
create table sc(a date, b varchar2(256));
insert into sc values(
to_date('2010-01-01 11:22:33', 'yyyy-mm-dd hh24:mi:ss'),
'2010-01-01 11:22:33'
);
select decode(
to_date('2010-01-01 11:22:33', 'yyyy-mm-dd hh24:mi:ss'),
null,
1,
b,
123,
a,
456
)
from sc;
为什么结果是 456 而不是 123?
最佳答案
编辑: 当第一个要比较的值是 null 或 char 时,所有值都将转换为 varchar2 并作为字符串进行比较。因此,如果不比较字符串,则始终比较相等的类型,并且不要使用 null 作为第一个比较值:
select decode(
to_date('2010-01-01 11:22:33', 'yyyy-mm-dd hh24:mi:ss'),
to_date('2010-01-01 11:22:31', 'yyyy-mm-dd hh24:mi:ss'),
0,
null,
1,
to_char(to_date('2010-01-01 11:22:33', 'yyyy-mm-dd hh24:mi:ss')),
2,
to_date(b, 'yyyy-mm-dd hh24:mi:ss'),
123,
a,
456
)
from sc;
如果第一个比较值为 NULL,则日期将转换为具有默认日期表示形式的字符串(可以与 b 中的不同)并与 b 进行比较。如果您想查看默认值,请使用:
select to_char(to_date('2010-01-01 11:22:33', 'yyyy-mm-dd hh24:mi:ss')),b from sc
如果我们阅读 Oracle 文档:
If the first result has the datatype CHAR or if the first result is null, then Oracle converts the return value to the datatype VARCHAR2.
同样的情况也发生在值(value)观上。第一个值为 null,然后所有内容都转换为字符串。您可以在此处看到它。
SELECT DECODE (1, NULL, 1, '01', 2, '1 ', 3, '1', 4, 1, 5) FROM DUAL;
现在用数字更改 null
SELECT DECODE (1, 5, 1, '01', 2, '1 ', 3, '1', 4, 1, 5) FROM DUAL;
什么会给出这个:
SELECT DECODE (TO_DATE ('2010-01-01 11:22:33', 'yyyy-mm-dd hh24:mi:ss'),
NULL, 1,
TO_DATE ('2010-01-01 15:22:32', 'yyyy-mm-dd hh24:mi:ss'), 2,
'3')
FROM DUAL
关于sql - 当搜索为空时 oracle 中的解码行为,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37568131/