/****** Object:  StoredProcedure [dbo].[P_EST_PROD_CPL_VD_PROC_PENDENTE]    Script Date: 12/16/2013 10:52:22 ******/

IF EXISTS
(
	SELECT *
	FROM sys.objects
	WHERE object_id = OBJECT_ID(N'[dbo].[P_EST_PROD_CPL_VD_PROC_PENDENTE]')
		  AND type IN(N'P', N'PC')
)
	DROP PROCEDURE [dbo].[P_EST_PROD_CPL_VD_PROC_PENDENTE];
GO
GO
--EXEC P_EST_PROD_CPL_VD_PROC


CREATE PROCEDURE P_EST_PROD_CPL_VD_PROC_PENDENTE @CD_EMP    INT
											   , @CD_FILIAL INT
											   , @ANO       INT
											   , @MES       TINYINT
AS
	 SET NOCOUNT ON;

	 --declare  @ANO INT =2017, @MES TINYINT=5

	 DECLARE
			@dtVenda DATE;
	 SET @dtVenda = CONVERT(VARCHAR(10), (@ano * 100) + @mes)+'01';
	 PRINT 'Remocao de registros anteriores  '+CONVERT(VARCHAR(8), GETDATE(), 108);

	 DELETE FROM EST_PROD_CPL_VD_PROC_PENDENTE
	 WHERE CD_EMP = @CD_EMP
		   AND CD_FILIAL = @CD_FILIAL
		   AND DATEPART(YEAR, DT_VD) = @ANO
		   AND DATEPART(MONTH, DT_VD) = @MES;

	 PRINT 'Inserindo na pendencia  '+CONVERT(VARCHAR(10), @dtvenda, 112)+' Time '+CONVERT(VARCHAR(8), GETDATE(), 108);
	 INSERT INTO EST_PROD_CPL_VD_PROC_PENDENTE
		 (CD_EMP
		, CD_FILIAL
		, CD_PROD
		, DT_VD
		, DT_CAD
		 )
			SELECT CD_EMP
				 , CD_FILIAL
				 , CD_PROD
				 , @dtvenda DT_VD
				 , GETDATE() DT_CAD
			FROM EST_PROD_CPL
			WHERE CD_EMP = @CD_EMP
				  AND CD_FILIAL = @CD_FILIAL; 