
GO
IF EXISTS (SELECT * FROM SYS.TRIGGERS WHERE NAME = 'TRG_TELE_ORC_ALTERACAO_INCLUI_PENDENCIA')
begin
	DROP TRIGGER [dbo].[TRG_TELE_ORC_ALTERACAO_INCLUI_PENDENCIA]
end
go

CREATE TRIGGER [dbo].[TRG_TELE_ORC_ALTERACAO_INCLUI_PENDENCIA] ON [dbo].[TELE_ORC] FOR UPDATE AS
		IF UPDATE(CD_ORC_ETAPA) AND UPDATE(CD_ETAPAS) AND UPDATE(CD_TIPO)
		BEGIN
			RETURN
		END	
		--VALIDA SE REALMENTE  UM PEDIDO
		DECLARE @DTHR_ENTREGA DATETIME 
		SET @DTHR_ENTREGA  = (SELECT TOP 1 ENT_DTHR FROM INSERTED)
		--Exclui pendencia
		DELETE FROM TELE_ORC_PENDENCIA WHERE CD_ORC =(SELECT TOP 1 CD_ORC FROM INSERTED)
		--Pendncia de saida do pedido do televendas
		IF @DTHR_ENTREGA IS NOT NULL
		BEGIN
		INSERT INTO TELE_ORC_PENDENCIA (
				CD_ORC,
				CD_EMP, 
				CD_FILIAL)
			SELECT 
				CD_ORC,
				CD_EMP, 
				CD_FILIAL
			FROM 
				INSERTED p
			WHERE 
				NOT EXISTS (SELECT TOP 1
										CD_ORC 
								FROM 
									TELE_ORC_ETAPA_PDV_VD
								WHERE 
									p.CD_ORC=CD_ORC);
		END
GO

