简体   繁体   中英

oracle 12c select to_date(' ',' ') dt from dual; returns 2017-10-01

somehow select to_date('space','space') dt from dual; returns some date 2017-10-01 ,

but to_date('','space') or to_date('space','') returns null as expected.

where "space" is chr(32)

Any idea?

Thanks

I wasn't able to find all the defaults in the documentation, but this should suffice:

If you specify a date value without a time component, then the default time is midnight. If you specify a date value without a date, then the default date is the first day of the current month.

https://docs.oracle.com/cd/B28359_01/server.111/b28286/functions191.htm#SQLRF06132

(This is for Oracle 11.1, but you will find the same for other versions).

In your code, you specify a date without a time component and without a date component. Apply both defaults from above and you will get your answer.

Another small piece of the puzzle is the treatment of spaces. You can take any valid TO_DATE() and add generous spaces around any of the date and time elements, in both arguments, and you will see they are ignored. In your case, the single space is ignored (but not "collapsed" - your inputs aren't converted to empty strings, meaning null in Oracle).

According to Tom Kyte on the AskTom forums, there are some default values that are used with TO_DATE when a format and input date cannot be determined.

https://asktom.oracle.com/pls/apex/f?p=100:11:0::::P11_QUESTION_ID:4843459400346642911

default year   = current year 
default month  = current month 
default day    = 1
default hour   = 0
default minute = 0
default second = 0

This means that using a TO_DATE(' ', ' ') means that Oracle cannot work out what format or input date is being used, so it uses the 1st day of the current month and year, which is 2017-10-01 (yyyy-mm-dd format).

It also means your second query of TO_DATE('', ' ') returns NULL, because the value you're supplying as a date is empty. This is different from a space - I think Oracle sees the space and thinks "oh I don't know what this is, I'll show the default".

There is a brief mention of this on the Oracle Format Models documentation page here , but I couldn't find a mention of what the default values are.

Update: as mathguy mentioned below: if the day is missing from BOTH the string to be converted AND from the format model, then by default it is assumed to be 1. Etc. `to_date('15', 'dd') will return midnight on the 15th of the current month and year. To the extreme, the OP omitted ALL the elements from BOTH arguments, so all are assigned the defaults. It's not that Oracle "can't work out what format", but instead it's all defaults

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM