I'm very new to Postgres and right now I am tasked to create a trigger that would fire after an insert. Basically, I would let a script do an insert, fire the trigger that would grab a field from another table based on a parameter from the Insert Statement then update the newly inserted record with the value from the other table.
- INSERT record to Table 1.
INSERT INTO "TableA" VALUES ('ABC-101', 'John Doe', '')
PersonID | Name | Address
------------------------------
ABC-101 John Doe
- After this insert, I would then fire the trigger that would grab the value from a field in TableB.
CREATE OR REPLACE FUNCTION fn_getaddress()
RETURNS trigger AS
$BODY$
DECLARE
PersonID TEXT;
BEGIN
PersonID := TG_ARGV[0];
UPDATE "TableA"
SET "Address" = (SELECT "Address"
FROM "TableB"
WHERE "PersonID" = PersonID);
RETURN null;
END;
$BODY$
LANGUAGE plpgsql VOLATILE
COST 100;
Here's my trigger:
CREATE TRIGGER tr_getaddress
AFTER INSERT
ON TableA
FOR EACH ROW
EXECUTE PROCEDURE fn_getaddress(personid);
So basically, I have a field in TableB (say Address) that I need to grab in order to complete the record in TableA. I am using an ID to reference which Address to take from TableB.