0

我一直在努力寻找一种插入支票的方法,这样它就不会允许付款日期早于发票日期。基本上,我有两张表:发票和付款。所以我想要一个支票约束来输入发票表中购买日期之前的日期。Invoice 表中的 invoice_id 是付款表中的 FK。有什么帮助吗?

4

2 回答 2

3

A check constraint can only look at columns on the table it is defined on.

You'll need to use a TRIGGER to do this.

于 2012-04-05T06:08:37.180 回答
2

一种方法可能是在支付表中复制购买日期,在 invoice_id + 购买日期的组合上添加第二个唯一约束,然后修改 FK 约束以包含它。然后,您可以拥有行级约束。例如

CREATE TABLE invoices
( invoice_id    NUMBER NOT NULL
, purchase_date DATE NOT NULL
, CONSTRAINT invoice_pk PRIMARY KEY (invoice_id)
, CONSTRAINT invoice_uk UNIQUE (invoice_id, purchase_date)
);

CREATE TABLE payments
( payment_id    NUMBER NOT NULL
, invoice_id    NUMBER NOT NULL
, purchase_date DATE NOT NULL
, payment_date  DATE NOT NULL
, CONSTRAINT payment_pk PRIMARY KEY (payment_id)
, CONSTRAINT payment_invoice_fk
    FOREIGN KEY (invoice_id, purchase_date)
    REFERENCES invoices (invoice_id, purchase_date)
, CONSTRAINT payment_date_ck
    CHECK (payment_date >= purchase_date)
);

缺点:更新 invoices.purchase_date 变得有点棘手。

于 2012-04-05T07:14:46.440 回答