oracle 使用触发器检查员工从当前日期起是否超过18岁

fdbelqdn  于 2023-04-29  发布在  Oracle
关注(0)|答案(1)|浏览(174)

我想确保新员工的年龄超过18岁,所以我想这样做的方法是使用一个触发器,从当前日期中减去员工的出生日期。
这是我的table

CREATE TABLE STAFF (
Staff_ID NUMBER(5),
First_Name VARCHAR2(25) NOT NULL,
Last_Name VARCHAR2(25),
Date_Of_Birth DATE NOT NULL,
Gender VARCHAR2(25),
Email VARCHAR2(25),
Telephone NUMBER(15),
Department VARCHAR2(25),
Staff_Type VARCHAR2(25),
Occupation VARCHAR2(25),
Hire_Date DATE,
Salary NUMBER (10)
);

这是我的插入声明;

INSERT INTO STAFF VALUES (1,'Ukeme', 'Mfon', TO_DATE('1980-12-2', 'yyyy-mm-dd'), 'Male', 'mfonclals@gmail.com',7826768732, 'Medical Team','Full-time','Nurse', TO_DATE('2023-02-12', 'yyyy-mm-dd'), 40000, 1);

这是我的触发器

create or replace trigger dob_check
before insert on Staff
for each row
declare
minimum_age number := 18;
begin
if extract(year from (sysdate - :old.Date_Of_Birth) year to month) < minimum_age
then
raise_application_error (-20000, 'Minimum age is '||minimum_age);
end if;
end;
/
c3frrgcw

c3frrgcw1#

在将行插入staff表之前检查age时,这里没有:old值,只有:new。这就是为什么你的扳机什么也没做。
简化:

SQL> create table staff (staff_id number, first_name varchar2(10), date_of_birth date);

Table created.

参见第7行,其中引用了:new.date_of_birth

SQL> create or replace trigger dob_check
  2    before insert on staff
  3    for each row
  4  declare
  5    minimum_age number := 18;
  6  begin
  7    if extract(year from (sysdate - :new.date_of_birth) year to month) < minimum_age then
  8       raise_application_error(-20000, 'Minimum age is ' || minimum_age);
  9    end if;
 10
 11    if :new.date_of_birth > sysdate then
 12       raise_application_error(-20001, 'Person can not be born in the future');
 13    end if;
 14  end;
 15  /

Trigger created.

测试:

SQL> insert into staff(staff_id, first_name, date_of_birth) values
  2    (1, 'Little', date '2014-03-28');
insert into staff(staff_id, first_name, date_of_birth) values
            *
ERROR at line 1:
ORA-20000: Minimum age is 18
ORA-06512: at "SCOTT.DOB_CHECK", line 5
ORA-04088: error during execution of trigger 'SCOTT.DOB_CHECK'

SQL> insert into staff(staff_id, first_name, date_of_birth) values
  2    (1, 'Foot', date '2004-03-28');

1 row created.

SQL>

相关问题