CREATE OR REPLACE FUNCTION FCT_BUSCA_DESCRICAO_ESCOPO (
    P_NRTIPOORCAMENTO  IN  FCT_DESCAGRUPESCOPO.NRTIPOORCAMENTO%TYPE,
    P_IDTPFATURA       IN  FCT_DESCAGRUPESCOPO.IDTPFATURA%TYPE,
    P_CDFILIALFATURA   IN  FCT_DESCAGRUPESCOPO.CDFILIALFATURA%TYPE,
    P_NRPARCFATURA     IN  FCT_DESCAGRUPESCOPO.NRPARCFATURA%TYPE,
    P_CDTIPOOPERFATURA IN  FCT_DESCAGRUPESCOPO.CDTIPOOPERFATURA%TYPE,
    P_CDSERIENF        IN  FCT_DESCAGRUPESCOPO.CDSERIENF%TYPE,
    P_CDEMPRESA        IN  FCT_DESCAGRUPESCOPO.CDEMPRESA%TYPE,
    P_CDINSCESTA       IN  FCT_DESCAGRUPESCOPO.CDINSCESTA%TYPE,
    P_CDINSCMUNI       IN  FCT_DESCAGRUPESCOPO.CDINSCMUNI%TYPE,
    P_NRORG            IN  FCT_DESCAGRUPESCOPO.NRORG%TYPE
)
RETURN VARCHAR2
AS
    V_DESCRICAO FCT_DESCAGRUPESCOPO.DSNOMEAGRUPAMENTO%TYPE;
BEGIN

    BEGIN
        SELECT DSNOMEAGRUPAMENTO
          INTO V_DESCRICAO
          FROM (
              SELECT DSNOMEAGRUPAMENTO
                FROM FCT_DESCAGRUPESCOPO
               WHERE NRTIPOORCAMENTO = P_NRTIPOORCAMENTO
                 AND IDTPFATURA = P_IDTPFATURA
                 AND (CDFILIALFATURA = P_CDFILIALFATURA OR CDFILIALFATURA IS NULL)
                 AND (NRPARCFATURA = P_NRPARCFATURA OR NRPARCFATURA IS NULL)
                 AND (CDTIPOOPERFATURA = P_CDTIPOOPERFATURA OR CDTIPOOPERFATURA IS NULL)
                 AND (CDSERIENF = P_CDSERIENF OR CDSERIENF IS NULL)
                 AND (CDEMPRESA = P_CDEMPRESA OR CDEMPRESA IS NULL)
                 AND (CDINSCESTA = P_CDINSCESTA OR CDINSCESTA IS NULL)
                 AND (CDINSCMUNI = P_CDINSCMUNI OR CDINSCMUNI IS NULL)
                 AND (NRORG = P_NRORG OR NRORG IS NULL)
               ORDER BY NRTIPOORCAMENTO,
                        IDTPFATURA,
                        CDFILIALFATURA,
                        NRPARCFATURA,
                        CDTIPOOPERFATURA,
                        CDSERIENF,
                        CDEMPRESA,
                        CDINSCESTA,
                        CDINSCMUNI
          )
         WHERE ROWNUM = 1;
    EXCEPTION WHEN NO_DATA_FOUND THEN
        V_DESCRICAO := NULL;
    END;
      
    RETURN V_DESCRICAO;
    
END;