/****** Object:  Trigger [dbo].[TRG_PDV_VD_AUDIT_CANCELAMENTO]    Script Date: 12/07/2016 10:46:25 ******/
IF  EXISTS (SELECT * FROM sys.triggers WHERE object_id = OBJECT_ID(N'[dbo].[TRG_PDV_VD_AUDIT_CANCELAMENTO]'))
 DROP TRIGGER TRG_PDV_VD_AUDIT_CANCELAMENTO
SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

CREATE TRIGGER [dbo].[TRG_PDV_VD_AUDIT_CANCELAMENTO] ON [dbo].[PDV_VD] AFTER  UPDATE
AS
BEGIN TRY
	IF UPDATE(ST_VD) 
	BEGIN
		INSERT INTO PDV_VD_AUDIT_CANCEL (CD_EMP,CD_FILIAL,CD_VD,CD_USU_ALT,DT_ALT,ST_VD) 
		SELECT       
			A.CD_EMP,
			A.CD_FILIAL,
			A.CD_VD,
			ISNULL(A.CD_USU,0) AS CD_USU_ALT, ---QDO CD_USU_ALT = 0 UPDATE VIA BANCO
			GETDATE() AS DT_ALT,
			A.ST_VD
		FROM       
		INSERTED A INNER JOIN PDV_VD C ON
			A.CD_EMP=C.CD_EMP AND
			A.CD_FILIAL=C.CD_FILIAL AND 
			A.CD_VD = C.CD_VD
	END

END TRY
BEGIN CATCH 
    declare @erro varchar (500) = ERROR_MESSAGE();
	INSERT INTO ADM_ERRO (numero, severidade, estado, rotina, linha, mensagem, dtErro)
		SELECT
			ERROR_NUMBER() AS numero,
			ERROR_SEVERITY() AS severidade,
			ERROR_STATE() AS estado,
			ERROR_PROCEDURE() AS rotina,
			ERROR_LINE() AS linha,
			ERROR_MESSAGE() AS mensagem,
			GETDATE() AS dtErro;	
			raiserror (@erro,16, 1)
END CATCH

GO

