IF  EXISTS (SELECT * FROM SYS.OBJECTS WHERE OBJECT_ID = OBJECT_ID(N'[DBO].[UFD_EST_PROD_IMP_LIBERACAO_VALOR_DISPONIVEL]') AND TYPE IN (N'FN', N'IF', N'TF', N'FS', N'FT'))
DROP FUNCTION [DBO].[UFD_EST_PROD_IMP_LIBERACAO_VALOR_DISPONIVEL]
GO 
--SELECT * FROM UFD_EST_PROD_IMP_LIBERACAO_VALOR_DISPONIVEL (1) 

CREATE FUNCTION [DBO].[UFD_EST_PROD_IMP_LIBERACAO_VALOR_DISPONIVEL] (  
					   @CD_USU INT)            
RETURNS @RSSALDO TABLE  (  
       TD_PRIV    INT,  
       VLR_SALDO   MONEY)  
AS  
BEGIN  
	DECLARE @VLR_AJUSTE_LIMITE MONEY
	DECLARE @VLR_AJUSTE_PENDENTE MONEY
	DECLARE @TD_PRIV INT
	DECLARE @VLR_AJUSTE_SALDO MONEY
	SET @VLR_AJUSTE_SALDO=0

	SELECT        
		TOP 1 @TD_PRIV=GLB_GRP_USU.TD_PRIV, 
		@VLR_AJUSTE_LIMITE=MAX(GLB_GRP_USU.VLR_MAX_AJUSTE) 
	FROM            
		GLB_GRP_USU INNER JOIN GLB_USU_GRP ON 
		GLB_GRP_USU.CD_GRP = GLB_USU_GRP.CD_GRP
	WHERE        
		GLB_USU_GRP.CD_USU = 1
	GROUP BY
		TD_PRIV
	ORDER BY
		2 DESC
		
	SELECT
		@VLR_AJUSTE_PENDENTE=SUM(QT_PROD*VLR_CUSTO)
	FROM
		EST_PROD_IMP_LIBERACAO_ALCADA_PENDENTE
	WHERE
		CD_USU=@CD_USU

	SET @VLR_AJUSTE_SALDO=0
	
	IF @TD_PRIV=0
	BEGIN
		SET @VLR_AJUSTE_SALDO=@VLR_AJUSTE_LIMITE-@VLR_AJUSTE_PENDENTE
	END

INSERT INTO @RSSALDO 
	SELECT
		@TD_PRIV,
		ISNULL(@VLR_AJUSTE_SALDO,0)
RETURN  
END