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

CREATE FUNCTION UFD_EXP_CTB_MOV_BC_LANC_RECTA(@CD_EMP			INT,
											  @CD_FILIAL		INT,
											  @DT_INI			DATETIME,
											  @DT_FIM			DATETIME)		
RETURNS @RS_RETURN TABLE(
		CD_EMP					INT,
		CD_FILIAL				INT,
		VLR_RECTA				MONEY,
		CD_CNT					INT,
		CD_DESP_REC				INT, 
		DS_DESP_REC				VARCHAR(100), 
		HIST_LANC				VARCHAR(250), 
		DS_HIST					VARCHAR(150), 
		NR_CNT_DESP				VARCHAR(50),
		CD_CNT_CTB_RED_DESP		INT,
		CD_CTB_CNT_CONTA		VARCHAR(50),
		CD_CTB_CNT_RED_CONTA	INT,
		DT_LANCTO				DATETIME,
		CD_BC_LANC              INT,
		CD_TIPO_TRANSACAO		INT,
		CD_CONTROLE				INT) 
						
BEGIN       

	DECLARE @CD_GRP_ECON			INT
	
	SET @CD_GRP_ECON = (SELECT PRC_GRP_ECON_PRC_FILIAL.CD_GRP_ECON
						FROM PRC_FILIAL
							INNER JOIN PRC_GRP_ECON_PRC_FILIAL ON
								PRC_FILIAL.CD_EMP = PRC_GRP_ECON_PRC_FILIAL.CD_EMP AND 
								PRC_FILIAL.CD_FILIAL = PRC_GRP_ECON_PRC_FILIAL.CD_FILIAL
						WHERE
						    PRC_FILIAL.CD_EMP = @CD_EMP
						    AND PRC_FILIAL.CD_FILIAL = @CD_FILIAL
						    AND PRC_FILIAL.FILIAL_MTZ_GRP_ECON = 1)
	
	IF ISNULL(@CD_GRP_ECON,0) = 0 
		BEGIN
			RETURN
		END

	INSERT INTO @RS_RETURN 
	SELECT 
		A.CD_EMP,
		@CD_FILIAL AS CD_FILIAL,
		A.VLR_RECTA,
		A.CD_CNT,
		A.CD_DESP_REC, 
		A.DS_DESP_REC, 
		A.HIST_LANC, 
		A.DS_HIST, 
		A.NR_CNT_DESP,
		A.CD_CNT_CTB_RED_DESP,
		A.CD_CTB_CNT_CONTA,
		A.CD_CTB_CNT_RED_CONTA ,
		A.DT_LANCTO,
		A.CD_BC_LANC,
		A.CD_TIPO_TRANSACAO,
		A.CD_CONTROLE				
    FROM V_BC_LANC_CREDITOS_CONTABIL A 
		INNER JOIN (SELECT 
						 CD_CNT 
					FROM 
						 BC_CONTAS_PRC_GRP_ECON 
					WHERE 
						CD_EMP = @CD_EMP
						AND CD_GRP_ECON = @CD_GRP_ECON)  C ON
		A.CD_CNT = C.CD_CNT 
    
    WHERE 
		A.CD_EMP = @CD_EMP
		AND A.DT_LANCTO BETWEEN @DT_INI AND @DT_FIM 
    
    ORDER BY A.CD_CNT, A.CD_DESP_REC, A.DS_DESP_REC, A.HIST_LANC
    
   RETURN
    
END    