2017-09-02 48 views
0

之前的日期格式的画面结束,我有以下代码,我想看看,如果日期是不到一年以前:uisng to_date函数仍然得到转换整个输入字符串错误

select id 
from mytable 
where id= :p_id 
and (to_date(trunc(sysdate), 'yyyy-mm-dd') - to_date(datewhen, 'yyyy-mm-dd')) < 365; 

我不断收到错误:

ORA-01830: date format picture ends before converting entire input string

寻找与StackOverflow上同样的错误我看到的解决办法通常是使用我做的,所以我不能确定为什么这是发生to_date函数等问题。 datewhen字段的类型为Date

+0

你不&#39;吨需要使用to_date函数在 “TO_DATE(TRUNC(SYSDATE), 'YYYY-MM-DD')”,因为你已经alread使用trunc()。 – WellingtonD

+0

对已经是“日期”的值使用'to_date()'是毫无意义的。不要那样做。 –

回答

0

请勿使用to_date()与DATE数据类型的柱面。 to_date()将字符串转换为DATE数据类型的值。将DATE转换为DATE是没有意义的。在第一步datewhen DATE类型的列将通过使用默认日期格式(最可能不是'yyyy-mm-dd')隐式转换为字符数据类型,这是ORA-01830错误的罪魁祸首。

所以你的说法应该是这个样子:

select id from mytable where id = :p_id and (trunc(sysdate) - trunc(datewhen)) < 365;  

我计算而不是几天在几个月或几年的区别:

... where months_between(sysdate, datewhen) < 12 
0

您使用TO_DATE函数当值字符格式

语法

TO_DA的语法在甲骨文/ PLSQL TE功能是:

TO_DATE(string1 [, format_mask] [, nls_language]) 
1

如果您datewhen列是CHAR/VARCHAR格式化为yyyy-mm-dd那么你必须做datewhento_date转换,但不能在SYSDATE:这已经是一个日期和不需要转换。

内的365日内的日期进行筛选,把它比作SYSDATE - 365

select id 
from mytable 
where id = :p_id 
    and to_date(datewhen, 'yyyy-mm-dd') > sysdate - 365; 

但一年并不总是365天:在闰年是366天。为了得到一个一年前值总是正确的,从目前的日期减去一年的时间间隔:

select id 
from mytable 
where id = :p_id 
    and datewhen > sysdate - interval '1' year; 

一两件事:在Oracle DATE类型不只是一个日期;这是一个日期和时间。 SYSDATE返回当前日期时间。试试这个查询:

select to_char(sysdate, 'yyyy-mm-dd hh24:mi:ss') from dual; 

除非你在午夜时分运行它,否则你也会看到一个时间组件。

说出您的查询在2017年9月2日上午10点运行,并且您正在寻找去年的日期。您预计会得到2016年9月3日的日期,但您不会,因为上午10点SYSDATE是2016年9月3日的10:00:00。这比2016年9月3日(即2016年9月3日0:00:00)的明确日期更长,因此不包括'2016-09-03'的datewhen的记录。

要忽略Oracle DATE值的时间部分,请使用TRUNC。你最终的查询应该是这个样子:

select id 
from mytable 
where id = :p_id 
    and datewhen > trunc(sysdate) - interval '1' year; 
+0

你也可以使用'add_month {SYSDATE,-12)' –

+0

谢谢Wernfried,很好!我忘记了'add_months'。 –

相关问题