Skip to content

Instantly share code, notes, and snippets.

@guidani
Created July 10, 2021 22:27
Show Gist options
  • Save guidani/b867295d4ae837b30e4634015dfb1c63 to your computer and use it in GitHub Desktop.
Save guidani/b867295d4ae837b30e4634015dfb1c63 to your computer and use it in GitHub Desktop.
questão 2
-- 2)Crie um trigger que altere o status da reserva de um leitor para I (Inativo)
-- sempre que ele tomar emprestado o livro do título que ele reservou
-- trigger function
CREATE OR REPLACE FUNCTION f_altera_status_reserva()
RETURNS TRIGGER AS $$
DECLARE
titulo_reservado int;
codigo_do_leitor int;
BEGIN
--
select cod_tit into titulo_reservado from livro where cod_livro in (select cod_livro from item_emprestimo);
select cod_leitor into codigo_do_leitor from emprestimo where cod_emprestimo in (select cod_emprestimo from item_emprestimo);
-- codigo
UPDATE RESERVA SET STATUS='I' WHERE cod_tit = titulo_reservado and cod_leitor = codigo_do_leitor;
RETURN NEW;
END;
$$ LANGUAGE 'plpgsql';
-- TRIGGER
CREATE TRIGGER t_altera_status_reserva
after INSERT or update
ON item_emprestimo
FOR EACH ROW EXECUTE PROCEDURE f_altera_status_reserva();
-- testes
insert into emprestimo(cod_emprestimo, cod_leitor, cod_func, dt_emprestimo, dt_prev_devolucao, quant_livro) values
(8, 2, 1, now(), '2021-07-10', 1)
@guidani
Copy link
Author

guidani commented Jul 10, 2021

create function atualizar_status()
returns trigger as $$
begin
if new.cod_leitor = (select emprestimo.cod_leitor from emprestimo join item_emprestimo on emprestimo.cod_emprestimo =
item_emprestimo.cod_emprestimo join livro on item_emprestimo.cod_livro = livro.cod_livro join
titulo on livro.cod_tit = titulo.cod_tit join reserva on titulo.cod_tit = reserva.cod_tit) then
update reserva set status = 'I';
end if;
return new;
end;
$$ language 'plpgsql';

create trigger status
after insert
on emprestimo
for each row
execute procedure atualizar_status()

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment