CREATE OR REPLACE FUNCTION MUNICIPIO_ISS
          (P_CDFILIAL    IN ITEMPRODUTO.CDFILIAL%TYPE,
           P_NRLANCTONF  IN ITEMPRODUTO.NRLANCTONF%TYPE) RETURN STRING
AS
   V_RESULT VARCHAR2(6);
BEGIN
   SELECT MAX(DECODE(M.CDMUNICIBGE, NULL, NVL(M.CDMUNICIPIO, ' '), TO_CHAR(TO_NUMBER(M.CDMUNICIBGE))))
   INTO V_RESULT
   FROM  IMPOSNFTOT I, ORIGDESTNF O, MUNICIPIO M
   WHERE I.CDFILIAL   = P_CDFILIAL    AND
         I.NRLANCTONF = P_NRLANCTONF  AND
         I.CDIMPOSTO  IN ('30', '31') AND
         I.CDFILIAL   = O.CDFILIAL    AND
         I.NRLANCTONF = O.NRLANCTONF  AND
         O.CDPAISORIG = M.CDPAIS      AND
         O.SGESTAORIG = M.SGESTADO    AND
         O.CDMUNIORIG = M.CDMUNICIPIO;
   RETURN(V_RESULT);
END;
/


