【发布时间】:2017-08-03 09:39:44
【问题描述】:
比较日期与 sysdate 时出现以下错误:ORA-01850 : Hours must be between 0 and 23.
这是我的查询:
with cr as
(select '1-2' heures from dual)
select mydate, to_date(mydate, 'yyyymmddhh24mi')
from (select to_char(extract(year from sysdate), 'fm0009') ||
to_char(extract(month from sysdate), 'fm09') ||
to_char(extract(day from sysdate), 'fm09') ||
to_char(h2.heure, 'fm09') || '45' mydate
from (select to_number(h.intervalle_debut + i.l) heure
from (select to_number(regexp_substr(cr.heures,
'[^-]+',
1,
1)) intervalle_debut,
to_number(regexp_substr(cr.heures,
'[^-]+',
1,
2)) intervalle_fin
from cr) h,
(select level - 1 l from dual connect by level <= 24) i
where h.intervalle_fin - h.intervalle_debut >= i.l) h2)
where to_date(mydate, 'yyyymmddhh24mi') > sysdate;
小解释:
子查询“h2”返回这两行:
heure
------
1
2
它对应于“cr”子查询中给出的范围 1-2。 h2 使用返回的小时数创建与今天相对应的日期。它还返回这两行:
mydate
-------
201708030145
201708030245
日期看起来不错。小时是 1 和 2(这是正确的!)。
执行不带 where 子句的完整查询会返回这两个日期:
TO_DATE(MYDATE,'YYYYMMDDHH24MI
------------------------------
03/08/2017 01:45:00
03/08/2017 02:45:00
这仍然是正确的。 但是,当添加 where 子句“to_date(mydate, 'yyyymmddhh24mi') > sysdate”时,我得到 ORA-01850。
怎么了?
【问题讨论】:
-
为什么要将日期存储在
varchar列中? -
将
sysdate转换为字符值的复杂方法可以简化为to_char(sysdate, 'yyyymmddhh42')||'45' -
代替
to_char(extract(year from sysdate), 'fm0009') || to_char(extract(month from sysdate), 'fm09') || to_char(extract(day from sysdate), 'fm09') || to_char(h2.heure, 'fm09') || '45' mydate,你可以更简单的TO_CHAR(TRUNC(sysdate) + h2.heure/24 + 45/24/60, 'yyyymmddhh24mi') -
查询不是真实的。我写了一个无需创建任何表即可重现问题的方法。当然可以简化,但这不是我的问题。问题是:“为什么 Oracle 在比较两个日期时会抛出错误?”。