我有两个表(stock和productsLot),我需要一个触发器,该触发器通过对(来自productsLot)的手数求和来计算产品的总数量(在stock表中)。
我对触发器了解不多,但是我的问题类似于这个Calculate column value from another column in another table。这是我的情况。
CREATE TABLE Stock (productId INTEGER,totalQuantity INTEGER, price NUMERIC(30,2))
PRIMARY KEY (productId);
CREATE TABLE productsLot (productId INTEGER CONSTRAINT fk_stock_productsLot REFERENCES ON Stock(productId) , lotNumber VARCHAR, lotQuantity INTEGER, expirationDate DATE, PRIMARY KEY (productId, lotNumber));
CREATE TRIGGER update_quantity_stock
BEFORE INSERT ON stock SET NEW.totalQuantity =
(
SELECT sum(lotQuantity)
FROM productsLot
WHERE productId = NEW.productId
LIMIT 1
);
我收到此错误:
“ SET”处或附近的语法错误
答案 0 :(得分:0)
显然这是一个愚蠢的问题,但是我感谢尼克。 这是解决方案
CREATE OR REPLACE FUNCTION update_quantity_stock()
RETURNS trigger AS
$$
BEGIN
UPDATE stock SET totalQuantity = (select sum(lotQuantity)
FROM productsLot
WHERE productsLot.productId=stock.productId);
RETURN NEW;
END;
$$
LANGUAGE 'plpgsql';
-触发
CREATE TRIGGER update_quantity_stock_trigger
AFTER INSERT
ON productsLot
FOR EACH ROW
EXECUTE PROCEDURE update_quantity_stock();