IF OBJECT_ID('UFD_EXP_CTB_MOV_DOACAO') IS NOT NULL
	BEGIN
		DROP FUNCTION UFD_EXP_CTB_MOV_DOACAO
	END
	
GO	

   
CREATE FUNCTION UFD_EXP_CTB_MOV_DOACAO(    @CD_EMP  INT,  
             @CD_FILIAL INT,  
             @DT_INI  DATETIME,  
             @DT_FIM  DATETIME)    
  
RETURNS @RS_RETURN TABLE(  
  CD_EMP    INT,   
  CD_FILIAL   INT,     
  DT_CUPOM   DATETIME,      
  CD_ENTID	 INT,  
  NM_ENTID   VARCHAR(100),   
  CD_CTB_CNT   VARCHAR(100),   
  CD_CTB_CNT_RED  VARCHAR(100),   
  VLR_TOT_CUPOM  MONEY)   
AS  
BEGIN         
  
 INSERT INTO @RS_RETURN    
  SELECT   
   PDV_CUPOM_NAO_FISCAL.CD_EMP,  
   PDV_CUPOM_NAO_FISCAL.CD_FILIAL,  
   PDV_CUPOM_NAO_FISCAL.DT_CUPOM,  
   EST_ENTID_DOACAO.CD_ENTID,  
   EST_ENTID_DOACAO.NM_ENTID,   
   EST_ENTID_DOACAO.CD_CTB_CNT,   
   EST_ENTID_DOACAO.CD_CTB_CNT_RED,  
   SUM(PDV_CUPOM_NAO_FISCAL.VLR_TOT_CUPOM) AS VLR_TOT_CUPOM  
       
  FROM PDV_CUPOM_NAO_FISCAL   
   INNER JOIN PDV_CUPOM_NAO_FISCAL_EST_ENTID_DOACAO ON  
    PDV_CUPOM_NAO_FISCAL.CD_EMP = PDV_CUPOM_NAO_FISCAL_EST_ENTID_DOACAO.CD_EMP AND  
    PDV_CUPOM_NAO_FISCAL.CD_FILIAL = PDV_CUPOM_NAO_FISCAL_EST_ENTID_DOACAO.CD_FILIAL AND  
    PDV_CUPOM_NAO_FISCAL.CD_CTR = PDV_CUPOM_NAO_FISCAL_EST_ENTID_DOACAO.CD_CTR   
   INNER JOIN EST_ENTID_DOACAO ON   
    PDV_CUPOM_NAO_FISCAL_EST_ENTID_DOACAO.CD_EMP = EST_ENTID_DOACAO.CD_EMP AND  
    PDV_CUPOM_NAO_FISCAL_EST_ENTID_DOACAO.CD_ENTID = EST_ENTID_DOACAO.CD_ENTID  
       
  WHERE PDV_CUPOM_NAO_FISCAL.CD_EMP  = @CD_EMP  
   AND PDV_CUPOM_NAO_FISCAL.CD_FILIAL = @CD_FILIAL  
   AND PDV_CUPOM_NAO_FISCAL.DT_CUPOM BETWEEN @DT_INI AND @DT_FIM     
       
  GROUP BY   
   PDV_CUPOM_NAO_FISCAL.CD_EMP,  
   PDV_CUPOM_NAO_FISCAL.CD_FILIAL,  
   PDV_CUPOM_NAO_FISCAL.DT_CUPOM,  
   EST_ENTID_DOACAO.CD_ENTID,
   EST_ENTID_DOACAO.NM_ENTID,   
   EST_ENTID_DOACAO.CD_CTB_CNT,   
   EST_ENTID_DOACAO.CD_CTB_CNT_RED  
     
 RETURN    
      
END   