IF EXISTS( SELECT * FROM SYS.OBJECTS 
			WHERE NAME ='TRG_PDV_VD_GERAR_DUP_PENDENCIA'AND TYPE = 'TR')
BEGIN
	DROP TRIGGER [dbo].[TRG_PDV_VD_GERAR_DUP_PENDENCIA]
END
GO
GO
GO
CREATE TRIGGER [dbo].[TRG_PDV_VD_GERAR_DUP_PENDENCIA] ON [dbo].[PDV_VD] 
FOR INSERT,UPDATE
AS
BEGIN TRY
	DECLARE @CD_CLI INT

	--Deletando caso exista o registro
	DELETE 
		p
	FROM 
		PDV_VD_GERAR_DUP_PENDENCIA p INNER JOIN INSERTED I ON
		p.CD_EMP = i.CD_EMP AND
		p.CD_FILIAL = i.CD_FILIAL AND
		p.CD_VD = i.CD_VD
	--Fim

	IF EXISTS( SELECT 
					CD_EMP 
			   FROM 
					INSERTED 
				WHERE 
					VLR_DUP > 0
					AND ST_VD = 0)
		begin
			INSERT INTO PDV_VD_GERAR_DUP_PENDENCIA
			SELECT 
				i.CD_EMP,
				i.CD_FILIAL,
				i.CD_VD,
				GETDATE()
			FROM
				INSERTED i 
		end

	SET @CD_CLI = ISNULL((SELECT 
							TOP 1 VALOR 
						   FROM 
								PRC_FILIAL_CONFIG 
							WHERE 
								CD_EMP = 1 
								AND CD_CHAVE = 'CD_CLI_PADRAO'
								AND VALOR IN (SELECT CD_CLI FROM INSERTED)),0);
	IF @CD_CLI=0 
	begin
		SET @CD_CLI = ISNULL((SELECT VALOR FROM PRC_EMP_CONFIG WHERE CD_EMP = 1 AND CD_CHAVE = 'CD_CLI_PADRAO'),0)
	end

	INSERT INTO RC_CLI_ESTATIS_PENDENTE
	SELECT DISTINCT 
		i.CD_EMP,
		i.CD_CLI,
		GETDATE()
	FROM
		INSERTED i
		LEFT JOIN RC_CLI_ESTATIS_PENDENTE C ON
		i.CD_EMP = C.CD_EMP AND
		i.CD_CLI = C.CD_CLI
	WHERE
		i.CD_CLI <> @CD_CLI
		AND C.CD_EMP IS NULL

END TRY
BEGIN CATCH
	DECLARE @mensagemErro	varchar(250);
	DECLARE @severidadeErro int;
	DECLARE @estadoErro		int;

	SELECT	@mensagemErro	=  ERROR_MESSAGE(), 
		@severidadeErro = ERROR_SEVERITY(), 
		@estadoErro		= ERROR_STATE();
	 
	RAISERROR (@mensagemErro , @severidadeErro , @estadoErro ); 

END CATCH
GO


