Postgres触发器 - 使用2个不同的表

时间:2015-11-30 16:36:43

标签: postgresql triggers plpgsql

我有两张桌子:

Books - isbn (PK), title, qty-in-stock
Orderlist - ordernum (PK), isbn, quantity

我的目标是在订单列表中插入记录,然后,如果匹配isbns,则将数量添加到库存中

我的功能和触发器不正确 -

CREATE OR REPLACE FUNCTION books_upd() RETURNS trigger as $bookupd$
BEGIN 
--IF   THE ISBN MATCHES BETWEEN BOOKS AND ORDERLIST
-- ADD THE EXISTING QTY_IN_STOCK (BOOKS)  TO QUANTITY (ORDERLIST)
QTY_IN_STOCK:=QTY_IN_STOCK+QUANTITY;
--END IF
RETURN NEW;
$bookupd$ LANGUAGE plpgsql;

CREATE TRIGGER books_upd
BEFORE INSERT OR UPDATE on orderlist
FOR EACH ROW
EXECUTE PROCEDURE books_upd();

有人可以帮忙吗?

1 个答案:

答案 0 :(得分:1)

由于插入和更新的不同情况,触发器功能非常复杂。

当用户更新订单时,该功能应该:

    如果qty_in_stock相同或,则
  • 添加quantities新旧isbns之间的差异
  • 从一本书的quantity中减去旧qty_in_stock,并在quantity不同时将新qty_in_stock添加到另一本书的isbns

此外,如果isbn中不存在给定的books,则该功能应拒绝更改。

CREATE OR REPLACE FUNCTION books_upd() 
RETURNS trigger as $bookupd$
DECLARE
    v_quantity int;
BEGIN
    v_quantity = NEW.quantity;
    IF TG_OP = 'UPDATE' THEN
        IF OLD.isbn != NEW.isbn THEN
            UPDATE books
            SET qty_in_stock = qty_in_stock- OLD.quantity
            WHERE isbn = OLD.isbn;
        ELSE
            v_quantity = NEW.quantity- OLD.quantity;
        END IF;
    END IF;

    UPDATE books
    SET qty_in_stock = qty_in_stock+ v_quantity
    WHERE isbn = NEW.isbn;

    IF NOT FOUND THEN
        RAISE EXCEPTION 'Uknown isbn';
    END IF;
    RETURN NEW;
END;
$bookupd$ LANGUAGE plpgsql;

详细了解NEW, OLD and TG_OP

仅针对插入的触发器功能非常简单:

CREATE OR REPLACE FUNCTION books_upd() 
RETURNS trigger as $bookupd$
BEGIN
    UPDATE books
    SET qty_in_stock = qty_in_stock+ NEW.quantity
    WHERE isbn = NEW.isbn;

    RETURN NEW;
END;
$bookupd$ LANGUAGE plpgsql;