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,
	@UpdateTable bit
AS 
BEGIN
SET XACT_ABORT, NOCOUNT ON

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

declare @tsql nvarchar(max)
set @tsql = case when @UpdateTable = 1 then N'
	update entity
	set ' + @Attr + N' = eer.NewEhr
	from ' + @Entity + N' entity 
	join EHR.T_ELEMENT_EHR_REPLACEMENT eer on eer.OldEhr = entity.' + @Attr +N'
	where eer.ExistsData = 1 and eer.NewEhr IS NOT NULL and eer.EhrReplacement = ''' + CAST(@EhrReplacement as nvarchar(36)) + N'''
' else '' end + '

UPDATE EHR.T_EHR_REFERENCE
SET EhrRusRefBooks = ' + CAST(@EhrRusRefBooks as varchar(50)) + '
WHERE Entities = (
SELECT e.EntityID FROM VCLib.T_ENTITIES e WHERE e.[Schema] + ''.T_'' + e.EntName = ''' + @Entity + N''')
AND AttributeName = ''' + @Attr + N'''';


--print @tsql;
exec sp_executesql @tsql;

return;

end
