IF EXISTS(SELECT * FROM SYS.TRIGGERS WHERE OBJECT_ID=OBJECT_ID(N'[DBO].[TRG_PDV_VD_ULT_MOV]') )
	DROP TRIGGER [DBO].[TRG_PDV_VD_ULT_MOV];
GO

CREATE TRIGGER [DBO].[TRG_PDV_VD_ULT_MOV] ON [DBO].[PDV_VD]
FOR UPDATE
AS 
	
	IF CONTEXT_INFO() = 0X66666 
		RETURN;
		
IF  UPDATE (VLR_VD)       OR UPDATE (VLR_DINH) OR 
		UPDATE (VLR_CARTAO)   OR UPDATE (VLR_CONV) OR 
		UPDATE (VLR_DUP)      OR UPDATE (CD_USU) OR 
		UPDATE (DT_ULT_ALT)   OR UPDATE  (VLR_SAQUE_CARTAO) OR 
		UPDATE (QT_PARC_CONV) OR UPDATE (VLR_NCC) 
		
/*************************************************************************************************************************/
/*DADOS PARA PROCESSAMENTO DE INFORMACAO DE VENDAS NO REL. ANALISE MOVIMENTO DE VENDAS */
 
BEGIN
	DECLARE @EST_PROD_CPL_VD_LOTE_PROC_PENDENTE_CD_CTR TABLE (CD_CTR INT, CD_CTR_DT_MOVIMENTO INT);
 
	BEGIN
		INSERT INTO EST_PROD_CPL_VD_LOTE_PROC_PENDENTE( CD_CTR_DT_MOVIMENTO
														,DT_CAD
														,ANO
														,MES
														,ANO_MES
														,ROTINA)
		  OUTPUT INSERTED.CD_CTR , INSERTED.CD_CTR_DT_MOVIMENTO INTO @EST_PROD_CPL_VD_LOTE_PROC_PENDENTE_CD_CTR
		SELECT DISTINCT
			 GLB_DT_MOVIMENTO.CD_CTR_DT_MOVIMENTO
			,GETDATE()
			,GLB_DT_MOVIMENTO.ANO_MOVIMENTO
			,GLB_DT_MOVIMENTO.MES_MOVIMENTO
			,GLB_DT_MOVIMENTO.ANO_MES_MOVIMENTO
			,OBJECT_NAME(@@PROCID)
		FROM
			GLB_DT_MOVIMENTO
			INNER JOIN INSERTED I ON GLB_DT_MOVIMENTO.DT_MOVIMENTO = CONVERT (DATE ,I.DT_VD) 
		
		/*SET @CD_CTR=SCOPE_IDENTITY(); --IDENT_CURRENT('EST_PROD_CPL_VD_LOTE_PROC_PENDENTE'); */

		IF NOT EXISTS (SELECT 1 FROM @EST_PROD_CPL_VD_LOTE_PROC_PENDENTE_CD_CTR)
			RETURN;

		INSERT INTO EST_PROD_CPL_VD_LOTE_PROC_PRC_FILIAL(CD_CTR,CD_EMP,CD_FILIAL)
		SELECT DISTINCT
			 PEND.CD_CTR
			,I.CD_EMP
			,I.CD_FILIAL
		FROM
			INSERTED AS I 
			INNER JOIN GLB_DT_MOVIMENTO ON GLB_DT_MOVIMENTO.DT_MOVIMENTO =CONVERT (DATE ,I.DT_VD)
			INNER JOIN @EST_PROD_CPL_VD_LOTE_PROC_PENDENTE_CD_CTR PEND ON PEND.CD_CTR_DT_MOVIMENTO = GLB_DT_MOVIMENTO.CD_CTR_DT_MOVIMENTO 

/*
		INSERT INTO EST_PROD_CPL_VD_LOTE_PROC_EST_PROD(CD_CTR ,CD_EMP ,CD_PROD)
		SELECT DISTINCT
			    PEND.CD_CTR
			   ,I.CD_EMP
			   ,I.CD_PROD
		 FROM INSERTED AS I
			  INNER JOIN GLB_DT_MOVIMENTO ON GLB_DT_MOVIMENTO.DT_MOVIMENTO =CONVERT (DATE ,I.DT_VD)
		  	  INNER JOIN @EST_PROD_CPL_VD_LOTE_PROC_PENDENTE_CD_CTR PEND ON PEND.CD_CTR_DT_MOVIMENTO = GLB_DT_MOVIMENTO.CD_CTR_DT_MOVIMENTO
			  LEFT OUTER JOIN EST_PROD_CPL_VD_LOTE_PROC_EST_PROD ON I.CD_EMP=EST_PROD_CPL_VD_LOTE_PROC_EST_PROD.CD_EMP
															    AND I.CD_PROD=EST_PROD_CPL_VD_LOTE_PROC_EST_PROD.CD_PROD
															    AND PEND.CD_CTR=EST_PROD_CPL_VD_LOTE_PROC_EST_PROD.CD_CTR
		WHERE EST_PROD_CPL_VD_LOTE_PROC_EST_PROD.CD_PROD IS NULL;
*/
	END;
END;
  