/****** Object:  StoredProcedure [dbo].[P_EST_PROD_CRONO_CONTAGEM_EFET_PROC]    Script Date: 05/26/2013 14:55:53 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[P_EST_PROD_CRONO_CONTAGEM_EFET_PROC]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[P_EST_PROD_CRONO_CONTAGEM_EFET_PROC]
GO

CREATE PROCEDURE [dbo].[P_EST_PROD_CRONO_CONTAGEM_EFET_PROC] (@CD_EMP INT,
										   @CD_FILIAL INT,
										   @DT_CONTAGEM DATETIME) AS
BEGIN

CREATE TABLE #TBL_CONTAGEM (CD_PROC			INT,
							CD_FILIAL		INT,
							DT_CONTAGEM		DATETIME) 
							
INSERT INTO #TBL_CONTAGEM 
SELECT 
	DISTINCT 
	CD_PROC, 
	CD_FILIAL,
	DT_CONTAGEM
FROM 
	EST_PROD_CRONO_CONTAGEM_EFET_PROC 
WHERE 1 = 1
	AND STS_PROC = 0
	AND CD_EMP = @CD_EMP
	AND CD_FILIAL = @CD_FILIAL
	AND DT_CONTAGEM = @DT_CONTAGEM;

 UPDATE C
 SET  
	C.QT_EST_INIC		= (M.QT_EST+M.QT_SAI_NF+M.QT_SAI_PDV+M.QT_EST_IMP) -  M.QT_EST_ENT_NF  ,
	C.QT_EST_SAI_NF		= M.QT_SAI_NF,
	C.QT_EST_SAI_PDV	= M.QT_SAI_PDV,
	C.QT_EST_ENT_NF		= M.QT_EST_ENT_NF,
	C.QT_EST_IMP		= M.QT_EST_IMP,
	C.STS_PROC			= 1,
	C.QT_PEND_SAI		= M.QT_PEND_SAI,
	C.QT_PEND_ENT		= M.QT_PEND_ENT 
FROM
	(SELECT   
		M.CD_EMP,
		M.CD_FILIAL,
        M.CD_PROD,
        M.DT_MOV,
        ISNULL(SUM(M.QT_EST),0) AS QT_EST,
        ISNULL(SUM(M.QT_SAI_NF),0) AS QT_SAI_NF,
        ISNULL(SUM(M.QT_SAI_PDV),0) AS QT_SAI_PDV,
        ISNULL(SUM(M.QT_EST_ENT_NF),0) AS QT_EST_ENT_NF,
        ISNULL(SUM(M.QT_EST_IMP),0) As QT_EST_IMP,
        ISNULL(SUM(M.QT_PEND_SAI),0) As QT_PEND_SAI,
        ISNULL(SUM(M.QT_PEND_ENT),0) As QT_PEND_ENT
	FROM
		V_EST_PROD_CPL_MOVIMENTACAO M  
	WHERE
		M.CD_EMP=@CD_EMP
	GROUP BY  
		M.CD_EMP, 	  
		M.CD_FILIAL,
		M.DT_MOV,
		M.CD_PROD)  M
	INNER JOIN EST_PROD_CRONO_CONTAGEM_EFET_PROC C ON
	M.CD_PROD	= C.CD_PROD AND
	M.CD_EMP	= C.CD_EMP AND
	M.CD_FILIAL = C.CD_FILIAL
	INNER JOIN #TBL_CONTAGEM T ON 
	C.CD_PROC	= T.CD_PROC AND
	C.CD_FILIAL	= T.CD_FILIAL  
		
	AND M.CD_FILIAL	= T.CD_FILIAL  
	AND M.DT_MOV	>= T.DT_CONTAGEM
	
WHERE
	C.CD_EMP =@CD_EMP 
	AND C.STS_PROC = 0
	AND C.DT_CONTAGEM = @DT_CONTAGEM
	AND C.CD_FILIAL = @CD_FILIAL

END