简体   繁体   English

更多关于从日期中提取年份 - Oracle

[英]More on extracting year from date - Oracle

I have a question about selecting year from a date.我有一个关于从日期中选择年份的问题。 This is in Oracle database 12c.这是在 Oracle 数据库 12c 中。

Given that SELECT trunc(SYSDATE) FROM DUAL;鉴于SELECT trunc(SYSDATE) FROM DUAL; returns 02/06/2020返回02/06/2020

These work proper and return current year of 2020 -这些工作正常并返回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给出错误: ORA-30076: invalid extract field for extract source

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

Gives error: ORA-01722: invalid number给出错误: ORA-01722: invalid number

The same format is being passed with sysdate and hard coded date of 02/06/2019.使用 sysdate 和硬编码日期 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.我知道我可以select 2019 from dual但这不是这里的重点或用例。

You can't extract year from a string (which '02/06/2019' is).您无法从字符串中提取年份(即'02/06/2019' )。 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或者,如果您知道最后 4 位数字是有效年份,那么

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. sysdate默认是一个 DATE 字段。 A hard date like '02/06/2020' by default is considered a string.默认情况下,像 '02/06/2020' 这样的硬日期被视为字符串。

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;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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