do $$
begin
	if exists 
	(
		select * from pg_proc p
		where p.proname = 'sp_setloaderrors'
	)
	then
		drop function public.sp_setloaderrors(uuid);
	end if;
end;
$$ language plpgsql;
CREATE OR REPLACE FUNCTION public.sp_setloaderrors(
	SLHID uuid)
    RETURNS void
    LANGUAGE 'plpgsql'
    COST 100
    VOLATILE PARALLEL UNSAFE
AS $BODY$
BEGIN
INSERT INTO IES.T_SLH_ERROR
(SlhErrorID, Count, ExpertiseError, SchetLoadHistory)
select gen_random_uuid(), count(*), aie.ExpertiseError, SLHID
from IES.T_SCHET_LOAD_HISTORY slh
join IES.T_SCHET s  on (slh.Schet = s.SchetID)
join IES.T_SCHET_ZAP sz  on (sz.Schet = s.SchetID)
join IES.T_SCHET_SLUCH ss  on (sz.SchetZapID = ss.SchetZap)
join IES.T_SCHET_ACT_ITEM sai on (ss.SchetSluchID = sai.SchetSluch)
join IES.T_ACT_ITEM_ERROR aie on (sai.SchetActItemID = aie.SchetActItem)
where slh.LoadHistoryID = SLHID
GROUP BY aie.ExpertiseError;

END;
$BODY$;

ALTER FUNCTION public.sp_setloaderrors(uuid)
    OWNER TO postgres;