我具有以下数据库结构:
table a (
id bigint primary key,
del timestamp
);
table b (
id bigint primary key,
a_id bigint references a(id) on delete cascade,
del timestamp
);
从表a
删除记录时,我想在当前时间设置del
标志,并将表b
中的相应标志设置为大写(但实际上不从数据库中删除记录)。
为此,我编写了一个触发器:
create or replace function a_delete_trigger()
returns trigger as
$$
begin
update a
set del = now()
where id = old.id; -- mark row
return null; -- return null, so that the record is not removed from database
end;
$$
language plpgsql;
create trigger a_delete
before delete
on a
for each row
execute procedure a_delete_trigger();
以及表b
的触发器:
create or replace function b_delete_trigger()
returns trigger as
$$
begin
update b
set del = now()
where id = old.id;
return null;
end;
$$
language plpgsql;
create trigger b_delete
before delete
on b
for each row
execute procedure b_delete_trigger();
当我从表a
(delete from a where id = ?
)中删除一条记录时,该记录被标记为已删除(标志del
包含时间戳记),但是表{{1}中的适当记录}没有标记(我猜想,级联删除不起作用,因为我从触发器b
返回null)
我该如何做,当我从表a_delete_trigger
中删除一条记录时,该记录标记为已删除,而a
中的相应记录也将标记为已删除?
答案 0 :(得分:0)
将删除项b添加到a_delete_trigger。
create or replace function a_delete_trigger()
returns trigger as
$$
begin
update a
set del = now()
where id = old.id; -- mark row
delete from b where a_id = a.id;
return null; -- return null, so that the record is not removed from database
end;
$$
language plpgsql;
create trigger a_delete
before delete
on a
for each row
execute procedure a_delete_trigger();