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

--------------------------------------INSERÇÃO EM TELE_ORC--------------------------------------
CREATE TRIGGER [dbo].[TRG_TELE_ORC_INCLUI_PENDENCIA] ON [dbo].[TELE_ORC] FOR INSERT AS


DECLARE @DTHR_ENTREGA DATETIME 
SET @DTHR_ENTREGA  = (SELECT ENT_DTHR FROM INSERTED)

--Pendência 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 
							* 
						FROM 
							TELE_ORC_ETAPA_PDV_VD
						WHERE 
							p.CD_ORC=CD_ORC);
END
GO



