ale
ale

Reputation: 11820

What's wrong with the usage of to_date in this Oracle query?

I have a query like this:

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

but I get:

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"

and:

*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.

but my usage of to_date seems okay?

Many thanks.

Upvotes: 0

Views: 1570

Answers (1)

Justin Cave
Justin Cave

Reputation: 231671

That looks correct. And it works for me so there must be something else to the problem that isn't part of your example...

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.

Are you really using hard-coded literals? Or are the strings you're passing to to_date coming from a table? Is it possible that there is (at least) one row in the table where the data doesn't match the expected format. Note that a row that is ultimately filtered out by a WHERE clause, even a WHERE clause in a subquery, can still call to_date before getting filtered out and cause the error. So it would be perfectly plausible that you would have something like

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

return an error.

Upvotes: 4

Related Questions