CREATE OR REPLACE FUNCTION APS.RecalculateMKBTreeParams(
    p_ParentID UUID = NULL,
    p_Begin INT = 1,
    p_End OUT INT,
    p_Level INT = 0
)
AS
$$
DECLARE
    v_ChCount     INT;
    v_ID          UUID;
    v_NestedLevel INT;
BEGIN

    SELECT COUNT(*)
    INTO v_ChCount
    FROM APS.T_MKB m
    WHERE M.ParentID = p_ParentID;

    IF v_ChCount = 0 OR v_ChCount IS NULL
    THEN
        p_End := p_Begin + 1;
    ELSE
        v_NestedLevel := p_Level + 1;
        IF p_ParentID IS NULL
        THEN
            p_Begin := 1;
            FOR v_ID IN SELECT m.MkbID FROM APS.T_MKB m WHERE m.ParentID IS NULL ORDER BY m.MkbID
                LOOP
                    SELECT (SELECT * FROM APS.RecalculateMKBTreeParams(v_ID, p_Begin, v_NestedLevel)) INTO p_End;
                    UPDATE APS.T_MKB
                    SET
                        LeftIndex  = p_Begin,
                        RightIndex = p_End,
                        TreeLevel  = p_Level
                    WHERE
                        MkbID = v_ID;
                    p_Begin := p_End + 1;
                END LOOP;
        ELSE
            p_Begin := p_Begin + 1;
            FOR v_ID IN SELECT m.MkbID FROM APS.T_MKB m WHERE m.ParentID = p_ParentID ORDER BY m.MkbID
                LOOP
                    SELECT (SELECT * FROM APS.RecalculateMKBTreeParams(v_ID, p_Begin, v_NestedLevel)) INTO p_End;
                    UPDATE APS.T_MKB
                    SET
                        LeftIndex  = p_Begin,
                        RightIndex = p_End,
                        TreeLevel  = p_Level
                    WHERE
                        MkbID = v_ID;
                    p_Begin := p_End + 1;
                END LOOP;
        END IF;
        p_End := p_End + 1;
    END IF;
END;
$$ LANGUAGE plpgsql;