oracle PL/SQL检查日期有效

hgb9j2n6  于 2023-06-22  发布在  Oracle
关注(0)|答案(3)|浏览(164)

如果我在PL/SQL中有一个日期格式DDMM,我想验证它。做这件事的正确方法是什么?
DD是日,MM是蛾。

For an example:
0208 - is a valid date
3209 - is not a valid date
0113 - is not a valid date.
9nvpjoqh

9nvpjoqh1#

你可以写一个这样的函数,例如:

create or replace function is_valid(p_val in varchar2)
return number
is
  not_a_valid_day   exception;
  not_a_valid_month exception;
  pragma exception_init(not_a_valid_day, -1847);
  pragma exception_init(not_a_valid_month, -1843);
  l_date date;
begin
  l_date := to_date(p_val, 'ddmm');
  return 1;
exception
  when not_a_valid_day or not_a_valid_month
  then return 0;
end;


SQL> with test_dates(dt) as(
  2    select '0208' from dual union all
  3    select '3209' from dual union all
  4    select '0113' from dual
  5  )
  6  select dt, is_valid(dt) as valid
  7    from test_dates
  8  /

DT        VALID
---- ----------
0208          1
3209          0
0113          0
dddzy1tm

dddzy1tm2#

--如果你有oracle 12 c

with test_dates(dt) as(
select '0208' from dual union all
select '3209' from dual union all
select '0113' from dual)

select dt, validate_conversion(dt as date, 'DDMM') as valid from test_dates

DT        VALID
---- ----------
0208          1
3209          0
0113          0
3qpi33ja

3qpi33ja3#

如果to_date的输入参数不是有效的日期,则会引发异常。所以你可以这样做:

declare
  x date;
begin
  x := to_date('3210', 'DDMM'); -- Will raise ORA-1847
  x := to_date('0113', 'DDMM'); -- Will raise ORA-1843
exception
  when others then 
    if sqlcode in (-1843, -1847) then
      dbms_output.put_line('Invalid Date!');
      null;
    else
      raise;
    end if;
end;

相关问题