DROP PROCEDURE IF EXISTS sp_q021formelload;
DROP FUNCTION IF EXISTS sp_q021formelload;

CREATE PROCEDURE public.sp_q021formelload("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_q021;

	CREATE TEMP TABLE temp_q021 as
	SELECT 
		IDFORM, 
		NAMFORM,
		COMMENT, 
		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 
		IDFORM text path './IDFORM' null, 
		NAMFORM text path './NAMFORM' null,
		COMMENT text path './COMMENT' null,
		DATEBEG text path './DATEBEG' null, 
		DATEEND text path './DATEEND' null );
	
			Update IES.T_Q021_FORM_EL t2 
	set  NAMFORM=t1.NAMFORM
		,COMMENT=t1.COMMENT
		,DATEEND=t1.DATEEND
	from temp_q021 t1
	where (t1.IDFORM=t2.IDFORM and t1.DATEBEG = t2.DATEBEG) and (t2.DATEEND = t1.DATEEND or t2.DATEEND is null );

	Insert into IES.T_Q021_FORM_EL(Q021FormElID,IDFORM,NAMFORM,COMMENT,DATEBEG,DATEEND)
	select gen_random_uuid(),t1.IDFORM,t1.NAMFORM, t1.COMMENT,t1.DATEBEG,t1.DATEEND
	from temp_q021 t1
	left join IES.T_Q021_FORM_EL t2 on (t1.IDFORM=t2.IDFORM and t1.DATEBEG = t2.DATEBEG) and (t2.DATEEND = t1.DATEEND or (t2.DATEEND is null and t1.DATEEND is null) )
	where t2.Q021FormElID is null;

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

