if exists ( select * from sys.procedures p where p.name = 'sp_DropOuterAct' ) DROP PROCEDURE [dbo].[sp_DropOuterAct]
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
	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 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

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 from [IES].T_OUTER_ACT_ITEM where OuterAct = @OuterActID

delete from [IES].T_OUTER_ACT where OuterActID = @OuterActID
END