CREATE or REPLACE FUNCTION CTB_CCCLIENTE(
P_CDCLIENTE  IN NOTAFISCAL.CDCLIENTE%TYPE,
P_CDFILIEMIT IN NOTAFISCAL.CDFILIEMIT%TYPE,
P_CDEMPRESA  IN EMPRESA.CDEMPRESA%TYPE) RETURN VARCHAR2
AS
   V_CDCONTCTBL VARCHAR2(20);
BEGIN
  BEGIN
     SELECT CDCONTCTBL
       INTO V_CDCONTCTBL
       FROM CLIENTE
      WHERE CDCLIENTE = P_CDCLIENTE;
  EXCEPTION
     WHEN NO_DATA_FOUND THEN
        V_CDCONTCTBL := NULL;
  END;

  IF V_CDCONTCTBL IS NULL THEN
     BEGIN
        SELECT CDCONCLIEFI
          INTO V_CDCONTCTBL
          FROM PARAMFILIAL
         WHERE CDFILIAL = P_CDFILIEMIT;
     EXCEPTION
        WHEN NO_DATA_FOUND THEN
           V_CDCONTCTBL := NULL;
     END;
  END IF;

  IF V_CDCONTCTBL IS NULL THEN
     BEGIN
        SELECT CDCONCLIEEM
          INTO V_CDCONTCTBL
          FROM PARAMEMPRESA
         WHERE CDEMPRESA = P_CDEMPRESA;
     EXCEPTION
        WHEN NO_DATA_FOUND THEN
           V_CDCONTCTBL := NULL;
     END;
  END IF;

  IF V_CDCONTCTBL IS NULL THEN
     BEGIN
        SELECT CDCONTCLIE
          INTO V_CDCONTCTBL
          FROM PARAMCTBL;
     EXCEPTION
        WHEN NO_DATA_FOUND THEN
           V_CDCONTCTBL := NULL;
     END;
  END IF;


  RETURN V_CDCONTCTBL;
END;
/

-- VERSAO --
BEGIN ATUVEROBJ('CTB_CCCLIENTE','5.50.000'); END;
/