IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[SP_EHR_RUS_ChangeRefs]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].SP_EHR_RUS_ChangeRefs
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[ehr].[SP_EHR_RUS_ChangeRefs]') AND type in (N'P', N'PC'))
DROP PROCEDURE ehr.SP_EHR_RUS_ChangeRefs
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE ehr.SP_EHR_RUS_ChangeRefs
	@Table VarChar(100),
	@Attr VarChar(100),
	@EhrReplacement uniqueidentifier,
	@UpdateTable bit,
	@EhrRef uniqueidentifier
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 ' + @Table + 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 EhrReferenceId = ''' +  CAST(@EhrRef as varchar(36)) + '''';


--print @tsql;
exec sp_executesql @tsql;

return;

end
