IF NOT OBJECT_ID('TRG_PDV_CONSLD_VD_REPROCESSAR') IS NULL
	BEGIN 
		DROP TRIGGER TRG_PDV_CONSLD_VD_REPROCESSAR 
	END 
GO
CREATE TRIGGER [dbo].[TRG_PDV_CONSLD_VD_REPROCESSAR] ON [dbo].[PDV_CONSLD_VD] FOR  INSERT,UPDATE,DELETE AS
BEGIN
declare @sql_type     	char;
declare @insert_count 	int;
declare @delete_count 	int;


select @insert_count = count(*) from inserted;
select @delete_count = count(*) from deleted;

if @insert_count = 0 and @delete_count = 0
	return
if (@delete_count	=  0)
	set @sql_type	= 'I';
if (@delete_count 	>  0 and @insert_count > 0)
	set @sql_type 	= 'U';
if (@insert_count 	=  0)
	set @sql_type 	= 'D';

DELETE 
	c
FROM 
	PDV_CONSLD_VD_MOVIMENTO_REPROCESSAR c INNER JOIN INSERTED i ON
	c.CD_EMP = i.CD_EMP AND
	c.CD_FILIAL = i.CD_FILIAL AND
	c.DT_MOV = i.DT_MOV
	INSERT INTO PDV_CONSLD_VD_MOVIMENTO_REPROCESSAR
	SELECT
		DISTINCT
		i.CD_EMP,
		i.CD_FILIAL,
		i.DT_MOV,
		'CONSOLIDACAO',
		GETDATE()
	FROM
		INSERTED i 

IF @sql_type 	= 'U'
begin
	INSERT INTO PDV_CONSLD_VD_AUDITORIA
		(CD_EMP,    
		CD_FILIAL,  
		CD_CX,     
		DT_MOV,                 
		NR_CUPOM_INI, 
		NR_CUPOM_FIM,
		VLR_VD_LIQ,            
		CD_USU,      
		DT_CAD,                  
		DT_ULT_ALT,              
		ORIG,      
		DT_CONSLD,             
		VALIDADO,    
		VL_SERV,     
		VL_RECEB,
		DT_CAD_AUDITORIA,
		NM_ESTACAO_TRABALHO)
	SELECT
		d.CD_EMP,    
		d.CD_FILIAL,  
		d.CD_CX,     
		d.DT_MOV,                 
		d.NR_CUPOM_INI, 
		d.NR_CUPOM_FIM,
		d.VLR_VD_LIQ,            
		d.CD_USU,      
		d.DT_CAD,                  
		d.DT_ULT_ALT,              
		d.ORIG,      
		d.DT_CONSLD,             
		d.VALIDADO,    
		d.VL_SERV,     
		d.VL_RECEB,
		GETDATE(),
		d.NM_ESTACAO_TRABALHO
	FROM
		DELETED d INNER JOIN INSERTED i ON
		d.CD_EMP = i.CD_EMP AND
		d.CD_FILIAL = i.CD_FILIAL AND
		d.CD_CX = i.CD_CX AND
		d.DT_MOV = i.DT_MOV 
	WHERE
		(d.NR_CUPOM_INI <> i.NR_CUPOM_INI)
		OR (d.NR_CUPOM_FIM <> i.NR_CUPOM_FIM) 
		OR (d.VLR_VD_LIQ <> i.VLR_VD_LIQ)
		OR (d.ORIG <> i.ORIG)      
		OR (d.VALIDADO <> i.VALIDADO)    
		OR (d.VL_SERV <> i.VL_SERV)     
		OR (d.VL_RECEB <> i.VL_RECEB)
end

IF @sql_type 	= 'D'
begin
	INSERT INTO PDV_CONSLD_VD_AUDITORIA
		(CD_EMP,    
		CD_FILIAL,  
		CD_CX,     
		DT_MOV,                 
		NR_CUPOM_INI, 
		NR_CUPOM_FIM,
		VLR_VD_LIQ,            
		CD_USU,      
		DT_CAD,                  
		DT_ULT_ALT,              
		ORIG,      
		DT_CONSLD,             
		VALIDADO,    
		VL_SERV,     
		VL_RECEB,
		DT_CAD_AUDITORIA,
		NM_ESTACAO_TRABALHO)
	SELECT
		d.CD_EMP,    
		d.CD_FILIAL,  
		d.CD_CX,     
		d.DT_MOV,                 
		d.NR_CUPOM_INI, 
		d.NR_CUPOM_FIM,
		d.VLR_VD_LIQ,            
		d.CD_USU,      
		d.DT_CAD,                  
		d.DT_ULT_ALT,              
		d.ORIG,      
		d.DT_CONSLD,             
		d.VALIDADO,    
		d.VL_SERV,     
		d.VL_RECEB,
		GETDATE(),
		d.NM_ESTACAO_TRABALHO
	FROM
		DELETED d 
end

END

