IF OBJECT_ID('V_PDV_VD_EST_NF_SAI') IS NOT NULL
	BEGIN
			DROP VIEW V_PDV_VD_EST_NF_SAI
	END

GO
CREATE VIEW V_PDV_VD_EST_NF_SAI
AS
SELECT
	PDV_VD_EST_NF_SAI.CD_EMP,
	PDV_VD_EST_NF_SAI.CD_FILIAL,
	PDV_VD_EST_NF_SAI.CD_VD,
	0 AS CD_PED,
	0 AS CD_FILIAL_PED,
	EST_NF_SAI.CD_NF,
	EST_NF_SAI.NF_NF,	
	EST_NF_SAI.DT_EMI_NF,
	EST_NF_SAI.HR_EMI_NF,
	EST_NF_SAI.VLR_NF,
	'' AS TIPO_ORIGEM,
	GLB_USU.NM_USU
FROM
	PDV_VD_EST_NF_SAI INNER JOIN EST_NF_SAI ON
	PDV_VD_EST_NF_SAI.CD_EMP = EST_NF_SAI.CD_EMP AND
	PDV_VD_EST_NF_SAI.CD_FILIAL = EST_NF_SAI.CD_FILIAL AND
	PDV_VD_EST_NF_SAI.CD_NF = EST_NF_SAI.CD_NF 
	INNER JOIN GLB_USU ON
	EST_NF_SAI.CD_USU = GLB_USU.CD_USU 	
UNION ALL
SELECT
	PDV_VD_EST_PED_VD_AGRUPAMENTO.CD_EMP,
	PDV_VD_EST_PED_VD_AGRUPAMENTO.CD_FILIAL_VD,
	PDV_VD_EST_PED_VD_AGRUPAMENTO.CD_VD,
	PDV_VD_EST_PED_VD_AGRUPAMENTO.CD_PED,
	PDV_VD_EST_PED_VD_AGRUPAMENTO.CD_FILIAL_PED, 
	ISNULL(EST_NF_SAI.CD_NF,0) AS CD_NF,
	ISNULL(EST_NF_SAI.NF_NF,0) AS NF_NF,
	EST_NF_SAI.DT_EMI_NF,
	EST_NF_SAI.HR_EMI_NF,
	EST_NF_SAI.VLR_NF,
	'AGRUPAMENTO' AS TIPO_ORIGEM,
	GLB_USU.NM_USU
FROM
	PDV_VD_EST_PED_VD_AGRUPAMENTO LEFT OUTER JOIN EST_NF_SAI_PED_VD ON
	PDV_VD_EST_PED_VD_AGRUPAMENTO.CD_EMP = EST_NF_SAI_PED_VD.CD_EMP AND
	PDV_VD_EST_PED_VD_AGRUPAMENTO.CD_FILIAL_PED = EST_NF_SAI_PED_VD.CD_FILIAL AND
	PDV_VD_EST_PED_VD_AGRUPAMENTO.CD_PED = EST_NF_SAI_PED_VD.CD_PED 
	LEFT OUTER 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 
	LEFT OUTER JOIN GLB_USU ON
	EST_NF_SAI.CD_USU = GLB_USU.CD_USU 



