Using PostgreSQL. What I have is: 3 tables
1.Customer2c with columns: CustomerID,PersonID,Number_Of_Items`.
2.SalesOrderHeader2c with columns: SalesOrderID,CustomerID.
SalesOrderDetail2cwith columns:SalesOrderDetailID,SalesOrderID,OrderQty
I want to create a trigger function, that will trigger whenever someone uses
INSERT INTO 'SalesOrderDetail2c' table
and that is going to get the OrderQty that was inserted and update the correspondent Number_Of_Items field with it.
My trigger is working, but the problem is that whenever I insert a new value to the SalesOrderDetail2c, the function gets the OrderQty value and updates all the rows of Number_Of_Items with it, instead of updating just the correspondent one.
Any help appreciated. What I have so far is this (It may be copletely wrong, dont judge please!):
CREATE OR REPLACE FUNCTION FunctionTrigger2c() RETURNS TRIGGER AS
$BODY$
BEGIN
UPDATE Customer2c
SET Number_Of_Items =
(SELECT OrderQty
FROM SalesOrderDetail2c
INNER JOIN SalesOrderHeader2c ON (SalesOrderDetail2c.SalesOrderID = SalesOrderHeader2c.SalesOrderID)
INNER JOIN Customer2c ON (SalesOrderHeader2c.CustomerID = Customer2c.CustomerID)
ORDER BY SalesOrderDetailID DESC LIMIT 1
)
FROM SalesOrderHeader2c
WHERE SalesOrderHeader2c.CustomerID = Customer2c.CustomerID
;
RETURN NEW;
END;
$BODY$
language plpgsql;
CREATE TRIGGER Trigger2c
AFTER INSERT ON SalesOrderDetail2c
FOR EACH ROW
EXECUTE PROCEDURE FunctionTrigger2c();
NEW(see: postgresql.org/docs/current/static/plpgsql-trigger.html) to get the value that was just inserted/updated.