简体   繁体   English

在Oracle中以日期格式转换varchar字段数据

[英]convert varchar field data in date format in oracle

I have table test column has cretaed_dt and id.Both are varchar 2 type. 我有表测试列具有cretaed_dt和id。两者都是varchar 2类型。

desc test 描述测试

ID Varchar2(30)
Created_Dt varchar2(30)

select * from test 从测试中选择*

ID       created_dt
1        2014-07-22-12.23.49.832868
2        2014-08-04-19.40.11.787317
3        2014-06-15-19.40.11.787317

I need to pick the data between 21st July to 5th aug 2014.Idealy ID 1 and 2 need to pick. 我需要选择2014年7月21日至8月5日之间的数据。理想情况下,需要选择ID 1和2。

I am not able to do this because created date column is in varchar2. 我无法执行此操作,因为创建的日期列位于varchar2中。

Please assist. 请协助。

Although your data is stored as varchar2() , you can still use it. 尽管您的数据存储为varchar2() ,您仍然可以使用它。 Happily the strings are in the right format for comparison operations. 幸运的是,字符串采用正确的格式进行比较操作。 So: 所以:

where created_dte >= '2014-07-21' and created_dte < '2014-08-05'

You can convert the varchar2() to a date using to_date() . 可以使用to_date()varchar2()转换为日期。 However, just using the string as is allows Oracle to take advantage of an index on the column. 但是,仅按原样使用字符串将使Oracle可以利用列上的索引。

Although you can do what you want, you should store date/times in native date format in the database. 尽管您可以执行所需的操作,但是应该以本机日期格式将日期/时间存储在数据库中。 Oracle has a wealth of date-related functions that are then accessible. Oracle具有大量与日期相关的功能,然后可以访问这些功能。

Use this: 用这个:

with t as (
  select '1' id, '2014-07-22-12.23.49.832868' created_dt from dual union all
  select '2' id, '2014-08-04-19.40.11.787317' created_dt from dual union all
  select '3' id, '2014-06-15-19.40.11.787317' created_dt from dual 
)
select * 
  from t
 where to_timestamp(created_dt, 'yyyy-MM-dd-HH24.MI.SS.FF') between to_date('21 jul 2014', 'DD mon YYYY') and to_date('5 aug 2014', 'DD mon YYYY')

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

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