IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[stor].[sp_DeleteInvoiceItemProcess]') AND type in (N'P', N'PC'))
DROP PROCEDURE stor.[sp_DeleteInvoiceItemProcess]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[sp_DeleteInvoiceItemProcess]') AND type in (N'P', N'PC'))
DROP PROCEDURE dbo.[sp_DeleteInvoiceItemProcess]
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:      Vitacore (с) Anatoliy
-- Create date: 2021 03 09
-- Description: Удаление из накладной элементов
-- =============================================
CREATE PROCEDURE stor.[sp_DeleteInvoiceItemProcess]
    @InvoiceId uniqueidentifier,
    @All bit
AS
BEGIN
	if(exists(select * from STOR.T_STORAGE_INVOICE where InvoiceID = @InvoiceId and State = 0))
	Begin
		Declare @DELETE table(ElementID uniqueidentifier) 

		if(@All = 1)
		begin

			INSERT INTO @DELETE(ElementID)
			select ii.ElementID
			from STOR.T_INVOICE_ITEM ii
			where StorageInvoice = @InvoiceId
		end
		else
		begin
			INSERT INTO @DELETE(ElementID)
			select ii.ElementID
			from STOR.T_INVOICE_ITEM ii
			where StorageInvoice = @InvoiceId and (ii.Amount is null or ii.Amount = 0)
		end

		delete dii
		from STOR.T_DESTRUCTION_ITEM_INFO dii
		join @DELETE d on d.ElementID = dii.InvoiceItem

		update mm
		set mm.ObjId = null
		from STOR.T_MARK_MESSAGE mm
		join @DELETE d on d.ElementID = mm.ObjId

		update pdd
		set pdd.InvoiceItem = null
		from STOR.T_PATIENT_DRUG_DELIVERY pdd
		join @DELETE d on d.ElementID = pdd.InvoiceItem
		
		delete ii
		from STOR.T_SGTINS ii
		join @DELETE d on d.ElementID = ii.IdInvoiceItem

		delete ii
		from STOR.T_INVOICE_ITEM ii
		join @DELETE d on d.ElementID = ii.ElementID
	end
END