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

在执行上述查询时,我收到以下错误

ORA-00932: inconsistent datatypes: expected NUMBER got DATE

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

4

2 回答 2

5

这里

NVL 的第一个参数是确定返回列的预期数据类型,trunc 函数将其默认为 NUMBER,因为它的参数为 NULL。NVL 的第二个参数需要匹配它不匹配的数据类型,因为它是一个日期。

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;
于 2015-06-18T13:41:24.703 回答
1

The second parameter must be of the same datatype as the first parameter. The trunc function is overloaded. Apparently when you pass it a null, it interprets the value as a number and returns a number. Any of the following works:

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;

Follow up:

If the variable that is being used is properly defined as a date, then you should not have a problem. As an example, the following runs without error:

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

In order to get an answer that actually solves your problem, I would recommend editing the question to include code that actually demonstrates the problem.

于 2015-06-18T13:43:01.180 回答