IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[stor].[sp_DeleteInventoryElementsProcess]') AND type in (N'P', N'PC'))
DROP PROCEDURE stor.[sp_DeleteInventoryElementsProcess]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[sp_DeleteInventoryElementsProcess]') AND type in (N'P', N'PC'))
DROP PROCEDURE dbo.[sp_DeleteInventoryElementsProcess]
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:      Vitacore (с) Anatoliy
-- Create date: 2021 03 09
-- Description: Удаление элементов инвентаризации
-- =============================================
CREATE PROCEDURE stor.[sp_DeleteInventoryElementsProcess]
    @InventoryDocumentID uniqueidentifier
AS
BEGIN
	if(exists(select * from STOR.T_INVENTORY_DOCUMENT where Status <> 2 and InventoryDocumentID = @InventoryDocumentID))
	begin
		delete ier
		from STOR.T_INVENTORY_ELEMENTS_REMAINS ier
		join STOR.T_INVENTORY_ELEMENTS ie on ie.InventoryElementsID = ier.InventoryElements
		where ie.InventoryDocument = @InventoryDocumentID

		delete ier
		from STOR.T_SCANNED_INVENTORY_ELEMENTS ier
		join STOR.T_INVENTORY_ELEMENTS ie on ie.InventoryElementsID = ier.InventoryElements
		where ie.InventoryDocument = @InventoryDocumentID

		delete ie
		from STOR.T_INVENTORY_ELEMENTS ie
		where ie.InventoryDocument = @InventoryDocumentID
	end
END