【发布时间】:2015-06-29 15:37:16
【问题描述】:
我对 SQL 还很陌生,但仍然编写了一些与我现在正在编写的查询非常相似的查询。无论出于何种原因,当我运行此查询时,都会返回“ORA-01821:日期格式无法识别”错误。我查了一下,并在 Stack 和其他地方四处寻找,我相信我的语法确实有意义,所以我很困惑为什么会出错。
我的查询基于月份中的哪一天运行。如果是第 1 天,则应在上个月的倒数第 15 天运行。如果是 16 号,则应该在当月的 1-15 号运行。
这是我每月第一天的代码:
select
case
when to_char(sysdate, 'yyyymmdd') = to_char(sysdate, 'yyyymm' || '01') then (do a lot of things)
.
.
.
end as FirstReportGroup
where *datetable* between between to_char(sysdate, 'yyyymm' || '16') and to_char(last_day(sysdate), 'yyyymmdd');
这是我在 16 号时的代码:
select
case
when to_char(sysdate, 'yyyymmdd') = to_char(sysdate, 'yyyymm' || '16') then (do a lot of things again)
.
.
.
end as SecondReportGroup
where *datetable* between to_char(sysdate, 'yyyymm' || '01') and to_char(sysdate, 'yyyymm' || '15')
这一定是某种我没有看到的日期格式语法错误。我真的很感谢这里的一些帮助,我期待着解决这个问题!如果您需要更多信息,请告诉我。
谢谢。
【问题讨论】:
-
sysdate 与 to_char 相比是什么数据类型? (日期到字符对吗?)您需要比较类似的数据类型才能开始。
-
哦,对了,愚蠢的错误。我刚刚将 sysdate 更改为:to_char(sysdate, 'yyyymmdd') 并解决了这个问题。不过,仍然无法看到日期格式的语法错误。
-
错误是由'01'和'16'引起的,这不是to_char指令的有效格式,所以,如果你想得到那一天,你应该使用
to_char(sysdate,'dd')。这将返回白天部分 -
将 01 移到字符之外,这不是日期...所以
to_char(sysdate, 'yyyymm') | '01'