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 @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 = (
SELECT er.EhrRusRefBooks FROM EHR.T_EHR_RUS er
WHERE EhrRusID = (
SELECT TOP 1 NewEhr FROM EHR.T_ELEMENT_EHR_REPLACEMENT eer 
WHERE eer.EhrReplacement = ''' + CAST(@EhrReplacement as nvarchar(40)) + 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
