 CREATE OR REPLACE FUNCTION CALCULA_QTDE_RESPOSTAS (
                   P_NRPROGRAMACAOPESQ IN  NUMBER,
                   P_NRQUESTAO IN NUMBER, 
                   P_NRRESPOSTA IN NUMBER,
                   P_DTINICIO IN VARCHAR2,
                   P_DTFIM IN DATE,
                   P_IDQTDE IN VARCHAR2
)RETURN NUMBER IS

V_QTDE NUMBER;

BEGIN 
    IF (P_IDQTDE = 'R') THEN
        BEGIN
           SELECT COUNT(RP.NRRESPOSTAPESQ) AS QTDE
             INTO V_QTDE
             FROM RESPOSTAPESQ RP INNER JOIN EXECUCAOPESQ EP
                  ON RP.NRORG = EP.NRORG AND RP.NREXECUCAOPESQ = EP.NREXECUCAOPESQ AND
                  EP.NRPROGRAMACAOPESQ = P_NRPROGRAMACAOPESQ AND
                  RP.NRRESPOSTA = P_NRRESPOSTA AND 
                  (TRUNC(EP.DTHRFIMPESQ) BETWEEN P_DTINICIO AND P_DTFIM);
        EXCEPTION
           WHEN NO_DATA_FOUND THEN
              V_QTDE := 0;
        END;               
    ELSE               
        BEGIN 
                SELECT COUNT(RP.QTDE) AS QTDE
                INTO V_QTDE
              FROM (SELECT RP.NRORG, NRQUESTAO, COUNT(RP.NRQUESTAO) AS QTDE, NREXECUCAOPESQ
                      FROM RESPOSTAPESQ RP
                     GROUP BY RP.NRORG, NRQUESTAO, RP.NREXECUCAOPESQ) RP INNER JOIN EXECUCAOPESQ EP
                ON RP.NRORG = EP.NRORG AND RP.NREXECUCAOPESQ = EP.NREXECUCAOPESQ AND
                   EP.NRPROGRAMACAOPESQ = P_NRPROGRAMACAOPESQ AND
                   RP.NRQUESTAO = P_NRQUESTAO AND 
                   (TRUNC(EP.DTHRFIMPESQ) BETWEEN P_DTINICIO AND P_DTFIM);
        EXCEPTION
           WHEN NO_DATA_FOUND THEN
              V_QTDE := 0;
        END;  
    END IF; 
    RETURN V_QTDE;
END;
/


-- VERSAO --
BEGIN ATUVEROBJ('CALCULA_QTDE_RESPOSTAS','6.25.000'); END;
/