create or replace FUNCTION BUSCA_NF_PEDIDO(
   P_CDFILIAL     IN FILIAL.CDFILIAL%TYPE,
   P_NRPEDIDO     IN PEDIDO.NRPEDIDO%TYPE) RETURN VARCHAR2 IS

   V_NRNOTAFISC NOTAFISCAL.NRNOTAFISC%TYPE;
   V_RESULT VARCHAR2(255);
BEGIN
   V_RESULT := '';
   FOR C_NOTAS IN (SELECT DISTINCT CDFILIAL, NRLANCTONF
                     FROM ITEMPRODUTO
                    WHERE CDFILIALPED = P_CDFILIAL
                      AND NRPEDIDO = P_NRPEDIDO)
   LOOP
      SELECT MAX(NRNOTAFISC)
        INTO V_NRNOTAFISC
        FROM NOTAFISCAL
       WHERE CDFILIAL = C_NOTAS.CDFILIAL
         AND NRLANCTONF = C_NOTAS.NRLANCTONF;
         V_RESULT := V_RESULT || V_NRNOTAFISC;
    END LOOP;
   RETURN(V_RESULT);
END;