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

GO 

CREATE FUNCTION BUSCA_EST_NF_ENT_IT_QT_DEV_LOTE(@CD_EMP		INT,
											@CD_FILIAL  INT,
											@CD_NF_ENT	INT,
											@CD_PROD	INT,
											@CD_LOTE	INT)
RETURNS MONEY 
AS
	BEGIN											
		DECLARE @QT_DEV MONEY 
			
		SET @QT_DEV = 								
			(SELECT ISNULL(SUM(EST_NF_SAI_IT_EST_PROD_CPL_LOTE.QTDE_PROD),0) AS QTDE_PROD
				FROM EST_NF_SAI 
				  INNER JOIN EST_NF_ENT_NF_SAI ON 
						EST_NF_SAI.CD_EMP = dbo.EST_NF_ENT_NF_SAI.CD_EMP AND
						EST_NF_SAI.CD_FILIAL = dbo.EST_NF_ENT_NF_SAI.CD_FILIAL And 
						dbo.EST_NF_SAI.Cd_Nf = dbo.EST_NF_ENT_NF_SAI.Cd_Nf_Sai
				  INNER JOIN GLB_MOV_OP ON
						EST_NF_SAI.Cd_Nt_Mov = GLB_MOV_OP.Cd_Mov_Op
				  Inner Join dbo.EST_NF_SAI_IT ON 
						dbo.EST_NF_SAI.CD_EMP = dbo.EST_NF_SAI_IT.CD_EMP AND
						dbo.EST_NF_SAI.CD_FILIAL = dbo.EST_NF_SAI_IT.CD_FILIAL And 
						dbo.EST_NF_SAI.Cd_Nf = dbo.EST_NF_SAI_IT.Cd_Nf
				  INNER JOIN EST_NF_SAI_IT_EST_PROD_CPL_LOTE  ON
						EST_NF_SAI_IT.CD_EMP  = EST_NF_SAI_IT_EST_PROD_CPL_LOTE.CD_EMP AND
						EST_NF_SAI_IT.CD_FILIAL  = EST_NF_SAI_IT_EST_PROD_CPL_LOTE.CD_FILIAL AND
						EST_NF_SAI_IT.CD_NF  = EST_NF_SAI_IT_EST_PROD_CPL_LOTE.CD_NF AND
						EST_NF_SAI_IT.CD_PROD = EST_NF_SAI_IT_EST_PROD_CPL_LOTE.CD_PROD
			    
				WHERE EST_NF_ENT_NF_SAI.CD_EMP =  @CD_EMP
				  AND EST_NF_ENT_NF_SAI.CD_FILIAL =  @CD_FILIAL
				  AND EST_NF_ENT_NF_SAI.CD_NF_ENT =  @CD_NF_ENT
				  AND GLB_MOV_OP.TP_MOV = 11 
				  AND EST_NF_SAI.STS_NF = 0 
				  AND EST_NF_SAI_IT_EST_PROD_CPL_LOTE.CD_PROD = @CD_PROD   
				  AND EST_NF_SAI_IT_EST_PROD_CPL_LOTE.CD_LOTE = @CD_LOTE)
				  
	
		RETURN @QT_DEV
				  
	END