从Oracle SQL中的字符串日期检索年份

时间:2018-06-06 13:56:47

标签: sql oracle date

我有以下日期列:

EXPIRY_DAT 31-Oct-17 31-Oct-17 18-Nov-18 12:11:10 31-Dec-12 31-Oct-17 31-Oct-17 18-Nov-18 12:11:10 31-Dec-12 31-Oct-17 31-Oct-17 20-Jul-18 19:20:33 31-Oct-18 31-Oct-18 11-Aug-19 21:52:56 31-Dec-12 . . .

我想以YYYY的形式从这些系列中检索年份。 我已经尝试使用以下SQL代码行:

TO_DATE(TO_CHAR(EXPIRY_DAT, 'DD-MON-YY HH:MI:SS'), 'YYYY'

虽然它返回错误信息:

ORA-01830:日期格式图片在转换整个输入字符串之前结束

2 个答案:

答案 0 :(得分:2)

使用:

select extract(year from TO_DATE(SUBSTR(EXPIRY_DAT,1,9),'DD-Mon-YY')
from your_table

答案 1 :(得分:2)

如果您所有的日期都是您展示的格式之一,那么这就足够了:

-- test case
with dateTable(EXPIRY_DAT) as (
    select '31-Oct-17'            from dual union all
    select '31-Oct-17'            from dual union all
    select '18-Nov-18 12:11:10'   from dual union all
    select '31-Dec-12'            from dual union all
    select '31-Oct-17'            from dual union all
    select '31-Oct-17'            from dual union all
    select '18-Nov-18 12:11:10'   from dual union all
    select '31-Dec-12'            from dual union all
    select '31-Oct-17'            from dual union all
    select '31-Oct-17'            from dual union all
    select '20-Jul-18 19:20:33'   from dual union all
    select '31-Oct-18'            from dual union all
    select '31-Oct-18'            from dual union all
    select '11-Aug-19 21:52:56'   from dual union all
    select '31-Dec-12'            from dual
)
-- query
select to_char(to_date(substr(EXPIRY_DAT, 1, 9), 'dd-mon-yy'), 'yyyy')
from dateTable