DROP PROCEDURE IF EXISTS ehr.SP_EHR_RUS_ChangeRefs;

CREATE PROCEDURE ehr.SP_EHR_RUS_ChangeRefs
(
	"Table" varchar(100)
,	"Attr" varchar(100)
,	"EhrReplacement" uuid
,	"UpdateTable" boolean
,	"EhrRef" uuid
)
    language plpgsql
as
$$
Begin
	declare _tsql text;
	DECLARE "EhrRusRefB" integer := (SELECT NewEhrRefBook FROM EHR.T_EHR_REPLACEMENT er WHERE er.EhrReplacementID = "EhrReplacement"::varchar(40) limit 1);
	Begin
		_tsql := case when "UpdateTable" = true then '
					update ' || "Table" || ' entity
					set ' || "Attr" || ' = eer.NewEhr
					from EHR.T_ELEMENT_EHR_REPLACEMENT eer
					where eer.OldEhr = entity.' || "Attr" ||' and eer.ExistsData = ''' || 1 || ''' and eer.NewEhr IS NOT NULL and eer.EhrReplacement = ''' || "EhrReplacement"::varchar(36) || ''';
				' else '' end || '
				
				UPDATE EHR.T_EHR_REFERENCE
				SET EhrRusRefBooks = ''' || "EhrRusRefB"::varchar(50) || '''
				WHERE EhrReferenceId = ''' ||  "EhrRef"::varchar(36) || ''';';
		
		--RAISE NOTICE '%', _tsql;
		EXECUTE _tsql;		
	
	End;
End;
$$;
