if exists ( select * from sys.procedures p where p.name = 'sp_SchetActItemAdd' ) DROP PROCEDURE [dbo].[sp_SchetActItemAdd]
GO
CREATE PROCEDURE [dbo].[sp_SchetActItemAdd]
  @SchetID uniqueidentifier
  ,@SchetActID uniqueidentifier
AS 
BEGIN 

insert into ies.T_SCHET_ACT_ITEM(SchetActItemID, SchetSluchAccomplished, SchetSluch, SchetAct, IsAddToAct)
select newid(), t2.SchetSluchAccomplishedID, t3.SchetSluchID, @SchetActID, 1
from ies.T_SCHET_ZAP t1 with(nolock)
join ies.T_SCHET_SLUCH_ACCOMPLISHED t2 with(nolock) on (t2.schetzap = t1.schetzapid)
join ies.T_SCHET_SLUCH t3 with(nolock) on (t2.SchetSluchAccomplishedID = t3.SchetSluchAccomplished)
left join ies.T_SCHET_ACT_ITEM t4 with(nolock) on (t3.SchetSluchID = t4.SchetSluch)
where exists (select * from ies.T_SCHET_ACT_ITEM sai with(nolock) where sai.SchetSluchAccomplished = t2.SchetSluchAccomplishedID and sai.IsAddToAct = 1)
	and t1.Schet = @SchetID and t4.SchetActItemID is null

INSERT INTO ies.T_ACT_ITEM_ERROR(ActItemErrorID, SchetActItem, ExpertiseError, EvaluatedDescr)
select newid(), sai.SchetActItemID, aie.ExpertiseError, aie.EvaluatedDescr
from ies.T_SCHET_ZAP t1 with(nolock)
join ies.T_SCHET_SLUCH_ACCOMPLISHED t2 with(nolock) on (t2.schetzap = t1.schetzapid)
join ies.T_SCHET_SLUCH t3 with(nolock) on (t2.SchetSluchAccomplishedID = t3.SchetSluchAccomplished)
join ies.T_SCHET_ACT_ITEM t4 with(nolock) on (t3.SchetSluchID = t4.SchetSluch)
join ies.T_ACT_ITEM_ERROR aie on (t4.schetactitemid = aie.schetactitem)
join ies.T_SCHET_ACT_ITEM sai on (sai.schetsluchaccomplished = t2.SchetSluchAccomplishedID and sai.schetactitemid <> t4.schetactitemid)
where not exists (select 1/ 0 from ies.T_ACT_ITEM_ERROR aie2 where aie2.schetactitem = sai.schetactitemid)
	and t1.Schet = @SchetID

update t1
set Schet = t2.Schet
from ies.T_SCHET_SLUCH_ACCOMPLISHED t1 with(nolock)
join ies.T_SCHET_ZAP t2 with(nolock) on (t1.SchetZap = t2.SchetZapID)
where t2.Schet = @SchetID and t1.Schet is null

update t1
set Schet = t3.Schet
from ies.T_SCHET_SLUCH_ACCOMPLISHED t1 with(nolock)
join ies.T_SCHET_SLUCH t2 with(nolock) on (t1.SchetSluchAccomplishedID = t2.SchetSluchAccomplished)
join ies.T_SCHET_ZAP t3 with(nolock) on (t2.SchetZap = t3.SchetZapID)
where t3.Schet = @SchetID and t1.Schet is null

END