在这个Oracle查询中使用to_date有什么问题?

时间:2012-10-24 21:13:59

标签: sql oracle

我有这样的查询:

INSERT INTO some_table (date1, date2) 
VALUES (to_date('2012-10-24','YYYY-MM-DD'), to_date('2012-10-24','YYYY-MM-DD'));

但我明白了:

SQL Error: ORA-01858: a non-numeric character was found where a numeric was expected
01858. 00000 -  "a non-numeric character was found where a numeric was expected"

*Cause:    The input data to be converted using a date format model was
           incorrect.  The input data did not contain a number where a number was
           required by the format model.
*Action:   Fix the input data or the date format model to make sure the
           elements match in number and type.  Then retry the operation.

但我对to_date的使用似乎没问题?

非常感谢。

1 个答案:

答案 0 :(得分:4)

看起来很正确。它对我有用,所以问题中必须有其他东西不属于你的例子......

SQL> create table some_table( date1 date, date2 date );

Table created.

SQL> INSERT INTO some_table (date1, date2)
  2  VALUES (to_date('2012-10-24','YYYY-MM-DD'), to_date('2012-10-24','YYYY-MM-DD'));

1 row created.

你真的使用硬编码的文字吗?或者你传递给to_date的字符串来自一张桌子?表中是否有(至少)一行数据与预期格式不匹配。请注意,最终被WHERE子句过滤掉的行,甚至是子查询中的WHERE子句,仍然可以在被过滤掉之前调用to_date并导致错误。所以你会有像

这样的东西是完全合理的
INSERT INTO some_table( date1, date2 )
  SELECT to_date( string1, 'YYYY-MM-DD' ), to_date( string2, 'YYYY-MM-DD' )
    FROM (SELECT *
            FROM some_other_table
           WHERE condition_that_limits_the_data_to_just_valid_date_strings )
   WHERE some_other_condition

返回错误。