if object_id('SP_EHR_RUS_ChangeRefs', 'P') is not null
	drop procedure SP_EHR_RUS_ChangeRefs
go
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE SP_EHR_RUS_ChangeRefs
	@Entity VarChar(100),
	@Attr VarChar(100),
	@EhrReplacement uniqueidentifier
AS 
BEGIN
SET XACT_ABORT, NOCOUNT ON

DECLARE @EhrRusRefBooks VARCHAR(40) = (SELECT TOP 1 NewEhrRefBook FROM EHR.T_EHR_REPLACEMENT er WHERE er.EhrReplacementID = CAST(@EhrReplacement as nvarchar(40)))

declare @tsql nvarchar(max)

set @tsql = N'update entity
set ' + @Attr + N' = (
SELECT TOP 1 case when eer.NewEhr is not null then eer.NewEhr else entity.' + @Attr + N' end)
from ' + @Entity + N' entity left join EHR.T_ELEMENT_EHR_REPLACEMENT eer
on eer.OldEhr = entity.' + @Attr + N'
where eer.EhrReplacement = ''' + CAST(@EhrReplacement as nvarchar(40)) + N'''
UPDATE EHR.T_EHR_REFERENCE
SET EhrRusRefBooks = ''' + @EhrRusRefBooks + N'''
WHERE Entities = (
SELECT e.EntityID FROM VCLib.T_ENTITIES e WHERE e.[Schema] + ''.T_'' + e.EntName = ''' + @Entity + N''')
AND AttributeName = ''' + @Attr + N'''
declare @txt varchar(500)
select @txt = ''begin(p)
  @p := new Process("ChangeServerHolderState");
  @p->{Parameters}["HolderName"] := "EHR.EhrReferenceHolder";
  @p->{Parameters}["State"] := "Refresh";
  @p->Run()[@p];
end;''
select @txt as lexem'
;


--print @tsql;
exec sp_executesql @tsql;

return;

end
