转换为日期 - 文字与格式字符串不匹配

时间:2014-09-23 08:14:49

标签: sql oracle date-formatting

我有这个选择:

 select P.DT03_DT as PROPOSAL_DATE,
        p.dt02_dt as DATE_OF_JUDGEMENT,
        P.DT05_DT as END_DATE,
        cast('20140704' as date) as Dt  

       from imxdb.t_intervenants i    
         join imxdb.g_indivparam p
       on i.refindividu = p.refindividu

        where p.type = 'BANCRUPTCY'    
         AND (to_char(p.dt02_dt, 'yyyymmdd') ='20140704' or
         to_char(P.DT05_DT, 'yyyymmdd') = '20140704')

这给了我错误:

  

ORA-01861:文字与格式字符串不匹配                             01861. 00000 - "文字与格式字符串"

不匹配

但是,当我只是将该行"#(' 20140704'作为日期)作为Dt"工作正常,为什么?

谢谢

2 个答案:

答案 0 :(得分:3)

问题在于NLS_DATE_FORMAT

让我用一个小例子来解释:

我的NLS_DATE_FORMATDD-MON-RR

SQL> SELECT VALUE FROM V$NLS_PARAMETERS WHERE PARAMETER='NLS_DATE_FORMAT';

VALUE
----------------------------------------------------------------
DD-MON-RR

SQL>

我可以在SQL * Plus中验证:

SQL> SELECT SYSDATE FROM DUAL;

SYSDATE
---------
23-SEP-14

SQL>

现在,如果我使用未知格式的CAST日期文字,我将收到错误:

SQL> SELECT CAST('20140704' AS DATE) AS DT FROM DUAL;
SELECT CAST('20140704' AS DATE) AS DT FROM DUAL
            *
ERROR at line 1:
ORA-01861: literal does not match format string


SQL>

所以,我会给出所需的NLS_DATE_FORMAT,它应该没问题:

SQL> SELECT CAST('23-sep-14' AS DATE) AS DT  FROM DUAL;

DT
---------
23-SEP-14

SQL>

其他替代方案,

  • 更改NLS_DATE_FORMAT
  • 在会话级别更改。
  • 或者,您可以使用TO_DATE并使用正确的`FORMAT

它将OVERRIDE locale-specific NLS settings

SQL> select to_date('20140704', 'YYYYMMDD') from dual;

TO_DATE('
---------
04-JUL-14

如果您想在desired format中显示,请使用TO_CHAR

答案 1 :(得分:2)

替换

cast('20140704' as date) as Dt  

TO_DATE('20140704','YYYYMMDD') as Dt