DELIMITER $$
CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `stock`.`buyOut_refresh`(
	`vTable` VARCHAR(255),
	`vId` INT)
BEGIN
	CREATE TEMPORARY TABLE tOutPrune
		ENGINE = MEMORY
		SELECT tableId FROM tOutOld
		EXCEPT
		SELECT tableId FROM tOutNew;

	DELETE o FROM buyOut o
		JOIN tOutPrune d USING(tableId)
		WHERE o.tableName = vTable;

	INSERT INTO buyOut (
			tableName,
			tableId,
			warehouseFk,
			dated,
			itemFk,
			quantity,
			lack,
			created,
			isPicked,
			isSync
		)
		SELECT
				vTable,
				tableId,
				warehouseFk,
				dated,
				itemFk,
				quantity,
				quantity,
				created,
				isPicked,
				FALSE
			FROM tOutNew
		ON DUPLICATE KEY UPDATE
			warehouseFk = VALUES(warehouseFk),
			dated = VALUES(dated),
			itemFk = VALUES(itemFk),
			quantity = VALUES(quantity),
			lack = VALUES(lack),
			created = VALUES(created),
			isPicked = VALUES(isPicked),
			isSync = VALUES(isSync);

	CREATE OR REPLACE TEMPORARY TABLE tPickPrune
		ENGINE = MEMORY
		SELECT id FROM buyPick
			WHERE tableName = vTable
				AND id IN (
					SELECT tableId FROM tOutDel
					UNION
					SELECT tableId FROM tOutNew
				);

	UPDATE buyLot l
			JOIN buyPick p ON p.buyFk = l.buyFk
			JOIN tPickPrune pp ON pp.id = p.id
		SET l.isSync = FALSE;

	DELETE p FROM buyPick p
		JOIN tPickPrune pp USING (id);

	DROP TEMPORARY TABLE tPickPrune;
END$$
DELIMITER ;
