CURRENT_DATE Oracle

时间:2019-06-16 03:06:14

标签: oracle sqlplus

我很难添加一个新的出生日期列,其检查规则年龄在18至65岁之间。 我在Oracle上使用sqplus 总是收到错误消息ORA00920 请需要您的帮助

ALTER TABLE Vendeur ADD (dateNaissance DATE, 
            dateDebutProjet DATE NOT NULL,  
            DateFinProjet DATE NOT NULL,
            CONSTRAINT chk_date_Birth CHECK ((TRUNC(CURRENT_DATE)-dateNaissance) 
            BETWEEN 18 AND 65),
            CONSTRAINT chk_date_Projet CHECK (DateFinProjet > dateDebutProjet));

2 个答案:

答案 0 :(得分:1)

如果有帮助,则解决方案无需触发(因为那时我们还没有学习下摆):

ALTER TABLE Vendeur ADD (dateNaissance DATE, debutProjet DATE DEFAULT '01/01/1000' NOT NULL, finProjet DATE DEFAULT '02/01/1000' NOT NULL, dateDuJour Date DEFAULT CURRENT_DATE, CONSTRAINT chk_date_Projet CHECK (finProjet > debutProjet), CONSTRAINT chk_date_Birth CHECK ((dateDuJour - dateNaissance)\365 BETWEEN 18 AND 65) );

答案 1 :(得分:0)

检查约束cannot call non-deterministic functions like CURRENT_DATE。检查约束应该总是正确的,如果检查约束过期就会发生奇怪的事情。

以下示例代码显示了您可能在检查约束中尝试使用CURRENT_DATE时遇到的错误之一:

SQL> create table test1(a date);

Table created.

SQL> alter table test1 add constraint test1_ck1 check(a > date '2000-01-01');

Table altered.

SQL> alter table test1 add constraint test1_ck2 check(a > current_date);
alter table test1 add constraint test1_ck2 check(a > current_date)
                                                     *
ERROR at line 1:
ORA-02436: date or system variable wrongly specified in CHECK constraint

创建触发器来解决此问题:

create or replace trigger test1_date_gt_today
before update or insert of a on test1
for each row
begin
    if :new.a is null or :new.a < current_date then
        raise_application_error(-20000, 'The date cannot be earlier than today.');
    end if;
end;
/

下面是一个INSERT工作且一个不满足触发器条件的示例:

SQL> insert into test1 values(sysdate + 1);

1 row created.

SQL> insert into test1 values(sysdate - 1);
insert into test1 values(sysdate - 1)
            *
ERROR at line 1:
ORA-20000: The date cannot be earlier than today.
ORA-06512: at "JHELLER.TEST1_DATE_GT_TODAY", line 3
ORA-04088: error during execution of trigger 'JHELLER.TEST1_DATE_GT_TODAY'