PostgreSQL 触发器无例外地禁止操作
PostreSQL trigger disallow an action without exceptions
正在尝试解决大学作业的问题。 table 中的每一行都有一个日期字段,我需要禁止删除该字段小于 5 年的行。需要使用触发器,并且它不得引发异常。我该怎么做?我尝试过类似的方法,但它不起作用:
create or replace function no_change()
returns trigger as $no_change$
begin
if current_timestamp - old.date <= interval '5y' then
new = old;
end if;
return new;
end;
$no_change$ language plpgsql;
create trigger no_change after delete on wiz
for each row execute procedure no_change();
Row-level triggers fired BEFORE can return null to signal the trigger manager to skip the rest of the operation for this row (i.e., subsequent triggers are not fired, and the INSERT/UPDATE/DELETE does not occur for this row).
<...>
In the case of a before-trigger on DELETE, the returned value has no direct effect, but it has to be nonnull to allow the trigger action to proceed. Note that NEW is null in DELETE triggers, so returning that is usually not sensible. The usual idiom in DELETE triggers is to return OLD.
所以在日期小于 5 天的情况下 return NULL。
未测试,但应该可以。
create or replace function no_change()
returns trigger as $no_change$
begin
if current_timestamp - old.date <= interval '5y' then
RETURN NULL;
ELSE
RETURN OLD;
end if;
end;
$no_change$ language plpgsql;
create trigger no_change BEFORE delete on wiz
for each row execute procedure no_change();
正在尝试解决大学作业的问题。 table 中的每一行都有一个日期字段,我需要禁止删除该字段小于 5 年的行。需要使用触发器,并且它不得引发异常。我该怎么做?我尝试过类似的方法,但它不起作用:
create or replace function no_change()
returns trigger as $no_change$
begin
if current_timestamp - old.date <= interval '5y' then
new = old;
end if;
return new;
end;
$no_change$ language plpgsql;
create trigger no_change after delete on wiz
for each row execute procedure no_change();
Row-level triggers fired BEFORE can return null to signal the trigger manager to skip the rest of the operation for this row (i.e., subsequent triggers are not fired, and the INSERT/UPDATE/DELETE does not occur for this row).
<...>
In the case of a before-trigger on DELETE, the returned value has no direct effect, but it has to be nonnull to allow the trigger action to proceed. Note that NEW is null in DELETE triggers, so returning that is usually not sensible. The usual idiom in DELETE triggers is to return OLD.
所以在日期小于 5 天的情况下 return NULL。
未测试,但应该可以。
create or replace function no_change()
returns trigger as $no_change$
begin
if current_timestamp - old.date <= interval '5y' then
RETURN NULL;
ELSE
RETURN OLD;
end if;
end;
$no_change$ language plpgsql;
create trigger no_change BEFORE delete on wiz
for each row execute procedure no_change();