将 DELETE 级联到另一行 table
Cascade DELETE to row of another table
CREATE OR REPLACE FUNCTION removerCapitulo()
RETURNS trigger AS
$BODY$
declare counter int;
BEGIN
select count(*) into counter FROM capitulos where id_capitulo = NEW.id_livro;
if (counter >1)
THEN
DELETE FROM capitulos WHERE id_capitulo = NEW.id_livro;
END IF;
RETURN NEW;
END;
$BODY$
LANGUAGE plpgsql;
CREATE TRIGGER removerCapitulo_trigger
BEFORE DELETE
ON livros
FOR EACH ROW
EXECUTE PROCEDURE removerCapitulo();
DELETE FROM public.livros
WHERE id_livro = 30
当我尝试删除 ID = id_capitulo 的 "livro" 时,我想删除 "livro" 和 "capitulo",但是当删除 "livro" 它 returns 成功,但它不会删除 "livro" 或 "capitulo" ...我试着放一个计数器以防 [=] 中有超过 1 个 "capitulo" 23=] 的 id 等于我要求删除它时输入的 id delete
When i try to delete a "livro" with id = id_capitulo i want to delete the "livro" and the "capitulo"
你不需要触发器。相反,您可以使用 on delete cascade
选项的外键:
create table capitulos (
... -- other table columns
id_capitulo int
references livros(id_livro)
on delete cascade
);
至于你现有的代码:因为你有一个 delete
触发器,你需要使用伪 table old
而不是 new
(实际上是空的):
create or replace function remover_capitulo()
returns trigger as
$body$
begin
delete from capitulos where id_capitulo = old.id_livro;
return old;
end;
$body$
language plpgsql;
create trigger trg_remover_capitulo
before delete on livros
for each row
execute procedure remover_capitulo();
CREATE OR REPLACE FUNCTION removerCapitulo()
RETURNS trigger AS
$BODY$
declare counter int;
BEGIN
select count(*) into counter FROM capitulos where id_capitulo = NEW.id_livro;
if (counter >1)
THEN
DELETE FROM capitulos WHERE id_capitulo = NEW.id_livro;
END IF;
RETURN NEW;
END;
$BODY$
LANGUAGE plpgsql;
CREATE TRIGGER removerCapitulo_trigger
BEFORE DELETE
ON livros
FOR EACH ROW
EXECUTE PROCEDURE removerCapitulo();
DELETE FROM public.livros
WHERE id_livro = 30
当我尝试删除 ID = id_capitulo 的 "livro" 时,我想删除 "livro" 和 "capitulo",但是当删除 "livro" 它 returns 成功,但它不会删除 "livro" 或 "capitulo" ...我试着放一个计数器以防 [=] 中有超过 1 个 "capitulo" 23=] 的 id 等于我要求删除它时输入的 id delete
When i try to delete a "livro" with id = id_capitulo i want to delete the "livro" and the "capitulo"
你不需要触发器。相反,您可以使用 on delete cascade
选项的外键:
create table capitulos (
... -- other table columns
id_capitulo int
references livros(id_livro)
on delete cascade
);
至于你现有的代码:因为你有一个 delete
触发器,你需要使用伪 table old
而不是 new
(实际上是空的):
create or replace function remover_capitulo()
returns trigger as
$body$
begin
delete from capitulos where id_capitulo = old.id_livro;
return old;
end;
$body$
language plpgsql;
create trigger trg_remover_capitulo
before delete on livros
for each row
execute procedure remover_capitulo();