/****** Object:  StoredProcedure [dbo].[P_EST_NF_SAI_CHECKIN_ENTRADA_AUTOMATICO]    Script Date: 02/27/2014 14:43:26 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[P_EST_NF_SAI_CHECKIN_ENTRADA_AUTOMATICO]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[P_EST_NF_SAI_CHECKIN_ENTRADA_AUTOMATICO]
GO
CREATE PROCEDURE P_EST_NF_SAI_CHECKIN_ENTRADA_AUTOMATICO @CD_EMP INT, 
														 @CD_FILIAL INT, 
														 @CD_NF INT 
with encryption 
AS
CREATE TABLE #NotaFiscal (CD_EMP INT,
						  CD_FILIAL INT,
						  CD_NF INT,
						  CD_USU INT,
						  DT_CAD DATETIME,
						  CHECKIN_DIVERGENCIA INT,
						  CD_PROD INT,
						  QT_IT_CHECK MONEY,
						  FLAG_ENTRADA_AUTOMATICA INT)

INSERT INTO #NotaFiscal
SELECT
	EST_NF_SAI.CD_EMP,
	EST_NF_SAI.CD_FILIAL,
	EST_NF_SAI.CD_NF,
	1,
	CONVERT(CHAR(10),GETDATE(),112),
	1,
	EST_NF_SAI_IT.CD_PROD,
	0,
	1
FROM
	EST_NF_SAI INNER JOIN EST_NF_SAI_PENDENCIA ON
	EST_NF_SAI.CD_EMP = EST_NF_SAI_PENDENCIA.CD_EMP AND 
	EST_NF_SAI.CD_FILIAL = EST_NF_SAI_PENDENCIA.CD_FILIAL AND
	EST_NF_SAI.CD_NF = EST_NF_SAI_PENDENCIA.CD_NF 
	INNER JOIN EST_NF_SAI_IT ON
	EST_NF_SAI.CD_EMP = EST_NF_SAI_IT.CD_EMP AND
	EST_NF_SAI.CD_FILIAL = EST_NF_SAI_IT.CD_FILIAL AND
	EST_NF_SAI.CD_NF = EST_NF_SAI_IT.CD_NF 
WHERE
	EST_NF_SAI.CD_EMP = @CD_EMP
	AND EST_NF_SAI.CD_FILIAL= @CD_FILIAL
	AND EST_NF_SAI.CD_NF= @CD_NF

INSERT INTO EST_NF_SAI_CHECKIN_ENTRADA
SELECT
	DISTINCT 
	CD_EMP,
	CD_FILIAL,
	CD_NF,
	CD_USU,
	DT_CAD,
	CHECKIN_DIVERGENCIA,
	FLAG_ENTRADA_AUTOMATICA
FROM
	#NotaFiscal

INSERT INTO EST_NF_SAI_CHECKIN_ENTRADA_CPL
SELECT 
	CD_EMP,
	CD_FILIAL,
	CD_NF,
	CD_PROD,
	QT_IT_CHECK
FROM
	#NotaFiscal

DROP TABLE #NotaFiscal