DELIMITER $$ CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`shelving_clean`() BEGIN DELETE FROM shelving WHERE length(code) > 3 AND parked < TIMESTAMPADD(WEEK,-1,util.VN_CURDATE()); DELETE FROM itemShelving WHERE visible <= 0 AND created < TIMESTAMPADD(MONTH,-1,util.VN_CURDATE()); DELETE ish.* FROM itemShelving ish JOIN vn.shelving sh ON sh.code = ish.shelvingFk WHERE sh.parkingFk IS NULL AND ish.created < TIMESTAMPADD(WEEK,-1,util.VN_CURDATE()); UPDATE shelving sh LEFT JOIN itemShelving its ON its.shelvingFk = sh.`code` SET isPrinted = 0, parkingFk = NULL WHERE its.id IS NULL AND sh.isRecyclable AND ( sh.parked IS NULL OR sh.parked < TIMESTAMPADD(MONTH,-1,util.VN_CURDATE()) ) AND IF(code REGEXP '^[A-Za-z]{2}[0-9]', LEFT (code, 2) NOT IN ( SELECT DISTINCT LEFT(its.shelvingFk, 2) FROM itemShelving its WHERE its.shelvingFk REGEXP '^[A-Za-z]{2}[0-9]' ), TRUE); END$$ DELIMITER ;