`
myharmony
  • 浏览: 106246 次
  • 性别: Icon_minigender_1
  • 来自: 中山市
社区版块
存档分类
最新评论

ORA-02436 date or system variable wrongly specified in check constraint

阅读更多
在做培训的时候,遇到一个很奇怪的问题:在给一个table加上constraint 去验证当前时间不允许小于系统时间。
  create table mytable(
   id number(4),
   mydate date
   );
  alter table mytable add constraint chk_date check (mydate >=sysdate); 
出现:ORA-02436 date or system variable wrongly specified in check constraint
经过google和请教别人得到此问题的2个解决方法:
1. 一般方法:使用Trigger去做验证。
2. 使用Oracle Visual column去验证

方法1代码如下:
 create trigger mytrigger 
 before insert or update on mytable
 for each row
 begin
   if inserting or updating(mydate) then
      if :new.mydate >=sysdate then
        raise_application_error(-20000,'mydate must be a date in the past.');
      end if;
   end if;
 end;

这样在做Insert和Update的时候就可以验证当前Insert的时间是否被允许了

方法2步骤如下(Oracle版本必须是11g或者以上):
Step1: 添加一个Function去验证
 
create or replace function fun_check_date(tmpDate date) 
  is 
  begin
    RETURN CASE WHEN empdate >= SYSDATE THEN 'N' ELSE 'Y' END;
  end fun_check_date;

  Step2: 添加visual column
 
ALTER TABLE mytable ADD (mydate_in_past_ind AS (CAST (fun_check_date(mydate) as varchar2(1))));

  Step3: 添加constraint
 
ALTER TABLE mytable ADD CONSTRAINT myck1 CHECK (mydate_in_past_ind = 'Y')

这样就可以解决在约束条件中的对sysdate的比较。



 
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics