/****** Object:  View [dbo].[V_EST_NF_ENT_DANFE_PROVISORIO_CAB]    Script Date: 07/04/2013 16:59:30 ******/
IF  EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[V_EST_NF_ENT_DANFE_PROVISORIO_CAB]'))
DROP VIEW [dbo].[V_EST_NF_ENT_DANFE_PROVISORIO_CAB]
GO
GO
GO
GO
--SELECT  * FROM V_EST_NF_ENT_DANFE_PROVISORIO_CAB where CD_CTR =370
CREATE VIEW [dbo].[V_EST_NF_ENT_DANFE_PROVISORIO_CAB] AS
--Versao 2956
SELECT 
	E.CD_CTR,
	E.CD_EMP,
	E.CD_FILIAL,
	(CASE WHEN ISNULL(EST_NF_ENT_DANFE_PROVISORIO_FILIAIS.CD_FILIAL_ORIG,0)>0 THEN
		(CASE WHEN ISNULL(FLAG_GRP_ECON,0)=0 THEN
			P.CD_FORN
		ELSE			
			P.CD_FILIAL			
		END)
	ELSE
		E.CD_FORN
	END) CD_FORN,
	(CASE WHEN ISNULL(EST_NF_ENT_DANFE_PROVISORIO_FILIAIS.CD_FILIAL_ORIG,0)>0 THEN
		entFilial.NM_FANT			
	ELSE
		F.NM_FANT
	END) NM_FANT,
	E.NR_NF,
	E.VLR_NF,
	E.DT_EMIS_NF,
	E.DT_CAD,
	E.CD_PED_FORN,
	E.NR_AUTORIZADOR,
	ISNULL(FLAG_GRP_ECON,0) AS FLAG_GRP_ECON,
	CASE WHEN ISNULL(EST_NF_ENT_DANFE_PROVISORIO_FILIAIS.CD_FILIAL_ORIG,0)>0 THEN
		1
	ELSE
		0
	END XML_TRANSF,
	ISNULL(FLAG_LIBERA_ENTRADA_SEM_PEDIDO,0) AS FLAG_LIBERA_ENTRADA_SEM_PEDIDO,
	ISNULL(E.CD_MOV_OP,0) AS CD_MOV_OP
	,ISNULL(F.FLAG_BLQ_NF_ENT_CHECKIN,0) AS FLAG_BLQ_NF_ENT_CHECKIN
FROM 
	EST_NF_ENT_DANFE_PROVISORIO e
	INNER JOIN PG_FORN F ON 
	e.CD_EMP = F.CD_EMP AND
	e.CD_FORN= F.CD_FORN
	
	INNER JOIN PRC_FILIAL ON
	e.CD_EMP = PRC_FILIAL.CD_EMP AND
	e.CD_FILIAL = PRC_FILIAL.CD_FILIAL 
	LEFT OUTER JOIN EST_NF_ENT_DANFE_PROVISORIO_FILIAIS ON
	e.CD_CTR = EST_NF_ENT_DANFE_PROVISORIO_FILIAIS.CD_CTR 
	LEFT OUTER JOIN PRC_FILIAL entFilial ON
	e.CD_EMP = entFilial.CD_EMP AND
	EST_NF_ENT_DANFE_PROVISORIO_FILIAIS.CD_FILIAL_ORIG = entFilial.CD_FILIAL LEFT JOIN PRC_FILIAL_PG_FORN P ON 
	EST_NF_ENT_DANFE_PROVISORIO_FILIAIS.CD_FILIAL_ORIG = P.CD_FILIAL