DROP PROCEDURE IF EXISTS sp_n008mrfrtload;
DROP FUNCTION IF EXISTS sp_n008mrfrtload;

CREATE PROCEDURE public.sp_n008mrfrtload("Xml" bytea, "FileName" character varying)
LANGUAGE 'plpgsql'
AS $BODY$
	
declare T xml;
declare tempStrXml text;
BEGIN
	select convert_from("Xml", 'WIN1251') into tempStrXml;
	
	select replace(tempStrXml, 'encoding="windows-1251"','')::xml into T; 
	
	DROP TABLE IF EXISTS temp_n008;

	CREATE TEMP TABLE temp_n008 as
	SELECT 
		ID_R_M::int, 
		R_M_NAME,
		ID_Mrf::int, 
		CASE WHEN  DATEBEG  = '' THEN NULL ELSE DATEBEG::TIMESTAMP END , 
		CASE WHEN  DATEEND  = '' THEN NULL ELSE DATEEND::TIMESTAMP END 
	FROM
	XMLTABLE ('/packet/zap' PASSING T 
	COLUMNS 
		ID_R_M text path './ID_R_M' null, 
		R_M_NAME text path './R_M_NAME' null,
		ID_Mrf text path './ID_Mrf' null, 
		DATEBEG text path './DATEBEG' null, 
		DATEEND text path './DATEEND' null );
	
		update IES.T_N008_MRF_RT t2
	set  R_M_NAME=t1.R_M_NAME
		,DATEEND=t1.DATEEND
	from temp_n008 t1
	where (t1.ID_R_M=t2.ID_R_M and t1.DATEBEG = t2.DATEBEG);

	insert into IES.T_N008_MRF_RT(N008MrfRtID, ID_R_M, N007Mrf, R_M_NAME, DATEBEG, DATEEND)
	select gen_random_uuid(),t1.ID_R_M,t3.N007MrfID,t1.R_M_NAME,t1.DATEBEG,t1.DATEEND
	from temp_n008 t1
	left join IES.T_N008_MRF_RT t2 on (t1.ID_R_M=t2.ID_R_M and t1.DATEBEG = t2.DATEBEG)
	join IES.T_N007_MRF t3 on (t3.ID_Mrf = t1.ID_Mrf)
	where t2.N008MrfRtID is null;

	drop table if exists temp_n008;
	
	return;
END
$BODY$;
