IF EXISTS (SELECT * FROM SYS.TRIGGERS WHERE NAME = 'TRG_EST_PED_VD_INCLUI_PEND_WMS' )
BEGIN
	DROP TRIGGER TRG_EST_PED_VD_INCLUI_PEND_WMS
END

GO

CREATE TRIGGER [dbo].[TRG_EST_PED_VD_INCLUI_PEND_WMS] ON [dbo].[EST_PED_VD] FOR UPDATE AS      
IF UPDATE(STS_PED)
BEGIN      
	IF EXISTS (SELECT * FROM INSERTED WHERE STS_PED = 2)
	BEGIN
		INSERT INTO
			EST_WMS_SAI_EXCLUSAO (CD_PED_WMS, DT_CAD, APLIC)
		SELECT
			S.CD_PED_WMS,
			GETDATE() AS DT_CAD,
			0 AS APLIC
		FROM
			INSERTED I
			INNER JOIN EST_PROD_TRANSF_PED_VD T ON
				I.CD_EMP = T.CD_EMP
				AND I.CD_FILIAL = T.CD_FILIAL
				AND I.CD_PED = T.CD_PED
			INNER JOIN EST_PROD_TRANSF_EST_WMS_SAI S ON
				T.CD_EMP = S.CD_EMP
				AND T.CD_FILIAL = S.CD_FILIAL
				AND T.CD_CTR = S.CD_CTR
		WHERE
			NOT EXISTS (
				SELECT
					*
				FROM
					EST_WMS_SAI_EXCLUSAO
				WHERE
					CD_PED_WMS = S.CD_PED_WMS)
	END
END
