【问题标题】:PL/SQL check date is validPL/SQL 检查日期是否有效
【发布时间】:2013-01-09 13:44:53
【问题描述】:

如果我在 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.

【问题讨论】:

  • '2902' 是有效日期吗?

标签: oracle validation date plsql


【解决方案1】:

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

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

【讨论】:

  • 可能值得注意的是to_date(p_val, 'ddmm') 默认为当前年份;这当然没关系,除非p_val 是2902,今年无效但去年有效。 OP 需要决定如何处理这种情况。
  • 这更像是对 OP 的观察,因为只有他们才能知道上下文 - 但例如如果他们希望2902 始终有效,他们可以使用固定年份,如果它是一个移动窗口,那么它可能是一个问题。只是他们需要注意的事情,而不是对您的回答的批评。
【解决方案2】:

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;

【讨论】:

  • 查看@NicholasKrasnov 的答案以获得更好的版本!
猜你喜欢
  • 2017-02-28
  • 2012-03-15
  • 1970-01-01
  • 2020-01-24
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-06-15
相关资源
最近更新 更多