ORA-01843“无效月份”和ORA-01861“文字与格式字符串不匹配”

时间:2010-12-14 18:45:15

标签: sql database oracle date-arithmetic

SQL> select to_timestamp('2010-12-14:09:56:53') - to_timestamp('2010-12-14:09:56:46') from dua
l;
select to_timestamp('2010-12-14:09:56:53') - to_timestamp('2010-12-14:09:56:46') from dual
                    *
ERROR at line 1:
ORA-01843: not a valid month


SQL> select to_date('2010-12-14:09:56:53') - to_date('2010-12-14:09:56:46') from dual;
select to_date('2010-12-14:09:56:53') - to_date('2010-12-14:09:56:46') from dual
               *
ERROR at line 1:
ORA-01861: literal does not match format string

执行

的正确方法是什么
2010-12-14:09:56:53
minus
2010-12-14:09:56:46
在Oracle SQL中

2 个答案:

答案 0 :(得分:12)

您必须指定时间戳字符串在TO_DATETO_TIMESTAMP函数中的格式:

select 
    to_date('2010-12-14:09:56:53', 'YYYY-MM-DD:HH24:MI:SS') - 
    to_date('2010-12-14:09:56:46', 'YYYY-MM-DD:HH24:MI:SS') 
from dual;

结果将以天为单位,您可以乘以86,400得到秒:

TO_DATE('2010-12-14:09:56:53','YYYY-MM-DD:HH24:MI:SS')-TO_DATE('2010-12-14:09:56
--------------------------------------------------------------------------------
.000081019

使用TO_TIMESTAMP

select 
    to_timestamp('2010-12-14:09:56:53', 'YYYY-MM-DD:HH24:MI:SS') - 
    to_timestamp('2010-12-14:09:56:46', 'YYYY-MM-DD:HH24:MI:SS') 
from dual;

结果将采用TIMESTAMP格式:

TO_TIMESTAMP('2010-12-14:09:56:53','YYYY-MM-DD:HH24:MI:SS')-TO_TIMESTAMP('2
---------------------------------------------------------------------------
+000000000 00:00:07.000000000

答案 1 :(得分:2)

使用to_timestamp

select TO_TIMESTAMP('2010-12-14:09:56:53',  'YYYY-MM-DD:HH24:MI:SS.FF') 
 - TO_TIMESTAMP('2010-12-14:09:56:46',  'YYYY-MM-DD:HH24:MI:SS.FF') 

from dual