DROP PROCEDURE IF EXISTS SP_EHR_RUS_ChangeRefs;

CREATE PROCEDURE SP_EHR_RUS_ChangeRefs
(
	"Entity" varchar(100)
,	"Attr" varchar(100)
,	"EhrReplacement" uuid
,	"UpdateTable" boolean
)
    language plpgsql
as
$$
Begin
	declare _tsql text;
	DECLARE "EhrRusRefB" integer := (SELECT NewEhrRefBook FROM EHR.T_EHR_REPLACEMENT er WHERE eer.EhrReplacementID = "EhrReplacement"::varchar(40) limit 1);
	Begin
		_tsql := case when "UpdateTable" = '1' then '
					update ' || "Entity" || ' 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 Entities = (
				SELECT e.EntityID FROM VCLib.T_ENTITIES e WHERE e.Schema + ''.T_'' + e.EntName = ''' || "Entity" || ''')
				AND AttributeName = ''' || "Attr" || ''';';
		
		--RAISE NOTICE '%', _tsql;
		EXECUTE _tsql;		
	
	End;
End;
$$;
