簡體   English   中英

檢查約束是否一個表(列)中的日期適合另一個表(列)中的另一個日期

[英]Check constraint whether the date from one table (column) fits to another date from another table (column)

讓我們假設我有兩個表如下。

create table contract(
 c_ID       number(1) primary key,
 c_name     varchar2(50) not null,
 start        date not null,
 end          date not null,
 d_ID       number(1) null,
 constraint fk_discount_ID
 foreign key(d_ID) references discount(d_ID)
);

create table discount(
 d_ID   number(1) primary key not null,
 d_amount decimal(4,2) not null,
 valid_from    date,
 valid_until   date
);

現在我想添加一個約束,檢查折扣在合同開始日期是否有效。 例如,合同於2015年5月1日開始,折扣僅在2015年4月30日有效,不能適用於上述合同。

我怎么能做這個約束?

遺憾的是,您無法使用約束執行此類復雜驗證。

雖然有一種方法可以使用物化視圖約束的組合(參見我的博客 ),但實際上我們通常不這樣做,因為它可能會產生不利的性能影響。

觸發器是一種選擇,但我會避免使用它們,因為它們很難正確,因此它們始終在多用戶系統中正常工作。

這留下了最常見的方法(根據我的經驗):為您的事務構建PL / SQL API,強制執行業務規則,以便應用程序調用API,而不是簡單地在contract插入行:

contract_api.create_contract 
   ( p_name => :name
   , p_start => :start
   , p_d_id => :d_id
   ...
   );

API在插入之前驗證業務規則,以便此調用可能失敗,例外情況如下:

ORA-20001: Discount not valid on contract start date

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM