简体   繁体   English

ORA-01843:不是有效的月份错误

[英]ORA-01843: not a valid month error

I have a column in Oracle DB which is varchar2 data type. 我在Oracle DB中有一列是varchar2数据类型。 Typical value stored in this column is like 06/16/2015 02:14:18 AM . 存储在此列中的典型值类似于06/16/2015 02:14:18 AM I am trying to get all records wherein this column is having records after 1st August 2015. 我正在尝试获取此列在2015年8月1日之后记录的所有记录。

select * 
from MYTABLE 
where to_date(substr(MYCOLUMN,1,10),'dd-mm-yyyy') > to_date('01-08-2015','dd-mm-yyyy');

But, I am getting ORA-01843 . 但是,我得到ORA-01843 Where am I doing wrong? 我在哪里做错了?

遵守VARCHAR中的格式

....where to_date(substr(MYCOLUMN,1,10),'mm/dd/yyyy')

I have a column in Oracle DB which is varchar2 data type. 我在Oracle DB中有一列是varchar2数据类型。 Typical value stored in this column is like 06/16/2015 02:14:18 AM. 该列中存储的典型值类似于06/16/2015 02:14:18 AM。

The first question is why do you store DATE as string ? 第一个问题是为什么将DATE存储为字符串 Using appropriate data type is one of the most important part of database design and performance . 使用适当的数据类型数据库设计性能最重要的部分之一。

Understand that DATE doesn't have the format you see, it is internally stored in 7 bytes which is Oracle's proprietary format. 请了解DATE没有您看到的格式 ,它在内部以Oracle专有格式7 bytes存储。 Storing date as a string to have a fixed format is not recommended. 不建议将日期存储为具有固定格式的字符串

I would suggest first fix the design so that you don't have to do this overhead activity while comparing dates . 我建议首先修改设计,这样您在比较日期时不必做这种开销的活动。 In the longer run it will help you. 从长远来看,它将为您提供帮助。

1. Add a new column as DATE data type. 1.添加一个新列作为DATE数据类型。

ALTER TABLE table_name 
   ADD new_column DATE;

2. Update the new column. 2.更新新列。

UPDATE table_name 
   SET new_column = TO_DATE(old_column, 'mm/dd/yyyy hh:mi:ss pm');

3. DROP the old column. 3.删除旧列。

ALTER TABLE table_name 
   DROP COLUMN old_column;

4. Rename the new column to old column name. 4.将新列重命名为旧列名。

ALTER TABLE table_name
  RENAME COLUMN old_name to new_name;

Now, you could compare dates easily: 现在,您可以轻松比较日期:

SELECT * FROM MYTABLE WHERE mycolumn > to_date('01-08-2015','dd-mm-yyyy');

This will also use any regular index on the date column. 这还将在日期列上使用任何常规索引

From performance point of view : 从性能角度来看

If you don't fix it now, you will keep facing performance issues. 如果您现在不解决它,您将继续面临性能问题。 Because the immediate fix of SUBSTR will not let you use any regular index , you need to create a function-based index . 因为SUBSTR的立即修复不允许您使用任何常规索引 ,所以您需要创建一个基于函数的索引

如果在表格中的所有值06/16/2015 02:14:18 AM ,那么你可以使用trunc(to_date(MYCOLUMN,'mm/dd/yyyy HH:mi:SS PM'),'dd')to_date(substr(MYCOLUMN,1,10),'dd-mm-yyyy')

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

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