我在PL/pgSQL中为PostgreSQL编写了一个简单的触发器,但它并没有按照我的计划工作。我有两个问题:
有PostgreSQL函数的调试器吗?
我错在哪里?我需要检查这里。

CREATE OR REPLACE FUNCTION add_towh() RETURNS TRIGGER AS $$
DECLARE
    idsupp integer;
    idprod integer;
    whamount integer;
BEGIN

    SELECT PRODUCT INTO idsupp from SUPPLIERS where ID = NEW.SUPPLIER;
    SELECT ID INTO idprod from PRODUCTS where ID = idsupp;

    if (idprod > 0) then
        select amount into whamount from warehouses where product = idprod;
        update warehouses set amount = whamount * new.amount;
    else
        insert into warehouses (product,amount) values(idprod, new.amount);
    end if;
    RETURN NEW;
END;

$$ LANGUAGE plpgsql;

CREATE TRIGGER addtowh
AFTER INSERT ON orders FOR EACH ROW EXECUTE PROCEDURE add_towh ();

最佳答案

你的if (idprod > 0)最好写成if idprod is not null,但idprod > 0应该行得通。
我猜错误就在这里:

update warehouses set amount = whamount * new.amount;

您在该更新中没有WHERE子句,因此您将更改表中的每一行。你可以用这个代替:
select amount into whamount from warehouses where product = idprod;
update warehouses set amount = whamount * new.amount where product = idprod;

或者更好的方法是,只需一次更新:
update warehouses set amount = amount * new.amount where product = idprod;

如果您使用后者,那么您就不再需要在声明部分使用whamount
另外,我认为您可以用一个选择来替换前两个选择。这两个:
SELECT PRODUCT INTO idsupp from SUPPLIERS where ID = NEW.SUPPLIER;
SELECT ID INTO idprod from PRODUCTS where ID = idsupp;

可以用这个来代替:
select p.id into idprod
from products p
join suppliers s on p.id = s.product
where s.id = new.supplier;

然后你也不需要idsupp
就调试而言,我只知道使用printf进行raise notice风格的调试;例如:
raise notice 'idprod is "%"', idprod;

关于sql - Postgres中的触发器,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/8557313/

10-11 02:08