Query 1: Redundant to_date usage:
SELECT 1
FROM dual
WHERE '22-APR-2018'>add_months(to_date(
(to_date('28-02-2018' ,'dd-mm-yyyy') ) ,'dd-mm-yyyy'),60);
--
Query 2: Single to_date usage:
SELECT 1
FROM dual where '22-APR-2018'>ADD_MONTHS(TO_DATE('28-02-2018' ,'dd-mm-yyyy'),60);
In any case, these queries must not return data, since 22-APR-2018 is never greater than 28-FEB-2023.
But Query 1 returns data. I do not understand oracle functionality here.
There are a few issues with this code. One of them is:
to_date((to_date('28-02-2018', 'dd-mm-yyyy')), 'dd-mm-yyyy')
or without the double-bracketing:
to_date(to_date('28-02-2018', 'dd-mm-yyyy'), 'dd-mm-yyyy')
to_date()
takes a string argument, so Oracle has to convert the date it got from to_date('28-02-2018', 'dd-mm-yyyy')
into a string. So implicitly it's
to_date(to_char(to_date('28-02-2018', 'dd-mm-yyyy')), 'dd-mm-yyyy')
What does to_char(to_date('28-02-2018', 'dd-mm-yyyy'))
give you? It will depend on your nls_date_format
, which often defaults to DD-MON-RR
, in which case you'll get 28-FEB-18
, and converting that back to a date with a YYYY
year format gives 28th Feb 0018 (Oracle implicitly interprets FEB
to match MM
), which is before 22nd April 2018.
Oracle also implicitly converts the string in the comparison to a date, again using the default date format, so although it's obviously a bad idea to compare a string to a date and hope for the best, in this case you get away with it.
In Oracle we write date literals as
date '2018-04-22'
and not
'22-APR-2018'
So the right way to write this would be
select 1
from dual
where date '2018-04-22' > add_months(date '2018-02-28', 60);
which gives no rows.
'22-APR-2018' is not a date
it is a string. So both sides of the condition get implicitly converted to strings and 'APR' < 'FEB'.
Use to_date
on it or (easier) an ANSI literal instead so that you are comparing date
values:
SELECT 1
FROM dual where DATE '2018-04-22'>ADD_MONTHS(TO_DATE('28-02-2018' ,'dd-mm-yyyy'),60);
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.