Problem with Trigger in select/Insert

Asked

Viewed 25 times

1

Personal I created two entities, where the information of one is manipulated by the other. That is, I own an entity conta and another conta_extrato the balance of the entity account is modified only with insertions in the conta_extrato.

I was able to reach the expected result, but when trying to make a select/Insert I came across the error below:

Can’t update table 'account' in stored Function/Trigger because it is already used by statement which Invoked this stored Function/Trigger.

If I do the registration Insert everything goes perfectly. How do I fix this error?

SGBD = Mysql 5.7

DDL

create table conta (
  id int primary key auto_increment,
  nome varchar(150),
  valor int not null default 0
);

create table conta_extrato (
  id int primary key auto_increment,
  idconta int not null,
  valor int not null,
  foreign key(idconta) references conta(id)
);

-- criando trigger para controlar a conta a partir do extrato...
DELIMITER //
CREATE TRIGGER trg_conta_extrato_after_insert
AFTER INSERT
   ON conta_extrato FOR EACH ROW
BEGIN
   UPDATE conta SET valor = valor + NEW.valor WHERE id = NEW.idconta;
END //
DELIMITER ;

DML

-- inserindo contas
insert into conta (nome) values ('josé da silva'), ('maria fernanda'), ('marcos antônio');

-- inserindo valores no extrato para teste
insert into conta_extrato (idconta, valor) values (1, 500), (2, 600), (3, 150);

-- extratos foram inseridos com sucesso
select * from conta_extrato;

-- contas foram atualizadas com sucesso
select * from conta;

-- erro acontece no select insert
insert into conta_extrato (valor, idconta)
select 500 as valor, id from conta;

Example in Dbfiddler: https://www.db-fiddle.com/f/c5467EmEpTzW68Uy52m8PJ/0

  • Of the manual: The target table of the INSERT statement may appear in the FROM clause of the SELECT part of the query, or as the table named by TABLE. However, you cannot insert into a table and select from the same table in a subquery. https://dev.mysql.com/doc/refman/8.0/en/insert-select.html

  • @anonymimo my query is not in the same table, in this example I did just to demonstrate. I consult in another table.

  • @anonimo I do a Join Inner on the table, now I get it. That’s it, thank you very much.

  • 1

    this does not answer the question but can give another way, why not use a stored procudure in place of a Rigger? that would work, transactional and becomes clearer, as all transactions are in the same statement, in the code of Procedure

  • @Ricardopunctual a stored The term you speak is to do the select/Insert job, correct?

  • yes, and also the account table update

Show 1 more comment
No answers

Browser other questions tagged

You are not signed in. Login or sign up in order to post.