简体   繁体   English

To_char和To_date

[英]To_char and To_date

I'm struggling with one report contain a varchar2 column as a date in MON-YY format 我正在努力处理一个包含varchar2列作为MON-YY格式的日期的报告

what I wanna do is convert the value of that column into date so I can do some process on it such as filtering with > or < or even between and set two dates 我想做的就是将该列的值转换为日期,以便可以对其进行一些处理,例如使用>或<甚至在之间进行过滤并设置两个日期

My column name: BAL.PERIOD_NAME below is the condition cussing error ORA-01843: not a valid month 我的栏名称:BAL.PERIOD_NAME下面是条件查询错误ORA-01843:无效的月份

AND TO_DATE(BAL.PERIOD_NAME,'MON-YY')  > TO_DATE('FEB-18','MON-YY')

thanks in advance 提前致谢

Make sure you are using the correct format mask for the date you are converting. 确保在转换日期使用正确的格式掩码。

Works: 作品:

select  TO_DATE('feb-18','MON-YY') from dual

Throws "not a valid month" error: 抛出“无效月份”错误:

select  TO_DATE('02-18','MON-YY') from dual

You can use a recursive CTE to check you table for invalif month names. 您可以使用递归CTE检查表中的无用月份名称。

WITH cte(month)
AS
(
SELECT 1 month
       FROM dual
UNION ALL
SELECT month + 1 month
       FROM cte
       WHERE month + 1 <= 12
)
SELECT *
       FROM bal
       WHERE substr(period_name, 1, 3) NOT IN (SELECT to_char(to_date(month, 'MM'), 'MON')
                                                      FROM cte);

Storing date values as strings like 'FEB-18' is really a design flaw. 将日期值存储为'FEB-18''FEB-18'字符串确实是设计缺陷。 You should consider a migration to DATE (or TIMESTAMP ) data type. 您应该考虑迁移到DATE (或TIMESTAMP )数据类型。

  • Did you never heard about the Year-2000-Problem ? 您是否从未听说过2000年问题 Well, I assume when everybody in IT world was talking about the Y2K problem many present software developers were still kids. 好吧,我想当IT世界中的每个人都在谈论Y2K问题时,许多当前的软件开发人员还是小孩。
  • The string can be malformed in any way. 该字符串可以任何形式变形。
  • Even if the string has correct format you may face problem with language settings. 即使字符串格式正确,您也可能会遇到语言设置问题。

Anyway, perhaps it is only a language issue. 无论如何,也许这仅仅是一个语言问题。 Try this one 试试这个

WHERE TO_DATE(BAL.PERIOD_NAME,'MON-RR', 'NLS_DATE_LANGUAGE = American') > DATE '2018-02-01'

In case you are running Oracle 12.2 or later you can use function VALIDATE_CONVERSION : 如果您运行的是Oracle 12.2或更高版本,则可以使用VALIDATE_CONVERSION函数:

WHERE VALIDATE_CONVERSION(BAL.PERIOD_NAME, 'MON-RR', 'NLS_DATE_LANGUAGE = American') = 1

If you don't have Oracle 12.2 yet then write your own function, for example like this: 如果您还没有Oracle 12.2,请编写自己的函数,例如:

CREATE OR REPLACE FUNCTION CONVERT_TO_DATE(str in VARCAHR2) RETURN DATE IS
BEGIN
   RETURN TO_DATE(str, 'MON-RR', 'NLS_DATE_LANGUAGE = American');
EXCEPTION
   WHEN OTHERS THEN
      RETURN NULL;  
END CONVERT_TO_DATE;

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

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