---
title: "ORA-02436 date or system variable wrongly specified in check constraint"
author: "myharmony"
date: "2011-06-24T15:18:51Z"
tags: []
categories: ["数据库"]
slug: "ora-02436-date-or-system-variable-wrongly-specified-in-check-constraint"
draft: false
lastmod: "2011-06-24T15:20:45Z"
id: 1103790
url: "https://myharmony.iteye.com/blog/1103790"
---

在做培训的时候，遇到一个很奇怪的问题：在给一个table加上constraint 去验证当前时间不允许小于系统时间。
 
```java

  create table mytable（
   id number(4),
   mydate date
   );
  alter table mytable add constraint chk_date check (mydate >=sysdate); 

```
出现：**<span style="color:red">ORA-02436 date or system variable wrongly specified in check constraint</span>**。
 经过google和请教别人得到此问题的2个解决方法：
 1. 一般方法：使用Trigger去做验证。
 2. 使用Oracle Visual column去验证

方法1代码如下：

```java

 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去验证
  
```java
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
  
```java
ALTER TABLE mytable ADD (mydate_in_past_ind AS (CAST (fun_check_date(mydate) as varchar2(1))));
```

  Step3: 添加constraint
  
```java
ALTER TABLE mytable ADD CONSTRAINT myck1 CHECK (mydate_in_past_ind = 'Y')
```

这样就可以解决在约束条件中的对sysdate的比较。