【问题标题】:Not able to convert String to date using to_date() java.sql.SQLException: ORA-01861 [duplicate]无法使用 to_date() java.sql.SQLException 将字符串转换为日期:ORA-01861 [重复]
【发布时间】:2016-04-24 06:05:46
【问题描述】:

我正在尝试更新输入日期为字符串类型的表

  SELECT FromDate FROM MyTbl where NUM=3;
    *output:*

    FromDate 
------------------------- 
  24-APR-16   

 UPDATE MyTbl SET FLAG='Y' WHERE FromDate=to_date(2016-04-24 00:00:00.0)

   String FromDate= 2016-04-24 00:00:00.0

SQL Error: ORA-01861: literal does not match format string
01861. 00000 -  "literal does not match format string"
*Cause:    Literals in the input must be the same length as literals in
           the format string (with the exception of leading whitespace).  If the
           "FX" modifier has been toggled on, the literal must match exactly,
           with no extra whitespace.
*Action:   Correct the format string to match the literal. 

【问题讨论】:

  • 看起来您正在使用 Java,但发布您正在使用的代码会有所帮助。您发布的 update 语句缺少字符串值周围的引号。我不确定这是因为您在 Java 中动态组装 SQL 语句而忽略了添加单引号,还是因为您在 Java 中使用了绑定变量,而您只是在转录语句的样子时出错文字。此外,您的 to_date 调用需要格式掩码,除非字符串恰好与您会话的 nls_date_format 匹配。

标签: java sql oracle


【解决方案1】:

to_date() 需要一个字符串常量,并且在 SQL 中将字符串放在单引号中。您还需要提供格式掩码:

UPDATE MyTbl SET FLAG='Y' 
   WHERE FromDate=to_date('2016-04-24 00:00:00', 'yyyy-mm-dd hh24:mi:ss');

查看手册了解更多详情:

【讨论】:

    【解决方案2】:

    Oracle date 类型只有第二个分辨率。如果您想保留有关毫秒的信息,请考虑使用timestamp 并转换为date

    UPDATE MyTbl
    SET FLAG='Y'
    WHERE FromDate = CAST(TO_TIMESTAMP('2016-04-24 00:00:00.0', 'YYYY-MM-DD HH24:MI:SS,FF1') AS DATE)
    

    如果您确实想保留毫秒精度,请考虑将FromDate 列更改为timestamp

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-10-21
      • 1970-01-01
      • 2013-12-02
      • 2018-11-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多