IF EXISTS ( SELECT * FROM SYS.TRIGGERS WHERE NAME ='TRG_EST_NF_SAI_NFE_PDV_VD_CONF_MERCK' )
BEGIN 
	DROP TRIGGER [TRG_EST_NF_SAI_NFE_PDV_VD_CONF_MERCK]
END 
GO 
CREATE TRIGGER [DBO].[TRG_EST_NF_SAI_NFE_PDV_VD_CONF_MERCK] ON [DBO].[EST_NF_SAI_NFE]
FOR INSERT
AS

INSERT INTO PDV_VD_CONF_MERCK
(CD_EMP
,CD_FILIAL
,CD_VD
,STS_ENVIO
,TIPO_DOC)

--TIPO DOC
--0 - CUPOM FISCAL
--1 - NOTA FISCAL

SELECT
EST_NF_SAI.CD_EMP,
EST_NF_SAI.CD_FILIAL,
EST_NF_SAI.CD_NF,
0,
1
FROM
TELE_ORC INNER JOIN TELE_ORC_EST_PED_VD ON
TELE_ORC.CD_ORC=TELE_ORC_EST_PED_VD.CD_ORC INNER JOIN EST_PED_VD ON
TELE_ORC_EST_PED_VD.CD_EMP=EST_PED_VD.CD_EMP AND
TELE_ORC_EST_PED_VD.CD_FILIAL=EST_PED_VD.CD_FILIAL AND
TELE_ORC_EST_PED_VD.CD_PED=EST_PED_VD.CD_PED
INNER JOIN EST_NF_SAI_PED_VD ON
EST_PED_VD.CD_EMP=EST_NF_SAI_PED_VD.CD_EMP AND
EST_PED_VD.CD_FILIAL=EST_NF_SAI_PED_VD.CD_FILIAL AND
EST_PED_VD.CD_PED=EST_NF_SAI_PED_VD.CD_PED INNER JOIN EST_NF_SAI ON
EST_NF_SAI_PED_VD.CD_EMP=EST_NF_SAI.CD_EMP AND
EST_NF_SAI_PED_VD.CD_FILIAL=EST_NF_SAI.CD_FILIAL AND
EST_NF_SAI_PED_VD.CD_NF=EST_NF_SAI.CD_NF INNER JOIN GLB_USU ON
TELE_ORC.CD_USU=GLB_USU.CD_USU INNER JOIN INSERTED I ON
EST_NF_SAI.CD_EMP=I.CD_EMP AND
EST_NF_SAI.CD_FILIAL=I.CD_FILIAL AND
EST_NF_SAI.CD_NF=I.CD_NF

WHERE
NOT EXISTS (SELECT CD_EMP FROM PDV_VD_CONF_MERCK WHERE CD_EMP=I.CD_EMP AND CD_FILIAL=I.CD_FILIAL AND CD_VD=I.CD_NF AND TIPO_DOC=1)
AND TELE_ORC.PROTOCOLO_MERCK IS NOT NULL