I have following function and trigger-
x
CREATE OR REPLACE FUNCTION function_copyX() RETURNS trigger AS
$BODY$
BEGIN
WITH
updates (id) AS (
UPDATE tbl_history
SET price=0
FROM tbl
WHERE tbl.id = tbl_history.id
AND tbl_history.price=1
RETURNING tbl_history.id
)
INSERT INTO tbl_history
SELECT id,1 FROM tbl;
RETURN new;
END;
$BODY$
language plpgsql;
create TRIGGER T_X
AFTER INSERT ON TBL
FOR EACH ROW
execute procedure function_copyX();
So, whenever I am inserting any record in TBL, I expect inserts/updates in the TBL_HISTORY but this does not work in trigger function. But if I execute this ‘WITH code’ separately it works. What could be the issue? please help.
Thanks
Advertisement
Answer
Below modification worked!
CREATE OR REPLACE FUNCTION function_copyX() RETURNS trigger AS
$BODY$
BEGIN
WITH
updates (id) AS (
UPDATE tbl_history
SET price=0 WHERE id =NEW.id AND price=1
RETURNING id
)
INSERT INTO tbl_history (id,price) values (NEW.id,1);
RETURN new;
END;
$BODY$
language plpgsql;
create TRIGGER T_X
AFTER INSERT ON TBL
FOR EACH ROW
execute procedure function_copyX();