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

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

		delete ii
		from STOR.T_INVOICE_ITEM ii
		join #DELETE d on d.ElementID = ii.ElementID

		drop table #DELETE
	end
END