两个表上的Oracle触发器

c3frrgcw  于 2022-12-18  发布在  Oracle
关注(0)|答案(1)|浏览(193)

我正尝试在两个表purchaseorderdetail和purchaseorderheader上创建BEFORE UPDATE触发器,如下所示。我希望在PurchaseOrderHeader表上实现此触发器,如果PurchaseOrderDetail表中的相应数据与PurchaseOrderHeader.SubTotal列的新值不一致,则禁止更新PurchaseOrderHeader.SubTotal列。

CREATE TABLE purchaseorderheader(
purchaseorderid NUMBER(4),
revisionnumber NUMBER(2),
status NUMBER(1),
employeeid NUMBER(3),
vendorid NUMBER(4),
shipmethodid NUMBER(1),
orderdate TIMESTAMP,
shipdate TIMESTAMP,
subtotal FLOAT(10),
taxamt FLOAT(10),
freight FLOAT(10),
modifieddate TIMESTAMP,
PRIMARY KEY(purchaseorderid)
);

CREATE TABLE purchaseorderdetail(
purchaseorderid NUMBER(4),
purchaseorderdetailid NUMBER(4),
duedate TIMESTAMP,
orderqty NUMBER(6),
productid NUMBER(6),
unitprice FLOAT(10),
receivedqty FLOAT(10),
rejectedqty FLOAT(10),
modifieddate TIMESTAMP,
PRIMARY KEY(purchaseorderdetailid),
CONSTRAINT fk_orderid FOREIGN KEY (purchaseorderid) REFERENCES purchaseorderheader(purchaseorderid)
);

到目前为止我所想到的,有帮助吗?

CREATE OR REPLACE TRIGGER Header_Before_Subtotal BEFORE UPDATE  
ON purchaseorderheader 
FOR EACH ROW
BEGIN
    IF(:NEW.subtotal <> (SELECT unitprice*orderqty FROM purchaseorderdetail GROUP BY purchaseorderid)) THEN
        RAISE_APPLICATION_ERROR(-20001, 'Subtotal is not equal to unitprice * order quantity, check again.');
    END IF;
END;
hvvq6cgz

hvvq6cgz1#

单独计算总计(并引用主密钥),然后将该值与新的小计进行比较。

CREATE OR REPLACE TRIGGER Header_Before_Subtotal 
  BEFORE UPDATE  
  ON purchaseorderheader 
  FOR EACH ROW
DECLARE
  l_total number;
BEGIN
  SELECT d.unitprice * d.orderqty
    INTO l_total
    FROM purchaseorderdetail d
    WHERE d.purchaseorderid = :new.purchaseorderid;

  IF :NEW.subtotal <> l_total THEN
      RAISE_APPLICATION_ERROR(-20001, 'Subtotal is not equal to unitprice * order quantity, check again.');
  END IF;
END;
/

相关问题