oracle中的数据验证

Data validation In oracle

嗨 table 在 oracle 中像

ID          NAME      STARTDATE
1           A         2014-01-01
2           B         1900-01-01
3           C         29-02-2016

在此处执行 select 查询时,我想进行数据验证,检查年份在 1900-2099 月 1-12 之间和日期在 1-31 之间。 我尝试通过在查询中使用正则表达式来获得此结果

SELECT *
FROM   test
WHERE  REGEXP_LIKE (
          startdate,
          '^(19|20)\d\d[- /.](0[1-9]|1[012])[- /.](0[1-9]|[12][0-9]|3[01])$')

它工作正常,但对于 31-02-2016 的情况,它失败了,我尝试使用此 link 中给出的另一个表达式 Regex to validate date format dd/mm/yyyy

但在执行查询时显示未找到任何数据, 具有正则表达式的 oracle 是否有任何限制,因为相同的表达式在此 http://regexr.com/

上工作正常

我不知道执行此操作的函数,但您可以使用 to_date 创建一个验证特定格式的函数。例如:

create or replace function test_date_func(d varchar2,format varchar2) return varchar2
is
  v_date date;
begin
  select to_date(d,format) into v_date from dual;
  return '1';
  exception when others then return '0';
end;

现在您可以多次调用该函数,格式如下:

select dat, test_date_func(dat,'dd-mm-yyyy')||test_date_func(dat,'yyyy-mm-dd') valid 
from (select '2014-01-01' dat from dual union all
select '1900-01-01' from dual union all
select '29-02-2010' from dual union all
select '28-02-2010' from dual);

这会验证 'dd-mm-yyyy' 和 'yyyy-mm-dd' 以及 return:

格式的日期
DAT     VALID
2014-01-01   01
1900-01-01   01
29-02-2010   00
28-02-2010   10

如您所见,唯一的无效日期是 29-02-2010,在这两种情况下 return 0 00。现在,如果你想让这个更清楚,你可以添加一个 case 条件来显示 Valid 或 Invalid 而不是 0s 和 1s:

select dat, case when regexp_like(valid,'1') then 'Valid' else 'Invalid' end from ( 
select dat, test_date_func(dat,'dd-mm-yyyy')||test_date_func(dat,'yyyy-mm-dd') valid 
from (select '2014-01-01' dat from dual union all
select '1900-01-01' from dual union all
select '29-02-2010' from dual union all
select '28-02-2010' from dual));