IF  EXISTS (
 SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[V_PDV_VD_CHQS]'))
DROP VIEW [dbo].[V_PDV_VD_CHQS]
GO
GO
GO


--SELECT ISNULL(SUM(VL_CHQ),0) AS VL_CHQ FROM V_PDV_VD_CHQS WHERE CD_EMP = 1 AND CD_FILIAL =9 AND DT_VD = '2007-12-14'
CREATE VIEW [dbo].[V_PDV_VD_CHQS] AS
SELECT     
	PDV_VD.CD_EMP, 
	PDV_VD.CD_FILIAL, 
	PDV_VD.CD_CX, 
	PDV_VD.CD_USU_OPE, 
	PDV_VD.DT_VD, 
	PDV_VD_CHQS.VL_CHQ,
	CASE WHEN CHQ_LANC_CPL.DT_VENCTO = CHQ_LANC_CPL.DT_EMI THEN
		0
	ELSE
		1
	END AS TIPO_VENCTO,
	0 AS TIPO_CHQ
FROM         
	PDV_VD INNER JOIN PDV_VD_CHQS ON 
	PDV_VD.CD_VD = PDV_VD_CHQS.CD_VD AND 
	PDV_VD.CD_FILIAL = PDV_VD_CHQS.CD_FILIAL AND 
    PDV_VD.CD_EMP = PDV_VD_CHQS.CD_EMP 
    INNER JOIN PDV_VD_CHQS_CHQ_LANC ON 
    PDV_VD_CHQS.CD_EMP = PDV_VD_CHQS_CHQ_LANC.CD_EMP AND 
    PDV_VD_CHQS.CD_FILIAL = PDV_VD_CHQS_CHQ_LANC.CD_FILIAL AND 
    PDV_VD_CHQS.CD_VD = PDV_VD_CHQS_CHQ_LANC.CD_VD AND 
    PDV_VD_CHQS.NR_ORD = PDV_VD_CHQS_CHQ_LANC.NR_ORD 
    INNER JOIN CHQ_LANC_CPL ON 
    PDV_VD_CHQS_CHQ_LANC.CD_EMP = CHQ_LANC_CPL.CD_EMP AND 
    PDV_VD_CHQS_CHQ_LANC.CD_CHQ = CHQ_LANC_CPL.CD_CHQ

WHERE     
	PDV_VD.ST_VD = 0
UNION ALL
SELECT     
	CHQ_LANC_CPL_RC_CARTAO_PROPRIO.CD_EMP, 
	CHQ_LANC_CPL_RC_CARTAO_PROPRIO.CD_FILIAL, 
	0 AS CD_CX, 
	0 AS CD_USU_OPE, 
	CHQ_LANC_CPL.DT_EMI, 
    CHQ_LANC_CPL.VLR_CHQ,
	CASE WHEN CHQ_LANC_CPL.DT_VENCTO = CHQ_LANC_CPL.DT_EMI THEN
		0
	ELSE
		1
	END AS TIPO_VENCTO,
	1 AS TIPO_CHQ
FROM         
	CHQ_LANC_CPL INNER JOIN CHQ_LANC_CPL_RC_CARTAO_PROPRIO ON 
	CHQ_LANC_CPL.CD_EMP = CHQ_LANC_CPL_RC_CARTAO_PROPRIO.CD_EMP AND 
    CHQ_LANC_CPL.CD_CHQ = CHQ_LANC_CPL_RC_CARTAO_PROPRIO.CD_CHQ

GO



