DELIMITER $$ CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn2008`.`XDiario_Quadrator`() BEGIN INSERT INTO vn.mail (receiver, subject, body) SELECT 'cau@verdnatura.es', 'asientos descuadrados', group_concat(CONCAT(' Asiento: ', ASIEN, '- importe:', quadre) SEPARATOR ' \r\n ') FROM ( SELECT ASIEN, SUM(IFNULL(ROUND(Eurodebe,2),0))- SUM(IFNULL(ROUND(EUROHABER,2),0)) quadre FROM XDiario WHERE enlazado = FALSE GROUP BY ASIEN HAVING ABS(SUM(IFNULL(ROUND(Eurodebe,2),0))- SUM(IFNULL(ROUND(EUROHABER,2),0))) > 0.01 ) t HAVING count(*) > 0; UPDATE XDiario XD INNER JOIN( SELECT XD.id, SUBCTA, Quadre FROM XDiario XD INNER JOIN ( SELECT ASIEN, SUM(IFNULL(ROUND(Eurodebe,2),0))- SUM(IFNULL(ROUND(EUROHABER,2),0)) as Quadre FROM XDiario WHERE enlazado = FALSE GROUP BY ASIEN HAVING Quadre != 0 ) sub USING(ASIEN) WHERE SUBCTA > '5999999999' GROUP BY ASIEN ) sub2 USING(id) SET Eurohaber = IF(IFNULL(Eurohaber,0) = 0, Eurohaber, Eurohaber + Quadre), Eurodebe = IF(IFNULL(Eurodebe,0) = 0, Eurodebe, Eurodebe - Quadre); END$$ DELIMITER ;