在销售商品时触发更改库存表的触发器

时间:2013-03-26 14:59:28

标签: sql postgresql triggers

当商品售出时,这是否正确触发器改变库存表的语法?

create trigger tr_stockquant
on tbl_ticket for insert, update, delete as $$
begin
update s set stockQty = s.stockQty - isnull(i.Qty,0) + isnull(d.Qty,0)
from tbl_stock s
left join inserted i
on s.itemID = i.itemID
left join deleted d on itemID = s.itemID
end;
$$ language plpgsql;

1 个答案:

答案 0 :(得分:0)

首先需要创建一个合适的函数,然后遵循CREATE TRIGGER语句的语法和语义。

首先你要创建一个函数:

CREATE FUNCTION alter_stock_table() RETURNS TRIGGER AS $$
    BEGIN
        IF tg_op = 'INSERT' THEN
            ...
        ELSIF tg_op = 'UPDATE' THEN
            ...
        ELSIF tg_op = 'DELETE' THEN
            ...
        ENDIF
$$ LANGUAGE PLPGSQL;

然后你可以创建一个触发器:

CREATE TRIGGER alter_stock_table_trigger
    AFTER INSERT, UPDATE, DELETE ON tbl_ticket
    FOR EACH ROW
    EXECUTE PROCEDURE alter_stock_table();

Google将帮助您找到有关如何定义功能的更多示例。 例如,this page给出了简要介绍。