有一列显示事务的一些语句。
例:'date-05-03-2020-Tran-100002345-W.44321-CR-9999eu843'
我只从声明中提取了日期。在某些情况下,有一个无效的日期,如date-05-032-2020 (月中有三个数字,而不是两个数字)
因此,当我执行查询时,我得到了一个错误,因为在从前面的语句中提取varchar之后,我使用TO_DATE函数来转换varchar。
因此,我需要的是像excel工作表中的IfError这样的函数,但是在oracle中。
例:如果DATE_x无效,那么用DATE_x2替换它
with x as(
select TO_DATE('01/20/2021','DD-MM-YYYY') DATE_x,
TO_DATE('01/02/2021','DD-MM-YYYY') DATE_x2
from dual
)
select
DATE_x2
from x;请指教
发布于 2021-08-01 08:16:31
在default... on conversion error的to_date:https://docs.oracle.com/en/database/oracle/oracle-database/12.2/sqlrf/TO_DATE.html#GUID-D226FA7C-F7AD-41A0-BB1D-BD8EF9440118中有一个参数
所以您可以编写TO_DATE('01/20/2021' default '01-01-2020' on conversion error, 'DD-MM-YYYY')或TO_DATE('01/20/2021' default null on conversion error ,'DD-MM-YYYY')。
还有validate_conversion函数:https://docs.oracle.com/en/database/oracle/oracle-database/12.2/sqlrf/VALIDATE_CONVERSION.html#GUID-DC485EEB-CB6D-42EF-97AA-4487884CB2CD
发布于 2021-08-01 06:46:23
一种选择是使用regexp_like检查日期格式。例如,你贴出的是'dd-mm-yyyy',意思是2位数字-2位数字-4位数字。当然,[43-85-0123]“匹配”这样的格式,但并不代表有效的日期。不管怎样,看看能不能帮上忙。在我的示例中,我用今天的日期替换无效的日期值。阅读代码中的注释。
SQL> with test (col) as
2 -- sample data; the 2nd row is invalid
3 (select 'date-05-03-2020-Tran-100002345-W.44321-CR-9999eu843' from dual union all
4 select 'date-05-032-2020-Tran-100002345-W.44321-CR-9999eu843' from dual
5 ),
6 exdate as
7 -- extract "date" substrings (values between 1st and 4th "-" character)
8 (select col,
9 substr(col, instr(col, '-') + 1,
10 instr(col, '-', 1, 4) - instr(col, '-') - 1
11 ) datum
12 from test
13 )
14 select col,
15 case when regexp_like(datum, '[0-9]{2}-[0-9]{2}-[0-9]{4}') then
16 to_date(datum, 'dd-mm-yyyy')
17 else trunc(sysdate)
18 end as result
19 from exdate
20 /
COL RESULT
---------------------------------------------------- ----------
date-05-03-2020-Tran-100002345-W.44321-CR-9999eu843 05-03-2020
date-05-032-2020-Tran-100002345-W.44321-CR-9999eu843 01-08-2021
SQL>https://stackoverflow.com/questions/68608012
复制相似问题