CREATE OR REPLACE PROCEDURE CONTCTBL_FILIAL(
         P_CDEMPRESA IN EMPRESA.CDEMPRESA%TYPE,
         P_TIPOOPER IN TIPOOPERAC.CDTIPOOPER%TYPE,
	 P_IDENTRSAID IN VARCHAR2,
	 P_CDFILIAL IN FILIAL.CDFILIAL%TYPE,
         P_CDCONTCTBL OUT VARCHAR2,
         P_CDCONTCTBLP OUT VARCHAR2,
         P_STCONTDIFE OUT VARCHAR2,
         P_CDHISTPADR OUT VARCHAR2)
IS
    V_CDCONTTOPER VARCHAR2(20);
    V_CDCONTFORCLI VARCHAR2(20);
    V_CDHISTPADR VARCHAR2(4);
    V_CDCONTPCTBL VARCHAR2(20);
    V_CDCONTPFILI VARCHAR2(20);
    V_CDCONTPEMPR VARCHAR2(20);
    V_CDCONTPROD VARCHAR2(20);
    V_CDCONTDIFE VARCHAR2(20);
    V_STCONTCTBL VARCHAR2(20);
    V_STCONTCTBLP VARCHAR2(20);
    V_STCDHISTPADR VARCHAR2(4);
    V_IDORIGDESTOP VARCHAR2(1);
BEGIN

    SELECT CDCONTTOPER,  CDCONTFORCLI, CDHISTPADR,  IDORIGDESTOP,
           CDCONTPCTBL,  TO_CHAR(CDCONTPFILI) CDCONTPFILI,
           TO_CHAR(CDCONTPEMPR) CDCONTPEMPR,
           TO_CHAR(CDCONTPROD) CDCONTPROD,
           TO_CHAR(CDCONTDIFE) CDCONTDIFE
    INTO V_CDCONTTOPER, V_CDCONTFORCLI, V_CDHISTPADR, V_IDORIGDESTOP,
         V_CDCONTPCTBL, V_CDCONTPFILI, V_CDCONTPEMPR, V_CDCONTPROD,
         V_CDCONTDIFE
    FROM
        (SELECT CDCONTFORCLI AS CDCONTTOPER, T.CDHISTPADR, IDORIGDESTOP,
                CDCONTPROD
         FROM TIPOOPERAC T
         WHERE CDTIPOOPER   = P_TIPOOPER 
         AND IDENTRSAIDOP = P_IDENTRSAID) A,

        (SELECT F.CDCONTCTBL AS CDCONTFORCLI,
                CDCONTPCTBL,
                NULL AS CDCONTPFILI,
                NULL AS CDCONTPEMPR,
                NULL AS CDCONTDIFE
         FROM FILIAL F,
              (SELECT MAX(CDCONTFORN)  AS CDCONTPCTBL FROM PARAMCTBL)  PC
               WHERE CDFILIAL = P_CDFILIAL ) B;
     
      IF V_CDCONTTOPER IS NOT NULL THEN
         P_CDCONTCTBL := V_CDCONTTOPER;
      ELSIF V_CDCONTFORCLI IS NOT NULL THEN
         P_CDCONTCTBL := V_CDCONTFORCLI;
      ELSIF V_CDCONTPFILI IS NOT NULL THEN
         P_CDCONTCTBL := V_CDCONTPFILI;
      ELSIF V_CDCONTPEMPR IS NOT NULL THEN
         P_CDCONTCTBL := V_CDCONTPEMPR; 
      ELSIF V_CDCONTPCTBL IS NOT NULL THEN
         P_CDCONTCTBL := V_CDCONTPCTBL;
      END IF;

      P_STCONTDIFE := V_CDCONTDIFE;
 
      P_CDCONTCTBLP := V_CDCONTPROD;

      P_CDHISTPADR := V_CDHISTPADR;

END;
/