DROP PROCEDURE IF EXISTS rds.sp_CleanFrlloNeedsProcess;

CREATE OR REPLACE PROCEDURE rds.sp_CleanFrlloNeedsProcess(
    "ExportId" int,
    "All" boolean
)
    LANGUAGE plpgsql
AS
$$
DECLARE
    p_exportid int := "ExportId";
    v_num      int  := 1000;
BEGIN
    CREATE TEMP TABLE tmp_obj
    (
        id  int NOT NULL UNIQUE,
        num serial
    );
    
    INSERT INTO
        tmp_obj (id)
    SELECT DISTINCT fed.ExportFrlloNeedsElementID
    FROM rds.T_EXPORT_FRLLO_NEEDS_ELEMENT fed
    WHERE fed.ExportFrlloNeeds = p_exportid;
    
    LOOP
        IF
            NOT EXISTS (SELECT 1 FROM tmp_obj LIMIT 1)
        THEN
            EXIT;
        END IF;
        UPDATE rds.T_EXPORT_FRLLO_NEEDS_ELEMENT fed
        SET --frlloid     = NULL,
            frllostatus = NULL,
            frlloerror  = NULL
            --Recipe_id = null,
            --Recipe_release_id = null
        WHERE EXISTS(SELECT 1 FROM tmp_obj t WHERE t.id = ExportFrlloNeedsElementID AND t.num <= v_num)
          AND ExportFrlloNeeds = p_exportid;
        
        DELETE FROM tmp_obj WHERE num <= v_num;
        v_num := v_num + 1000;
    END LOOP;

END;
$$