CREATE OR REPLACE FUNCTION BUSCA_FILIALDESTINO_PEDIDO_NF(
   P_CDFILIAL     IN FILIAL.CDFILIAL%TYPE,
   P_NRLANCTONF   IN NOTAFISCAL.NRLANCTONF%TYPE) RETURN VARCHAR2 IS

   V_CDFILIALDEST VARCHAR2(5000);
BEGIN  

   V_CDFILIALDEST := '';
   FOR C_FILIALDEST IN (SELECT DISTINCT P.CDFILIALPED
                          FROM NOTAFISCAL N, ITEMPRODUTO I, PEDIDO P
                         WHERE N.CDFILIAL = P_CDFILIAL
                           AND N.NRLANCTONF = P_NRLANCTONF
                           AND N.CDFILIAL = I.CDFILIAL
                           AND N.NRLANCTONF = I.NRLANCTONF
                           AND I.CDFILIALPED = P.CDFILIAL
                           AND I.NRPEDIDO = P.NRPEDIDO)
   LOOP
      IF (C_FILIALDEST.CDFILIALPED IS NOT NULL) THEN
         IF (V_CDFILIALDEST IS NOT NULL) THEN
            V_CDFILIALDEST := V_CDFILIALDEST ||'-'||C_FILIALDEST.CDFILIALPED;
         ELSE
            V_CDFILIALDEST := C_FILIALDEST.CDFILIALPED;
         END IF;   
         
      END IF;
   END LOOP;

   RETURN(V_CDFILIALDEST);
END;