update Trigger - Mysql

0

I have to create a trigger associated with the orders table so that when I update a record in the orders table, I update it in the table detailing requests, I have tried it in the following way but there is no way, if someone could solve it. ...

drop table if exists updatepedidos; 
create table updatepedidos (
  CodigoPedido integer NOT NULL,
  FechaPedido date NOT NULL,
  FechaEsperada date NOT NULL,
  FechaEntrega date DEFAULT NULL,
  Estado varchar(15) NOT NULL,
  Comentarios text,
  CodigoCliente integer NOT NULL,
  PRIMARY KEY (CodigoPedido),
  CONSTRAINT Pedidos_Cliente FOREIGN KEY (CodigoCliente) REFERENCES Clientes (CodigoCliente)
);


drop trigger if exists controlpedidos; 

DELIMITER //

create trigger controlpedidos before update on pedidos for each row 
begin

if new.CodigoPedido<>old.CodigoPedido then 
insert into updatepedidos values (new.CodigoPedido, old.FechaPedido, old.FechaEsperada, old.FechaEntrega, old.Estado, old.Comentarios, old.CodigoCliente);
end if;

if new.FechaPedido<>old.FechaPedido then 
insert into updatepedidos values (old.CodigoPedido, new.FechaPedido, old.FechaEsperada, old.FechaEntrega, old.Estado, old.Comentarios, old.CodigoCliente);
end if;

if new.FechaEsperada<>old.FechaEsperada then 
insert into updatepedidos values (old.CodigoPedido, old.FechaPedido, new.FechaEsperada, old.FechaEntrega, old.Estado, old.Comentarios, old.CodigoCliente);
end if;

if new.FechaEntrega<>old.FechaEntrega then 
insert into updatepedidos values (old.CodigoPedido, old.FechaPedido, old.FechaEsperada, new.FechaEntrega, old.Estado, old.Comentarios, old.CodigoCliente);
end if;

if new.Estado<>old.Estado then 
insert into updatepedidos values (old.CodigoPedido, old.FechaPedido, old.FechaEsperada, old.FechaEntrega, new.Estado, old.Comentarios, old.CodigoCliente);
end if;

if new.Comentarios<>old.Comentarios then 
insert into updatepedidos values (old.CodigoPedido, old.FechaPedido, old.FechaEsperada, old.FechaEntrega, old.Estado, new.Comentarios, old.CodigoCliente);
end if;

if new.CodigoCliente<>old.CodigoCliente then 
insert into updatepedidos values (old.CodigoPedido, new.FechaPedido, old.FechaEsperada, old.FechaEntrega, old.Estado, old.Comentarios, new.CodigoCliente);
end if;

end//
DELIMITER ;

update pedidos set CodigoCliente=22 where CodigoPedido=1; 
    
asked by 14.01.2018 в 12:21
source

1 answer

0

You are inserting do not do any UPDATE on the trigger, imagine that you use IF to know if the record exists or not in the updated table.

Another detail is that you can not make an update with CodigoPedido because it is a PK. (Actually it allows you but it is not a good practice)

What you should do is with the code CodigoPedido search if there is record data in your table updatepedidos , if null you use insert but update filtering with CodigoPedido .

Execute describe pedidos; to know what data the table contains.

    
answered by 15.01.2018 в 15:19