首页 > 解决方案 > 如何创建检查 vlue 是否低于产品的 reorder_point 属性的更新语句

问题描述

利用 Outdoor Clubs & Product 数据库创建与产品表上的更新操作相关联的触发器“product_reorder_au”。触发器检查在更新 quantity_in_stock 属性期间,其值是否低于产品的 reorder_point 属性值。当这种情况发生时,触发器会自动在purchase_order 表中插入一个新的采购订单。新的采购订单将使用 product 表中产品的现有 supplier_no 属性值,quantity 属性值将与 product 表中产品的 reorder_qty 值相同。将触发源另存为脚本文件。

这是产品表的样子

在此处输入图像描述

到目前为止,这就是我所拥有的,但我通常对如何更新表并添加我猜测的 if then 语句感到困惑,以便仅在reorderpoint低于quantitiy_in_stock.

CREATE TRIGGER product_reorder_au
AFTER UPDATE OF product
for each row
begin
IF Quantity_In_Stock < Reorder_Point
THEN
    INSERT INTO Purchase_Order (Po_No, Po_Date, Product_Id, Quantity, Supplier_id)
    VALUES ( );
END IF;
END;

--测试脚本

update product
set quantity_in_stock = 5
where product_id = 10012;

附在其他表格中在此处输入图像描述

标签: oracleplsqltriggers

解决方案


你需要一个BEFORE触发器而不是AFTER触发器。见下文:

--餐桌准备

CREATE TABLE product_1 (
    quantity_in_stock   NUMBER,
    reorder_point       NUMBER,
    product_id          NUMBER,
    supplier_id         NUMBER,
    reorder_qty         NUMBER
);

    INSERT INTO product_1 VALUES (
        20,
        5,
        10010,
        500,
        25
    )

CREATE TABLE purchase_order (
    po_no         NUMBER,
    po_date       DATE,
    product_id    NUMBER,
    quantity      NUMBER,
    supplier_id   NUMBER
);

SQL> Select * from product_1;

QYT_IN_STOCK  REORDER_PNT PRDT_ID  SUPP_ID  RERDR_QTY
-----------   ----        -----    -----    -----
 4            5       10010 500 25

- 扳机

CREATE TRIGGER product_reorder_au BEFORE
    UPDATE ON product_1
    FOR EACH ROW
    WHEN ( new.quantity_in_stock < old.reorder_point )
BEGIN
    INSERT INTO purchase_order (
        po_no,
        po_date,
        product_id,
        quantity,
        supplier_id
    ) VALUES (
        1, --Populate this coulmn by a sequence or by some logic
        SYSDATE,
        :old.product_id,
        :old.reorder_qty,
        :old.supplier_id
    );
END;

执行:

SQL> UPDATE product_1
     SET
        quantity_in_stock = 4
     WHERE product_id = 10010;

SQL> SELECT * FROM purchase_order;
PO_NO PO_DATE       PRODUCT_ID  QTY     SUPP_ID
----- -------       --------   ----      -------
1     25-10-18  10010       25       500

推荐阅读