简体   繁体   English

在sql命令中比较日期

[英]compare date in sql command

My database save the date as this format 5/29/2015 12:07:58.000000 AM . 我的数据库将日期保存为此格式5/29/2015 12:07:58.000000 AM And I got the date input from user as 5/29/2015 12:07:58 format. 我从用户输入的日期为5/29/2015 12:07:58格式。 Can I just compare the day/month/year instead of the whole line in sql command? 我可以只比较日/月/年,而不是sql命令中的整行吗? my database is oracle and format as TIMESTAMP. 我的数据库是oracle,格式为TIMESTAMP。 anyone have any idea how to do it? 任何人有任何想法怎么做?

My database save the date as this format 5/29/2015 12:07:58.000000 AM 我的数据库将日期保存为此格式5/29/2015 12:07:58.000000 AM

No. Date/Timestamps doesn't have any format . 否。 日期/时间戳没有任何格式 Oracle doesn't store the date/timestamps in the format you see. Oracle不会以您看到的格式存储日期/时间戳。 The format you see is only for display purpose. 您看到的格式仅用于显示目的。 Date is internally stored in 7 bytes which is Oracle's proprietary format . 日期在内部以Oracle专有格式7字节存储

Can I just compare the day/month/year instead of the whole line in sql command? 我可以只比较日/月/年,而不是sql命令中的整行吗?

Of course you could. 当然可以。 You could use TRUNC which truncates the time portion and leaves only date portion and data type remains as date. 您可以使用TRUNC截断时间部分,只保留日期部分,而数据类型保留为日期。

For example, 例如,

SQL> SELECT TRUNC(SYSTIMESTAMP) my_tmstmp FROM DUAL;

MY_TMSTMP
----------
2015-05-29

And I got the date input from user as 5/29/2015 12:07:58 format. 我从用户输入的日期为5/29/2015 12:07:58格式。

So, you get the user input in that format as a string . 因此,您将以这种格式将用户输入作为字符串 You need to first convert it into DATE using TO_DATE and then compare it. 您需要先使用TO_DATE 转换为DATE,然后进行比较。

For example, 例如,

WHERE TRUNC(dt_column) < TO_DATE('05/29/2015 12:07:58', 'MM/DD/YYYY HH24:MI:SS')

As I already said, if you want to ignore the time portion, then apply TRUNC . 正如我已经说过的,如果您想忽略时间部分,请应用TRUNC

However, applying TRUNC on the date column would suppress any regular index on that column. 但是,在日期上应用TRUNC会抑制该列上的任何常规索引 From performance point of view, better use a Date range condition . 从性能角度来看,最好使用Date范围条件

For example, 例如,

WHERE dt_column
BETWEEN 
        TO_DATE('05/29/2015 12:07:58', 'MM/DD/YYYY HH24:MI:SS')
AND     
        TO_DATE('05/29/2015 12:07:58', 'MM/DD/YYYY HH24:MI:SS') +1

I presume your record in databases and user input is both Timestamp. 我假设您在数据库中的记录和用户输入都是时间戳。 You can use TRUNC function to get the date of this value and use this to compare 您可以使用TRUNC函数获取此值的日期并使用它进行比较

declare v_tsdate DATE; v_txdate DATE; begin v_tsdate := TRUNC( CAST('5/29/2015 12:07:58.000000 AM' as DATE) ); v_txdate := TRUNC( CAST('5/29/2015 12:07:58' as DATE) ); --do the comparision and conditions you need with v_tsdate and v_txdate end;

The reason I convert to DATE format, because TRUNCT(Timestamp) theoretically is TRUNC(CAST(Timestamp AS DATE)) 之所以将其转换为DATE格式,是因为TRUNCT(Timestamp)理论上是TRUNC(CAST(Timestamp AS DATE))

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

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