--SELECT DBO.UFD_RC_ADM_CARTAO_MOV_SLD_FILIAL(150872,1,'2008-12-31', 1)  
ALTER FUNCTION [dbo].[UFD_RC_ADM_CARTAO_MOV_SLD_FILIAL](  
              @CD_FILIAL INT,  
              @CD_CLI  INT,  
              @CD_GRP_ECON  INT,  
              @DT_INI  DATETIME,  
              @TP_DATA      INT,
              @MODALIDADE INT)  
RETURNS MONEY  
AS  
BEGIN  
DECLARE @VLR_SLD_ANT MONEY  
IF @TP_DATA = 0
BEGIN
SELECT   
 @VLR_SLD_ANT = isnull(SUM(VLR_DEB),0) - ISNULL(SUM(VLR_CRED),0)  
FROM   
(  
SELECT     
 CASE WHEN TP_LANC = 0 THEN VLR_LANC ELSE 0 END AS VLR_CRED,  
 CASE WHEN TP_LANC = 1 THEN VLR_LANC ELSE 0 END  AS VLR_DEB
FROM           
 RC_ADM_CARTAO_MOV  
WHERE   
 CD_EMP=1
 AND CD_FILIAL = @CD_FILIAL  
 AND CD_CLI = @CD_CLI       
 AND CD_GRP_ECON=@CD_GRP_ECON 
 AND RC_ADM_CARTAO_MOV.DT_LANC < @DT_INI
 AND RC_ADM_CARTAO_MOV.MODALIDADE=@MODALIDADE) s  
END
ELSE
BEGIN
SELECT   
 @VLR_SLD_ANT = isnull(SUM(VLR_DEB),0) - ISNULL(SUM(VLR_CRED),0)  
FROM   
(  
SELECT     
 CASE WHEN TP_LANC = 0 THEN VLR_LANC ELSE 0 END AS VLR_CRED,  
 CASE WHEN TP_LANC = 1 THEN VLR_LANC ELSE 0 END  AS VLR_DEB
FROM           
 RC_ADM_CARTAO_MOV  
WHERE   
 CD_EMP=1	
 AND CD_FILIAL = @CD_FILIAL  
 AND CD_CLI = @CD_CLI       
 AND CD_GRP_ECON=@CD_GRP_ECON 
 AND RC_ADM_CARTAO_MOV.DT_VENCTO < @DT_INI
 AND RC_ADM_CARTAO_MOV.MODALIDADE=@MODALIDADE) s  

END
RETURN(@VLR_SLD_ANT)  
END

