DELIMITER $$ CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`timeControl_getError`(vDatedFrom DATETIME, vDatedTo DATETIME) BEGIN /* * @param vDatedFrom * @param vDatedTo * @table tmp.`user`(userFk) * Fichadas incorrectas de las cuales no se puede calcular horas trabajadas * @return tmp.timeControlError (id) */ DECLARE vDayMaxTime INTEGER; SET @journeyCounter := 0; SET @lastUserFk := NULL; SELECT dayMaxTime INTO vDayMaxTime FROM workerTimeControlConfig LIMIT 1; DROP TEMPORARY TABLE IF EXISTS tmp.timeControl; CREATE TEMPORARY TABLE tmp.timeControl (INDEX(id), INDEX(journeyCounter)) ENGINE = MEMORY SELECT sub.id, sub.direction, sub.timed, IF(sub.direction = 'in' OR @hasOut OR sub.userFk <> @lastUserFk, @journeyCounter := @journeyCounter + 1, @journeyCounter) journeyCounter, @lastUserFk := sub.userFk workerFk, IF(sub.direction = 'out', @hasOut:= TRUE, @hasOut:= FALSE) FROM ( SELECT DISTINCT wtc.id, wtc.direction, wtc.timed, wtc.userFk FROM workerTimeControl wtc JOIN tmp.`user` w ON w.userFk = wtc.userFk WHERE wtc.timed BETWEEN DATE_SUB(vDatedFrom, INTERVAL 1 DAY) AND DATE_ADD(vDatedTo, INTERVAL 1 DAY) ORDER BY wtc.userFk, wtc.timed ) sub; DROP TEMPORARY TABLE IF EXISTS tmp.timeControlAux; CREATE TEMPORARY TABLE tmp.timeControlAux (INDEX(id), INDEX(journeyCounter)) ENGINE = MEMORY SELECT * FROM tmp.timeControl; DROP TEMPORARY TABLE IF EXISTS tmp.timeControlError; CREATE TEMPORARY TABLE tmp.timeControlError (INDEX(id)) ENGINE = MEMORY SELECT id FROM tmp.timeControlAux tca JOIN ( SELECT journeyCounter, UNIX_TIMESTAMP(MAX(timed)) - UNIX_TIMESTAMP(MIN(timed)) timeWork, SUM(direction = 'in') totalIn, SUM(direction = 'out') totalOut, timed FROM tmp.timeControl GROUP BY journeyCounter HAVING COUNT(*) MOD 2 = 1 OR totalIn <> 1 OR totalOut <> 1 OR timeWork >= vDayMaxTime )sub ON sub.journeyCounter = tca.journeyCounter WHERE sub.timed BETWEEN vDatedFrom AND vDatedTo; DROP TEMPORARY TABLE IF EXISTS tmp.timeControl; DROP TEMPORARY TABLE IF EXISTS tmp.timeControlAux; END$$ DELIMITER ;