简体   繁体   中英

How to fix date format problem in Oracle?

I need to run this query

SELECT ADD_MONTHS (
    TRUNC (TO_DATE (i.list_member, 'dd-mm-yyyy'),'MM'), 1 * LEVEL - 13) month
    FROM   DUAL

Where i.list_member is a VARCHAR2, which is a result of a select and the format is like mm-yyyy (09-2019)

When I run the query, I get

SQL error [1841] [22008]: ORA-01841: the (complete) year must be between -4713 and +9999, and be different from 0

The problem is the date format, could someone help to solve it?

i.list_member is a VARCHAR2, which is a result of a select and the format is like mm-yyyy (09-2019)

To translate the date:

select add_months(to_date (i.list_member, 'mm-yyyy'), level - 13) month
from dual -- you should be selecting from a table here

Or if you want the month number of the translated date:

select extract(month from add_months(to_date (i.list_member, 'mm-yyyy'), level - 13)) month
from dual

Format mask should match data, ie

SQL> alter session set nls_date_format = 'dd.mm.yyyy';

Session altered.

SQL>     SELECT ADD_MONTHS (TRUNC (TO_DATE ('09-2019', 'mm-yyyy'), 'MM'),
  2                         1 * LEVEL - 13)
  3                month                     ^^^^^^
  4        FROM DUAL                         This is i.list_member     
  5  CONNECT BY LEVEL <= 12
  6  /

MONTH
----------
01.09.2018
01.10.2018
01.11.2018
01.12.2018
01.01.2019
01.02.2019
01.03.2019
01.04.2019
01.05.2019
01.06.2019
01.07.2019
01.08.2019

12 rows selected.

SQL>

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