-- =============================================
-- Author:      Vitacore Anatoliy
-- Create date: 2021 03 09
-- =============================================
DROP PROCEDURE IF EXISTS stor.sp_DeleteInventoryElementsProcess;

CREATE PROCEDURE stor.sp_DeleteInventoryElementsProcess
(
	"InventoryDocumentID" uuid
)
    language plpgsql
as
$$
Begin 

	if exists(select * from STOR.T_INVENTORY_DOCUMENT where Status <> 2 and InventoryDocumentID = "InventoryDocumentID")
	then
		delete from STOR.T_INVENTORY_ELEMENTS_REMAINS ier
		where exists(select* from STOR.T_INVENTORY_ELEMENTS ie where ie.InventoryElementsID = ier.InventoryElements and ie.InventoryDocument = "InventoryDocumentID");

		delete from STOR.T_SCANNED_INVENTORY_ELEMENTS ier
		where exists(select* from STOR.T_INVENTORY_ELEMENTS ie where ie.InventoryElementsID = ier.InventoryElements and ie.InventoryDocument = "InventoryDocumentID");

		delete from STOR.T_INVENTORY_ELEMENTS ie where ie.InventoryDocument = "InventoryDocumentID";
	end if;
End;
$$;