drop procedure if exists public.sp_CleanFrlloRemainsProcess;
-- =============================================
-- Author:      Vitacore (с) Anatoliy
-- Create date: 2024 11 25
-- Description: Выгрузка данных в ФРЛЛО
-- =============================================
create procedure public.sp_CleanFrlloRemainsProcess
(
	"ExportId" uuid default null::uuid
);
language plpgsql
as
$$
begin
	declare _Num int := 1000;

	create temp table TMP_OBJ 
	(
		"id" integer not null unique,
		"num" serial
	);

	insert into TMP_OBJ("id")
	select distinct ExportFrlloRemainsDataID
	from RDS.T_EXPORT_FRLLO_REMAINS_DATA fed 
	WHERE fed.ExportFrlloRemains = "ExportId";

	loop
		if 
		not exists (select 1 from TMP_OBJ limit 1) 
			then exit;
		end if;
		update RDS.T_EXPORT_FRLLO_REMAINS_DATA as fed
		set fed.FrlloId = null,
			fed.FrlloStatus = null,
			fed.FrlloError = null
		where exists(select 1 from TMP_OBJ t where t.id = fed.ExportFrlloRemainsDataID and t.num <= _Num))

		delete TMP_OBJ where num <= _Num;
		_Num := _Num + 1000;
	end loop;
end;
$$;