DELIMITER $$ CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn2008`.`account_conciliacion_add`() BEGIN UPDATE account_conciliacion ac JOIN ( SELECT idaccount_conciliacion, @c:= if(@id = id_calculated, @c + 1, 1) contador, @id:= id_calculated as id_calculated, concat(id_calculated,'(',@c,')') as new_id FROM account_conciliacion JOIN ( select id_calculated, count(*) rep, @c:= 0, @id:= concat('-',id_calculated) from account_conciliacion group by id_calculated having rep > 1 ) sub using(id_calculated) ) sub2 using(idaccount_conciliacion) SET ac.id_calculated = sub2.new_id; INSERT INTO Cajas(Cajafecha, Partida, Serie, Concepto, Entrada, Salida, Id_Banco,empresa_id, warehouse_id, Proveedores_account_id, id_calculated, InForeignValue, OutForeignValue, Id_Trabajador) SELECT Fechaoperacion, TRUE, 'MB', ac.Concepto, IF(DebeHaber = 2 AND currencyFk = 1, importe,null), IF(DebeHaber = 1 AND currencyFk = 1, importe, null), a.id, sa.supplierFk, 1, ac.Id_Proveedores_account, ac.id_calculated, IF(DebeHaber = 2 AND NOT currencyFk = 1, importe, null), IF(DebeHaber = 1 AND NOT currencyFk = 1, importe, null), account.myUser_getId() FROM account_conciliacion ac JOIN vn.supplierAccount sa on sa.id = ac.Id_Proveedores_account JOIN vn.accounting a ON a.id = sa.accountingFk LEFT JOIN Cajas c on c.id_calculated = ac.id_calculated WHERE c.Id_Caja IS NULL; END$$ DELIMITER ;