簡體   English   中英

你能防止在 pgsql 的后觸發器中插入嗎?

[英]Can you prevent an insert in an after trigger in pgsql?

在 postgres 中,我在分區表上有一個插入后觸發器,用於檢查記錄是否唯一。 目前,如果記錄不是唯一的,觸發器會引發異常。 這不是我想要的,因為我只想忽略這種情況並表現得好像插入確實發生了。

是否可以將觸發器配置為靜默失敗? 周圍的事務不應失敗,但不應插入行。

我在分區表上有一個插入后觸發器,用於檢查記錄是否唯一。

您可以在insert語句中執行此操作,使用on conflict do nothing子句。 這比使用觸發器更簡單、更有效。

為此,您需要對要強制執行其唯一性的列(或列的元組)進行unique約束。 假設這是列id ,你會這樣做:

insert into mytable(id, ...)    -- enumerate the target columns here
values(id, ...)                 -- enumerate the values to insert here
on conflict(id) do nothing

請注意,沖突操作do nothing做實際上並不需要指定沖突目標,因此嚴格來說,您可以將其寫成on conflict do nothing 我發現指定沖突目標總是一個好主意,所以 scope 更好地定義。


如果由於某種原因,您不能在目標列上擁有唯一索引,那么另一種選擇是使用insert... select語法以及not exists條件:

insert into mytable(id, ...)
select id, ...
from (values(id, ...)) t(id, ...)
where not exists (select 1 from mytable t1 where t1.id = t.id)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM