2016-06-20 25 views
0

我有一個簡單的問題,但我對SQL很陌生。 我有一個簡單的監獄&囚犯模型,我需要觸發器,這將提供我的日期不會重疊。SQL TRIGGER - 簡單囚犯模型中的重疊日期

表(句子的執行)具有3個屬性: 1. ID句子( 「ID_exec」) 2.從( 「來自」) 3.執行到( 「至」)

我需要確定囚犯的一句話不會與他的另一句話重疊。 例如 - 他將有句子(2011年8月1日 - 2031年8月1日),新句子不應與此日期重疊。

謝謝你的回答。

回答

0

我想你還需要在你的sentence表中的prisonerID

create table sentence 
(id number, 
    prisonerID number, 
    fromDate date, 
    toDate date); 

沒有它,很難確定你處理哪個囚犯的判決。 拒絕的標準是:

:NEW.toDate > fromDate AND 
:NEW.FromDate < toDate 

如果某些記錄由上述條件返回 - 插入應予駁回。標準來自於要求開始時間或結束時間不能在現有時間段內,並且他們不能包括這樣的時間段。打破這一部分 - 新的fromDate必須早於ToDate,而new toDate必須晚於fromDate。

create or replace trigger sentence_reject_existing 
    before insert 
    on sentence 
    for each row 
    declare 
    vCount NUMBER; 
    begin 
    select count(*) 
     into vCount 
    from sentence 
    where prisonerID = :NEW.prisonerID and 
      :NEW.Todate > fromDate and 
      :New.FromDate < toDate ; 

    if vCount > 0 then 
     raise_application_error(-20005,'Prisoner is already in prison'); 
    end if; 

    end;