Oracle NVL 函数不允许第二个参数作为日期时间

Oracle NVL function not allows second parameter as datetime

select nvl(trunc(null),trunc(sysdate)) from dual;

执行上述查询时出现以下错误

ORA-00932: inconsistent datatypes: expected NUMBER got DATE

当我使用字符串或数字而不是 trunc(sysdate) 时看起来 运行 很好。

来自here

The first parameter to NVL is determining the expected datatype of the returned column, with the trunc function defaulting that to NUMBER because it's parameter is NULL. The second parameter to NVL needs to match that datatype which it doesn't because it is a date.

SQL> select nvl(trunc(sysdate), sysdate) as mydate from dual;

MYDATE
-------------------
26/05/2006 00:00:00

SQL> select nvl(trunc(null), sysdate) as mydate from dual;
select nvl(trunc(null), sysdate) as mydate from dual
                        *
ERROR at line 1:
ORA-00932: inconsistent datatypes: expected NUMBER got DATE

或者你可以这样做:

SELECT NVL(TO_DATE(TRUNC(NULL)),SYSDATE) FROM dual;

第二个参数必须与第一个参数的数据类型相同。 trunc 函数重载。显然,当您将 null 传递给它时,它将值解释为数字,而 returns 则解释为数字。以下作品之一:

SELECT NVL (NULL, TRUNC (SYSDATE)) FROM DUAL;

SELECT NVL (TRUNC (TO_DATE (NULL)), TRUNC (SYSDATE)) FROM DUAL;

SELECT NVL (TRUNC (CAST (NULL AS DATE)), TRUNC (SYSDATE)) FROM DUAL;

跟进:

如果正在使用的变量被正确定义为日期,那么您应该没有问题。例如,以下运行没有错误:

DECLARE
   FUNCTION f
      RETURN DATE IS
   BEGIN
      RETURN NULL;
   END f;
BEGIN
   DBMS_OUTPUT.put_line (NVL (TRUNC (f), TRUNC (SYSDATE)));
END;

为了得到真正解决问题的答案,我建议编辑问题以包含实际演示问题的代码。