简体   繁体   English

Oracle SQL 日期比较

[英]Oracle SQL date comparison

why if date1 is of type date with value: 31-DIC-99 00:00:00为什么如果 date1 是日期类型,其值为:31-DIC-99 00:00:00

this instruction is true这个指令是真的

to_char(date1) = to_char(TO_DATE('9999-12-31', 'yyyy-MM-dd'))

and this is false?这是假的吗?

date1 = TO_DATE('9999-12-31', 'yyyy-MM-dd')

Thanks谢谢

Dates in Oracle have time components -- even if you don't seem them when the values are printed out. Oracle 中的日期具有时间分量——即使在打印出这些值时您没有看到它们。 When you convert the value to a string with no format specified, then the time component is set to zero.当您将该值转换为未指定格式的字符串时,时间分量将设置为零。

I would recommend writing the logic as:我建议将逻辑编写为:

 trunc(date1) = date '9999-12-31'

Or, if you prefer:或者,如果您愿意:

date1 >= date '9999-12-31'

You are referring to the maximum date value, so there are no dates with larger values.您指的是最大日期值,因此没有较大值的日期。 . . . . but there are larger values on the same date with a time.但在同一日期有更大的值与时间。

I do not recommend converting dates to string, except for output purposes (or if needed for a very specific reason).我不建议将日期转换为字符串,除了 output 目的(或者如果出于非常特定的原因需要)。 Date/time functions are usually quite sufficient for operations on date/time values.日期/时间函数通常足以用于日期/时间值的操作。

Here, Your first condition is true because you are using the TO_CHAR both sides and it will convert both of the dates into the same string.在这里,您的第一个条件为真,因为您在双方都使用TO_CHAR ,它将两个日期转换为相同的字符串。 (string comparision) (字符串比较)

to_char(date1) = to_char(TO_DATE('9999-12-31', 'yyyy-MM-dd'))

Let's say NLS_DATE_FORAMT is dd.mon.rrrr then your comparison will be假设NLS_DATE_FORAMTdd.mon.rrrr那么你的比较将是

to_char(date1,'dd.mon.rrrr') = to_char(TO_DATE('9999-12-31', 'yyyy-MM-dd'),'dd.mon.rrrr')

The second condition is not true as both the sides are different - date1 may have time portion and right side expression do not have it.第二个条件不成立,因为双方不同 - date1 可能有时间部分,而右侧表达式没有。

date1 = TO_DATE('9999-12-31', 'yyyy-MM-dd')

date1 contains time part so one date will be the same as the second date if they are the same until seconds precision. date1 包含时间部分,因此如果它们在秒精度之前相同,则一个日期将与第二个日期相同。

You can use trunc to remove the time portion from date1:您可以使用 trunc 从 date1 中删除时间部分:

trunc(date1) = TO_DATE('9999-12-31', 'yyyy-MM-dd')

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

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