DROP PROCEDURE IF EXISTS sp_n007mrfload;
DROP FUNCTION IF EXISTS sp_n007mrfload;

CREATE PROCEDURE public.sp_n007mrfload("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_n007;

	CREATE TEMP TABLE temp_n007 as
	SELECT 
		ID_Mrf::int, 
		Mrf_NAME, 
		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_Mrf text path './ID_Mrf' null, 
		Mrf_NAME text path './Mrf_NAME' null, 
		DATEBEG text path './DATEBEG' null, 
		DATEEND text path './DATEEND' null );
	
	update IES.T_N007_MRF t2 
	set  Mrf_NAME=t1.Mrf_NAME
		,DATEEND=t1.DATEEND
	from temp_n007 t1
	where (t1.ID_Mrf=t2.ID_Mrf and t1.DATEBEG = t2.DATEBEG);

	insert into IES.T_N007_MRF(N007MrfID, ID_Mrf, Mrf_NAME, DATEBEG, DATEEND)
	select gen_random_uuid(),t1.ID_Mrf,t1.Mrf_NAME,t1.DATEBEG,t1.DATEEND
	from temp_n007 t1
	left join IES.T_N007_MRF t2 on (t1.ID_Mrf=t2.ID_Mrf and t1.DATEBEG = t2.DATEBEG)
	where t2.N007MrfID is null;

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