IF EXISTS (SELECT * FROM SYSOBJECTS O, SYSUSERS U
            WHERE O.NAME = 'CTB_BONIFICACAO_DFS' AND
                  TYPE = 'FN'    		 AND
	          U.UID = O.UID                  AND
	          U.NAME = USER)

DROP FUNCTION CTB_BONIFICACAO_DFS
GO

CREATE FUNCTION CTB_BONIFICACAO_DFS(
   @P_CDFILIAL    VARCHAR(04),
   @P_NRLANCTONF  VARCHAR(10)) RETURNS VARCHAR(01)
AS
BEGIN
   DECLARE @V_CONTABILIZA   VARCHAR(1);

   SET @V_CONTABILIZA  = 'N';

      SELECT @V_CONTABILIZA = 'S'
        FROM IMPOSTONF IMP, NOTAFISCAL NF, IMPOSTO I, PARAMFILIAL PF,
             (SELECT DISTINCT CDIMPOSTO,
                              dbo.CONTCTBL_IMPOSTO(I.CDIMPOSTO, 'A', 'S', NF.CDTIPOOPER, NF.IDTPIJURNF) AS CDCONTATIV,
                              dbo.CONTCTBL_IMPOSTO(I.CDIMPOSTO, 'P', 'S', NF.CDTIPOOPER, NF.IDTPIJURNF) AS CDCONTPASS,
                              dbo.CONTCTBL_IMPOSTO(I.CDIMPOSTO, 'D', 'S', NF.CDTIPOOPER, NF.IDTPIJURNF) AS CDCONTDESP
                FROM IMPOSTONF I, NOTAFISCAL NF
               WHERE I.CDFILIAL   = NF.CDFILIAL
                 AND I.NRLANCTONF = NF.NRLANCTONF
                 AND I.CDFILIAL   = @P_CDFILIAL
                 AND I.NRLANCTONF = @P_NRLANCTONF) CT
       WHERE IMP.VRIMPOSTONF > 0          AND
             IMP.CDIMPOSTO = CT.CDIMPOSTO AND
             IMP.CDIMPOSTO = I.CDIMPOSTO  AND
             ((IMP.IDIMPOSTONF IN ('1','4')) OR (IMP.IDIMPOSTONF IS NULL)) AND
             I.IDTIPCONTAB  = 'D'         AND
             ((((I.IDIMPORECUP  = 'S'  AND IMP.CDFISCALNF = '1' AND PF.IDCARACFIS  = 'C') OR (PF.IDCARACFIS = 'A')) AND (CT.CDCONTPASS IS NOT NULL))
              OR
              ((I.IDIMPORECUP <> 'S') AND (CT.CDCONTPASS IS NOT NULL)))     AND
             NF.CDFILIAL     = @P_CDFILIAL      AND
             NF.NRLANCTONF   = @P_NRLANCTONF    AND
             NF.CDFILIEMIT   = PF.CDFILIAL    AND
             NF.CDFILIAL     = IMP.CDFILIAL   AND
             NF.NRLANCTONF   = IMP.NRLANCTONF
       GROUP BY 1;

   RETURN(@V_CONTABILIZA);
END
GO

-- VERSAO --
EXEC ATUVEROBJ 'CTB_BONIFICACAO_DFS','5.70.XXX';
GO