CREATE OR REPLACE PROCEDURE CONTCTBL_FORNECEDOR(
         P_CDEMPRESA IN EMPRESA.CDEMPRESA%TYPE,
         P_TIPOOPER IN TIPOOPERAC.CDTIPOOPER%TYPE,
	 P_IDENTRSAID IN VARCHAR2,
	 P_FILIAL IN FILIAL.CDFILIAL%TYPE,
	 P_FORNECED IN FORNECEDOR.CDFORNECED%TYPE,
         P_CDCONTCTBL OUT VARCHAR2,
         P_STCONTCTBLP OUT VARCHAR2,
         P_STCONTDIFE  OUT VARCHAR2,
         P_STCDHISTPADR 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
   BEGIN
     SELECT CDCONTTOPER,  CDCONTFORCLI, CDHISTPADR,  IDORIGDESTOP,
            CDCONTPCTBL,  CDCONTPFILI,  CDCONTPEMPR, CDCONTPROD,
            CDCONTDIFE
     INTO V_CDCONTTOPER, V_CDCONTFORCLI, V_CDHISTPADR, V_IDORIGDESTOP,
          V_CDCONTPCTBL, V_CDCONTPFILI, V_CDCONTPEMPR, V_CDCONTPROD,
          V_CDCONTDIFE
     FROM
      (SELECT MAX(CDCONTFORCLI) AS CDCONTTOPER, MAX(T.CDHISTPADR) AS CDHISTPADR, MAX(IDORIGDESTOP) AS IDORIGDESTOP,
              MAX(CDCONTPROD) AS CDCONTPROD 
         FROM TIPOOPERAC T
        WHERE CDTIPOOPER   = P_TIPOOPER
          AND IDENTRSAIDOP = P_IDENTRSAID) A,
      (SELECT F.CDCONTCTBL AS CDCONTFORCLI, CDCONTPCTBL,
              CDCONTPFILI, CDCONTPEMPR, '' AS CDCONTDIFE
         FROM FORNECEDOR F,
      (SELECT MAX(CDCONTFORN)  AS CDCONTPCTBL FROM PARAMCTBL)  PC,
      (SELECT MAX(CDCONFORNEM) AS CDCONTPEMPR FROM PARAMEMPRESA
        WHERE CDEMPRESA = P_CDEMPRESA)PE,
      (SELECT MAX(CDCONFORNFI) AS CDCONTPFILI FROM PARAMFILIAL
        WHERE CDFILIAL  = P_FILIAL) PF
     WHERE CDFORNECED   = P_FORNECED ) B;
   EXCEPTION
    WHEN NO_DATA_FOUND THEN
     V_CDCONTTOPER := NULL;
     V_CDCONTFORCLI := NULL;
     V_CDHISTPADR := NULL;
     V_IDORIGDESTOP := NULL;
     V_CDCONTPCTBL := NULL;
     V_CDCONTPFILI := NULL;
     V_CDCONTPEMPR := NULL;
     V_CDCONTPROD := NULL;   
     V_CDCONTDIFE := NULL;
   END;

   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_STCONTCTBLP := V_CDCONTPROD;

   P_STCDHISTPADR := V_CDHISTPADR; 

END;
/