比较SQL命令日期 [英] compare date in sql command

查看:330
本文介绍了比较SQL命令日期的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的数据库保存日期为这种格式 2015年5月29日12:07:58.000000 AM 。而我从用户输入的日期为 2015年5月29日12时07分58秒格式。可我只是比较SQL命令的整条生产线的日/月/年呢?我的数据库是Oracle和格式TIMESTAMP。
任何人有任何想法怎么办呢?


解决方案

  

我的数据库日期保存为这种格式2015年5月29日12:07:58.000000 AM


没有。 日期/时间戳记没有任何的格式即可。 Oracle不存储在你看到的格式的日期/时间戳。您所看到的格式是仅适用于的显示的宗旨。 日期存储在内部7字节,这是Oracle专有的格式


  

我可以只比较了日/月/年,而不是在SQL命令全行的?


当然你可以研究。你可以使用 TRUNC 这截断时间部分,只保留日期部分和数据类型仍然是最新的。

例如,

  SQL> SELECT TRUNC(SYSTIMESTAMP)my_tmstmp FROM DUAL;MY_TMSTMP
----------
2015年5月29日


  

和我从用户输入的日期为2015年5月29日12时07分58秒的格式。


所以,你在该格式为字符串的用户输入。首先,您需要的转化入日采用 TO_DATE ,然后进行比较。

例如,

  WHERE TRUNC(dt_column)LT; TO_DATE('05 /二千零十五​​分之二十九12时07分58秒,MM / DD / YYYY HH24:MI:SS')

正如我已经说过,如果你想忽略时间部分,然后应用的 TRUNC

但是,在应用的 TRUNC 上的日期的将坐席preSS该列任何常规的首页即可。从性能上来看,最好使用一个的日期范围条件

例如,

 其中dt_column
之间
        TO_DATE('05 /二千零十五​​分之二十九12时07分58秒,MM / DD / YYYY HH24:MI:SS')

        TO_DATE('05 /二千零十五​​分之二十九12时07分58秒,MM / DD / YYYY HH24:MI:SS')+1

My database save the date as this format 5/29/2015 12:07:58.000000 AM. And I got the date input from user as 5/29/2015 12:07:58 format. Can I just compare the day/month/year instead of the whole line in sql command? my database is oracle and format as 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

No. Date/Timestamps doesn't have any format. Oracle doesn't store the date/timestamps in the format you see. The format you see is only for display purpose. Date is internally stored in 7 bytes which is Oracle's proprietary format.

Can I just compare the day/month/year instead of the whole line in sql command?

Of course you could. You could use TRUNC which truncates the time portion and leaves only date portion and data type remains as date.

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.

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.

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.

However, applying TRUNC on the date column would suppress any regular index on that column. From performance point of view, better use a Date range condition.

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

这篇关于比较SQL命令日期的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆