DROP PROCEDURE IF EXISTS sp_n010markload;
DROP FUNCTION IF EXISTS sp_n010markload;

CREATE PROCEDURE public.sp_n010markload("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_n010;

	CREATE TEMP TABLE temp_n010 as
	SELECT 
		ID_Igh::int, 
		KOD_Igh,
		Igh_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_Igh text path './ID_Igh' null, 
		KOD_Igh text path './KOD_Igh' null,
		Igh_NAME text path './Igh_NAME' null, 
		DATEBEG text path './DATEBEG' null, 
		DATEEND text path './DATEEND' null );
	
		update IES.T_N010_MARK t2  
	set  KOD_Igh=t1.KOD_Igh
		,Igh_NAME=t1.Igh_NAME
		,DATEEND=t1.DATEEND
	from temp_n010 t1
	where (t1.ID_Igh=t2.ID_Igh and t1.DATEBEG = t2.DATEBEG);

	insert into IES.T_N010_MARK(N010MarkID, ID_Igh, KOD_Igh, Igh_NAME, DATEBEG, DATEEND)
	select gen_random_uuid(),t1.ID_Igh,t1.KOD_Igh,t1.Igh_NAME,t1.DATEBEG,t1.DATEEND
	from temp_n010 t1
	left join IES.T_N010_MARK t2 on (t1.ID_Igh=t2.ID_Igh and t1.DATEBEG = t2.DATEBEG)
	where t2.N010MarkID is null;

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