[英]Can I manually trigger before insert function for already inserted records in Postgres?
I am using PostgreSQL 14.5我正在使用 PostgreSQL 14.5
I have a beneficiaries
table where people are registered and I have BEFORE INSERT
trigger function that generates a unique ID
based on their location (if Paris - PAR-001, if London - LON-004, etc) and it works.我有一个
beneficiaries
表,人们在其中注册,我有BEFORE INSERT
触发器 function,它根据他们的位置生成一个唯一的ID
(如果巴黎 - PAR-001,如果伦敦 - LON-004 等)并且它有效。
But the problem is, lots of records are inserted before writing this function, and since the function is triggered BEFORE INSERT
I can't have the ID
s for them.但问题是,在写入这个 function 之前插入了很多记录,并且由于 function
BEFORE INSERT
之前被触发,所以我无法获得它们的ID
。
I have seen the documentation and didn't find how to trigger the function for previous records我看过文档,没有找到如何触发 function 以前的记录
Can I manually trigger this function for all records once or any other solution?我可以为所有记录手动触发此 function 一次或任何其他解决方案吗?
Add an additional trigger like this:像这样添加一个额外的触发器:
CREATE TRIGGER temp BEFORE UPDATE ON tab
FOR EACH ROW WHEN (OLD.id IS NULL)
EXECUTE FUNCTION your_trigger_func();
The trigger function is the one you use in your BEFORE INSERT
trigger.触发器 function 是您在
BEFORE INSERT
触发器中使用的触发器。 Then update all these rows:然后更新所有这些行:
UPDATE tab SET id = id WHERE id IS NULL;
You can drop the trigger when you are done.完成后可以放下触发器。
You can perform the update in batches and run VACUUM
on the table in between, to avoid bloat by a single massive update.您可以分批执行更新并在中间的表上运行
VACUUM
,以避免因单个大规模更新而膨胀。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.