CREATE OR REPLACE FUNCTION RETORNA_AGLU_ANT(P_CDTIPODEMO IN VARCHAR,
                                            P_CDITEMSTRU IN VARCHAR) RETURN VARCHAR
AS
   V_IDGRUPOBALSPED VARCHAR2(01);
   V_CDNIVELITEM VARCHAR2(01);
   V_CDITEMTEMP VARCHAR2(04);
   V_RESULT VARCHAR2(50);
BEGIN
   BEGIN
      SELECT IDGRUPOBALSPED, CDNIVELITDEMOF
        INTO V_IDGRUPOBALSPED, V_CDNIVELITEM
        FROM ITEMDEMOF I
       WHERE CDTIPODEMO = P_CDTIPODEMO
         AND CDITEMSTRU = P_CDITEMSTRU;
   EXCEPTION
      WHEN NO_DATA_FOUND THEN
         V_IDGRUPOBALSPED := NULL;
   END;
   SELECT MAX(CDITEMSTRU)
     INTO V_CDITEMTEMP
     FROM ITEMDEMOF I
    WHERE CDTIPODEMO = P_CDTIPODEMO
      AND CDITEMSTRU < P_CDITEMSTRU
      AND IDGRUPOBALSPED = V_IDGRUPOBALSPED
      AND TO_NUMBER(CDNIVELITDEMOF) < TO_NUMBER(V_CDNIVELITEM);
   IF V_CDITEMTEMP IS NOT NULL THEN
      SELECT T.IDREFESPED||I.IDGRUPOBALSPED||I.CDITEMSTRU
        INTO V_RESULT
        FROM TIPODEMO T, ITEMDEMOF I
       WHERE T.CDTIPODEMO = P_CDTIPODEMO
         AND T.CDTIPODEMO = I.CDTIPODEMO
         AND I.CDITEMSTRU = V_CDITEMTEMP;
   ELSE
      V_RESULT := NULL;
   END IF;
   RETURN V_RESULT;
END;
/