DROP PROCEDURE IF EXISTS sp_n009mrtdsload;
DROP FUNCTION IF EXISTS sp_n009mrtdsload;

CREATE PROCEDURE public.sp_n009mrtdsload("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_n009;

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

	insert into IES.T_N009_MRT_DS(N009MrtDsID, ID_M_D, N007Mrf, DS_Mrf, DATEBEG, DATEEND)
	select gen_random_uuid(),t1.ID_M_D,t3.N007MrfID,t1.DS_Mrf,t1.DATEBEG,t1.DATEEND
	from temp_n009 t1
	left join IES.T_N009_MRT_DS t2 on (t1.ID_M_D=t2.ID_M_D and t1.DATEBEG = t2.DATEBEG)
	join IES.T_N007_MRF t3 on (t3.ID_Mrf = t1.ID_Mrf)
	where t2.N009MrtDsID is null;

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