Database Administrators Asked by PGerrits on September 25, 2020
Hello and thanks for taking the time in advance to look at my question. This is my first try at using triggers and functions in PostgreSQL (using DBeaver) and I appreciate your feedback.
I’d like to update a column (village_id) every time a new row is entered or updated with the primary key value of a different table (which is not connected as a foreign key directly). See below for an outline of my tables and trigger + function.
Unfortunately, after using the code below I received an error each time I was entering a new row with information. I used an UPDATE statement, but I also considered using an insert into statement, but wasn’t sure what is more preferable. Thank you in advance.
CREATE TABLE register_table
(
register_id integer CONSTRAINT register_id_pk PRIMARY KEY,
village_id integer NOT NULL
);
CREATE TABLE er_table
(
er_id integer CONSTRAINT er_id_pk PRIMARY KEY,
register_id integer NOT NULL,
village_id integer NOT NULL
);
CREATE OR REPLACE FUNCTION update_village_id_column()
RETURNS trigger AS
$BODY$
BEGIN
UPDATE schema_example.er_table
SET village_id = register_table.village_id
FROM schema_example.register_table
WHERE (schema_example.register_id = new.register_id);
RETURN new;
END;
$BODY$
LANGUAGE plpgsql VOLATILE
COST 100;
CREATE TRIGGER update_village_id
AFTER INSERT OR UPDATE
ON schema_example.er_table
FOR EACH ROW
EXECUTE PROCEDURE update_village_id_column();
EDIT: removed recursive part from trigger
CREATE TRIGGER update_village_id
AFTER INSERT
ON schema_example.er_table
FOR EACH ROW
EXECUTE PROCEDURE update_village_id_column();
0 Asked on January 10, 2021
1 Asked on January 10, 2021 by hadrian-blackwater
1 Asked on January 9, 2021 by francesco-mantovani
2 Asked on January 9, 2021 by mark-mcwiggins
0 Asked on January 8, 2021 by jayakusumah
1 Asked on January 8, 2021
1 Asked on January 8, 2021 by pg2286
1 Asked on January 7, 2021 by conanthegerbil
0 Asked on January 6, 2021 by vrace
1 Asked on January 5, 2021 by kulstad
2 Asked on January 4, 2021 by stuart-j-cuthbertson
1 Asked on January 4, 2021 by jonggu
1 Asked on January 4, 2021 by spedo-de-la-rossa
full text search performance postgresql postgresql performance
1 Asked on January 3, 2021 by slim
1 Asked on January 1, 2021 by user2578332
1 Asked on January 1, 2021 by manvith
1 Asked on January 1, 2021 by racer-sql
1 Asked on December 31, 2020 by programmer
Get help from others!
Recent Answers
© 2022 AnswerBun.com. All rights reserved. Sites we Love: PCI Database, MenuIva, UKBizDB, Menu Kuliner, Sharing RPP