删除前的Postgres触发支票金额

时间:2019-07-11 11:31:21

标签: sql postgresql triggers

我正在尝试在触发器之前创建一个postgres,以检查在实际删除之前要删除的记录量。例如,删除不超过5条记录

1 个答案:

答案 0 :(得分:3)

您可以使用AFTER DELETE语句级触发器来实现。在触发函数内部,您可以计算受影响的行数,如果计数太高则抛出异常。该异常将强制回滚启动删除操作的事务。

create function prevent_delete()
  returns trigger
as
$BODY$ 
declare
  l_count integer;
begin 
  select count(*)
    into l_count
  from old_table;

  if l_count > 5 then 
    raise exception 'Too many rows would be deleted';
  end if; 
  return null;
end; 
$BODY$ 
LANGUAGE plpgsql;

然后创建触发器:

create trigger prevent_mass_delete 
   after delete on the_table
   referencing old table as old_table
   for each statement 
   execute procedure prevent_delete();