DELIMITER $$ CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`absoluteInventoryHistory`( vItemFk INT, vWarehouseFk INT, vDate DATETIME ) BEGIN /** * Calcula y proporciona un historial de inventario absoluto * para un artículo específico en un almacén dado * hasta una fecha determinada. * * @param vItemFk Id de artículo * @param vWarehouseFk Id de almacén * @param vDate Fecha */ DECLARE vCalculatedInventory INT; DECLARE vToday DATETIME DEFAULT util.VN_CURDATE(); CREATE OR REPLACE TEMPORARY TABLE tHistoricalPast ENGINE = MEMORY SELECT * FROM ( SELECT tr.landed `date`, b.quantity input, NULL `output`, tr.isReceived ok, s.name alias, e.invoiceNumber reference, e.id id, tr.isDelivered f5 FROM buy b JOIN `entry` e ON e.id = b.entryFk JOIN travel tr ON tr.id = e.travelFk JOIN supplier s ON s.id = e.supplierFk WHERE tr.landed >= '2001-01-01' AND s.id <> 4 AND vWarehouseFk IN (tr.warehouseInFk, 0) AND b.itemFk = vItemFk AND NOT e.isExcludedFromAvailable AND NOT e.isRaid UNION ALL SELECT tr.shipped `date`, NULL input, b.quantity `output`, tr.isDelivered ok, s.name alias, e.invoiceNumber reference, e.id id, tr.isDelivered f5 FROM buy b JOIN `entry` e ON e.id = b.entryFk JOIN travel tr ON tr.id = e.travelFk JOIN supplier s ON s.id = e.supplierFk WHERE tr.shipped >= '2001-01-01' AND vWarehouseFk = tr.warehouseOutFk AND s.id <> 4 AND b.itemFk = vItemFk AND NOT e.isExcludedFromAvailable AND NOT e.isRaid UNION ALL SELECT t.shipped `date`, NULL input, m.quantity `output`, (m.isPicked OR t.isLabeled OR t.refFk IS NOT NULL) ok, t.nickname alias, t.refFk reference, t.id, t.isPrinted FROM sale m JOIN ticket t ON t.id = m.ticketFk JOIN client c ON c.id = t.clientFk WHERE t.shipped >= '2001-01-01' AND m.itemFk = vItemFk AND vWarehouseFk IN (t.warehouseFk , 0) ) t1 ORDER BY `date`, input DESC, ok DESC; SELECT SUM(input) - SUM(`output`) INTO vCalculatedInventory FROM tHistoricalPast WHERE `date` < vDate; SELECT p1.*, NULL v_virtual FROM ( SELECT vDate `date`, vCalculatedInventory input, NULL `output`, 1 ok, 'Inventario calculado' alias, '' reference, 0 id, 1 f5 UNION ALL SELECT * FROM tHistoricalPast WHERE `date` >= vDate ) p1; DROP TEMPORARY TABLE tHistoricalPast; END$$ DELIMITER ;