简体   繁体   English

对于 Postgres 中已插入的记录,我可以在插入 function 之前手动触发吗?

[英]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.

相关问题 Postgres触发器仅在与上次插入的值不同时触发插入 - Postgres trigger only insert if different than last inserted value Postgres 触发器检查与现有记录的日期重叠 - Postgres trigger to check date overlap with already existing records 如何创建 Postgres 11 触发器 function 在插入或更新到表“a”时在表“b”中插入新行? - How can I create a Postgres 11 trigger function which inserts a new row in table 'b' upon insert or update to table 'a'? 我可以在sqlite中插入触发器之前更新New吗? - Can I update New in before insert trigger in sqlite? Postgres函数在两个表中插入多个记录 - Postgres Function to insert multiple records in two tables 如果 Postgres 中不存在记录,则插入值 - Insert values if records don't already exist in Postgres 如何在插入之前编写触发器以检查是否检查6000条以上记录的重复项 - How do i write a trigger before insert to check for duplicates checking 6000+ records 创建触发器以将记录从表插入到另一个。 在触发器中获取插入的值 - Create a trigger to insert records from a table to another one. Get inserted values in a trigger MySQL-在插入之前触发+如果数据已经存在+枚举列 - MySQL - trigger on before insert + if data already exists + enum column SQL插入,更新触发器-您可以更新插入的表吗? - SQL Insert, Update Trigger - Can you update the inserted table?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM