if exists (select * from sys.all_objects ao where ao.name = 'sp_DropOuterAct' ) DROP PROCEDURE [dbo].[sp_DropOuterAct]
GO

SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE PROCEDURE [dbo].[sp_DropOuterAct]
  @OuterActID uniqueidentifier
AS
BEGIN

if exists(select top 1 1/0 
	from [IES].T_OUTER_ACT_ITEM_CONCAT t1 with(nolock)
	join [IES].T_OUTER_ACT_ITEM t2 with(nolock) on t1.SchetsluchAccomplished = t2.SchetsluchAccomplished
	join ies.T_SCHET_SLUCH_ACCOMPLISHED ssa with(nolock) on (t1.OuterActItemConcatID = ssa.OuterActItemConcat)
	where t2.OuterAct = @OuterActID)
BEGIN
	raiserror('Невозможно удалить сторонний акт, т.к. есть случаи сформированные из него', 18, 100);
	return;
END

delete sl
from [IES].T_OUTER_ERROR_SL sl
join [IES].T_OUTER_ERROR t1 with(nolock) on t1.OuterErrorID = sl.OuterError
join [IES].T_OUTER_ACT_ITEM t2 with(nolock)  on t1.OuterActItem = t2.OuterActItemID
where t2.OuterAct = @OuterActID

delete t1
from [IES].T_OUTER_ERROR t1
join [IES].T_OUTER_ACT_ITEM t2 with(nolock)  on t1.OuterActItem = t2.OuterActItemID
where t2.OuterAct = @OuterActID

delete t1
from [IES].T_OUTER_ACT_ITEM_CONCAT t1
join [IES].T_OUTER_ACT_ITEM t2 with(nolock)  on t1.SchetsluchAccomplished = t2.SchetsluchAccomplished
where t2.OuterAct = @OuterActID

delete from [IES].T_OUTER_ACT_ITEM where OuterAct = @OuterActID

END
