简体   繁体   中英

More on extracting year from date - Oracle

I have a question about selecting year from a date. This is in Oracle database 12c.

Given that SELECT trunc(SYSDATE) FROM DUAL; returns 02/06/2020

These work proper and return current year of 2020 -

SELECT EXTRACT(YEAR FROM trunc(SYSDATE)) FROM DUAL;
SELECT TO_CHAR(trunc(SYSDATE,'YYYY')) FROM DUAL;

These do not work and give error -

SELECT EXTRACT(YEAR FROM '02/06/2019') FROM DUAL;

Gives error: ORA-30076: invalid extract field for extract source

SELECT TO_CHAR('02/06/2019','YYYY') FROM DUAL;

Gives error: ORA-01722: invalid number

The same format is being passed with sysdate and hard coded date of 02/06/2019. Why is it that one works and the other does not?

I know I could just select 2019 from dual but that is not the point or use case here.

You can't extract year from a string (which '02/06/2019' is). First convert it to date:

SQL> SELECT EXTRACT(YEAR FROM to_date('02/06/2019', 'dd/mm/yyyy')) year FROM DUAL;

      YEAR
----------
      2019

SQL>

Or, if you know that last 4 digits are valid year, then

SQL> select substr('02/06/2019', -4) year from dual;

YEAR
----
2019

SQL>

It comes down to the data type being passed. sysdate by default is a DATE field. A hard date like '02/06/2020' by default is considered a string.

To get around that, just cast the string as a date. All good.

SELECT TO_CHAR(cast('6-feb-2019' as date),'YYYY') FROM DUAL;

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