IF  EXISTS (SELECT 1 FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].V_EDELIVERY_EST_PROD_SYNC'))
DROP VIEW [dbo].V_EDELIVERY_EST_PROD_SYNC
GO
CREATE VIEW V_EDELIVERY_EST_PROD_SYNC AS

	SELECT EST_PROD_CPL.CD_EMP, EST_PROD_CPL.CD_FILIAL,  EST_PROD_CPL.CD_PROD, EST_PROD.STS_PROD, EST_PROD_CPL.QT_EST, EST_PROD_PRECO.VLR_TABELA, EST_PROD_PRECO.VLR_OFERTA, EST_PROD_CPL.TP_PROD, EDELIVERY_EST_PROD_SINC.DT_ULT_ALT
	FROM 
		EST_PROD_CPL
		INNER JOIN EST_PROD_PRECO ON
			EST_PROD_CPL.CD_PROD = EST_PROD_PRECO.CD_PROD 
			AND EST_PROD_CPL.CD_FILIAL = EST_PROD_PRECO.CD_FILIAL
		INNER JOIN EST_PROD ON
			EST_PROD.CD_PROD = EST_PROD_CPL.CD_PROD
		INNER JOIN EDELIVERY_EST_PROD_SINC ON
			EDELIVERY_EST_PROD_SINC.CD_FILIAL = EST_PROD_CPL.CD_FILIAL
			AND EDELIVERY_EST_PROD_SINC.CD_PROD = EST_PROD_CPL.CD_PROD
		LEFT JOIN EDELIVERY_PRODUTO EP ON
			EP.COD_PROD = EDELIVERY_EST_PROD_SINC.CD_PROD
			AND EP.CD_FILIAL = EDELIVERY_EST_PROD_SINC.CD_FILIAL
		INNER JOIN EDELIVERY_CONFIGURACAO ON
			EDELIVERY_CONFIGURACAO.CD_EMP = EST_PROD_CPL.CD_EMP 
			AND EDELIVERY_CONFIGURACAO.CD_FILIAL = EST_PROD_CPL.CD_FILIAL
	WHERE 
		EDELIVERY_EST_PROD_SINC.DT_ULT_ALT > EDELIVERY_CONFIGURACAO.DATA_HORA_ENVIO_CARGA 
		AND (EDELIVERY_EST_PROD_SINC.DT_ULT_ALT > EP.DATA_HORA_ULT_ENVIO
			OR EP.DATA_HORA_ULT_ENVIO IS NULL);