检查不在两个日期之间的sql

问题描述 投票:0回答:1

我正在尝试验证数据库不能存储日期范围内的信息。

CREATE TABLE works(
    nro_employee varchar2(10),
    job_name varchar2(100),
    date_incorporation date NOT NULL,
    low_date date,
    CONSTRAINT PK_work PRIMARY KEY (nro_employee, job_name),
    CONSTRAINT FK_work1 FOREIGN KEY (nro_employee) REFERENCES employee(nro_employee),
    CONSTRAINT FK_work2 FOREIGN KEY (job_name) REFERENCES installation(job_name)
);

对于此示例,如果我有引入的实例

1, executive, 01-mar-2010, 01-mar-2019 

我不能在该范围内拥有另一个实例,即“您一次只能在一个位置工作”(对于nro_employee = 1),最高日期和最低日期小于2010年3月1日或大于2019年3月1日。

发生在我身上的唯一方法是检查,但是为此我需要访问表中存储的数据以能够检查值,但我没有找到替代方法

oracle ddl
1个回答
1
投票

我认为您可以使用trigger如下实现:

我假设date_incorporation是开始日期,low_date是结束日期。因此,使用start_dateend_date作为列名。

Create or replace trigger works_trg_01
Before insert or update on works
For each row
Declare
Cnt number;
Begin
Select count(1) into cnt
from works 
where :new.nro_employee =  nro_employee
And case when :new.start_date < start_date and :new.end_date < start_date then 1
When :new.start_date > end_date then 1
Else 0 end = 0;

If cnt <> 0 then
Raise_application_error('-20001', 'employee can not work in overlapping dates');
End if;

End;
/

db<>fiddle demo

请根据以上触发器的要求更改逻辑。这只是向您显示如何完成此工作。

干杯!

© www.soinside.com 2019 - 2024. All rights reserved.