IF OBJECT_ID('UFD_EXP_CTB_MOV_CARTAO') IS NOT NULL
	BEGIN
		DROP FUNCTION UFD_EXP_CTB_MOV_CARTAO
	END
	
GO 
   
  
CREATE FUNCTION UFD_EXP_CTB_MOV_CARTAO(@CD_EMP		INT,
									   @CD_FILIAL	INT,
									   @DT_INI		DATETIME,
									   @DT_FIM		DATETIME,
									   @TP_DEB_CRED INT)		

RETURNS @RS_RETURN TABLE(
		CD_EMP				INT, 
		CD_FILIAL			INT, 
		CD_CLI				INT, 
		DT_MOV				DATETIME, 
		VLR_CARTAO			MONEY, 
		NM_CARTAO			VARCHAR(100), 
		CD_CTB_CNT_RED		INT, 
		CD_CTB_CNT			VARCHAR(50), 
		VLR_SAQUE_CARTAO	MONEY, 
		TP_TRANSACAO		INT, 
		DS_TRANSACAO		VARCHAR(100),
		TP_DEB_CRED			INT)
AS
BEGIN
	
	--@TP_DEB_CRED
	-- 0 - Ambos
	-- 1 - DEBITO
	-- 2- CREDITO
	
	IF @TP_DEB_CRED IN (0,1)
		BEGIN
			INSERT INTO @RS_RETURN    
			SELECT 
				CD_EMP, 
				CD_FILIAL, 
				CD_CLI, 
				DT_MOV, 
				VLR_CARTAO, 
				NM_CARTAO, 
				CD_CTB_CNT_RED, 
				CD_CTB_CNT, 
				VLR_SAQUE_CARTAO, 
				TP_TRANSACAO, 
				DS_TRANSACAO,
				0 AS TP_DEB_CRED
			FROM V_PDV_VD_FECHA_RC_ADM_CARTAO_DEBITO_CONTABIL
			WHERE 
				CD_EMP			= @CD_EMP
				AND CD_FILIAL	= @CD_FILIAL 
				AND DT_MOV		BETWEEN @DT_INI AND @DT_FIM        
		END
	
	IF @TP_DEB_CRED IN (0,2)
		BEGIN
			INSERT INTO @RS_RETURN    
			SELECT 
				CD_EMP, 
				CD_FILIAL, 
				CD_CLI, 
				DT_MOV, 
				VLR_CARTAO, 
				NM_CARTAO, 
				CD_CTB_CNT_RED, 
				CD_CTB_CNT, 
				0 AS VLR_SAQUE_CARTAO, 
				0 AS TP_TRANSACAO, 
				'' AS DS_TRANSACAO,
				1 AS TP_DEB_CRED
			FROM V_PDV_VD_FECHA_RC_ADM_CARTAO_CREDITO_CONTABIL
			WHERE 
				CD_EMP			= @CD_EMP
				AND CD_FILIAL	= @CD_FILIAL 
				AND DT_MOV		BETWEEN @DT_INI AND @DT_FIM
		END
		
	RETURN
	
END			


    
    
    
    