I have two tables time_info and category. I want to update the temp_id
of time_info table whenever there is insertion of record or update of duration
column of time_info table.
Here is the schema
time_info
id
name
– textduration
– smallint NOT NULLtemp_id
– integer
category
id
temp_id
– integerduration
– smallint
The category table has some static records and those record’s temp_id
s need to be populated to time_info table based the condition time_info.duration
= category.duration
.
Example
category
id | temp_id | duration |
---|---|---|
001 | 123 | 30 |
002 | 234 | 60 |
003 | 345 | 90 |
So if a record is added in time_info like
id | name | duration | temp_id |
---|---|---|---|
101 | abc | 60 |
Then trigger function should run and update the row as following
id | name | duration | temp_id |
---|---|---|---|
101 | abc | 60 | 234 |
Now if someone changes the duration
in time_info to 90
then trigger function should run again and update the temp_id
to 345
.
WHat I tried
CREATE FUNCTION update_time_info_temp_id() RETURNS trigger AS $update_time_info_temp_id$
BEGIN
UPDATE NEW SET NEW.temp_id = subquery.temp_id
FROM (SELECT * from category) AS subquery
WHERE NEW.duration = subquery.duration;
RETURN NEW;
END;
$update_time_info_temp_id$ LANGUAGE plpgsql;
CREATE TRIGGER update_time_info_temp_id AFTER INSERT OR UPDATE ON time_info
FOR EACH ROW EXECUTE FUNCTION update_time_info_temp_id();
But it doesn’t seem to be working as expected
2
Answers
Check this out. This might fix the problem.
You probably want a BEFORE trigger. That lets you avoid the UPDATE and just modify NEW. You can also avoid any work when the duration hasn’t changed.
Note that your schema, as defined, has a couple of oddities. The
category
table’sid
seems redundant – the way you are using it suggests to meduration
is the actual primary key. In any case you definitely want to put a unique constraint on it. You normally wouldn’t copy thetemp_id
over too – just join from thetime_info
if you needed it.Oh, you’ve not said what should happen if the duration isn’t in the category table either – you’ll want to consider that.