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);
出现:[b][color=red]ORA-02436 date or system variable wrongly specified in check constraint[/color][/b]。
经过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的时间是否被允许了 :lol:

方法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的比较。
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值