DROP PROCEDURE IF EXISTS rds.sp_updatefrllorecipetype;
CREATE OR REPLACE PROCEDURE rds.sp_updatefrllorecipetype(exportfrllorecipedataid uuid,"WorkWithError" boolean = false)
    LANGUAGE plpgsql
AS
$$
DECLARE
    p_exportfrllorecipedataid uuid := exportfrllorecipedataid;
    p_workwitherror boolean  := "WorkWithError";
    v_recid                   uuid;
BEGIN
    SELECT
        r.recipeid
    INTO v_recid
    FROM rds.t_export_frllo_recipe_data d
    JOIN rds.t_recipe r ON d.objid = r.recipeid
    WHERE d.exportfrllorecipedataid = p_exportfrllorecipedataid;

    IF (v_recid IS NOT NULL) THEN

        UPDATE rds.t_recipe r
        SET frllotype = case WHEN p_workwitherror = false THEN (CASE WHEN r.FrlloType = 0 THEN null ELSE 0 END) 
                                            else r.FrlloType + 1
                                            end
        WHERE r.recipeid = v_recid;

    ELSE

        UPDATE rds.t_recipe_element r
        SET frllotype = case WHEN p_workwitherror = false THEN (CASE WHEN r.FrlloType = 0 THEN null ELSE 0 END) 
                                            else r.FrlloType + 1
                                            end
        FROM rds.t_export_frllo_recipe_data d
        WHERE r.recipeelementid = d.objid and d.exportfrllorecipedataid = p_exportfrllorecipedataid;

    END IF;
END;
$$