 
IF EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[V_RC_DEB_CLI_BLOQUEIO]'))
	DROP VIEW [dbo].[V_RC_DEB_CLI_BLOQUEIO]
GO
/****** Object:  View [dbo].[V_RC_DEB_CLI_BLOQUEIO]    Script Date: 10/06/2016 17:18:46 ******/
SET ANSI_NULLS ON 
GO 
SET QUOTED_IDENTIFIER ON 
GO 
CREATE VIEW [dbo].[V_RC_DEB_CLI_BLOQUEIO]
AS
	SELECT 
		dbo.RC_DEB.CD_CLI
		, 
		( CASE WHEN ISNULL(RC_CLI_CREDIARIO.DIAS_CAREN_BLOQ, 0) > 0 THEN DATEADD(DAY, RC_CLI_CREDIARIO.DIAS_CAREN_BLOQ, 
						CASE WHEN RC_DEB.DT_PRORROG IS NULL THEN RC_DEB.DT_VENCTO ELSE RC_DEB.DT_PRORROG END)
			 ELSE DATEADD(DAY, dbo.RC_MDL_VENDA.DIAS_BLOQ_ATRASO,  
							CASE WHEN RC_DEB.DT_PRORROG IS NULL THEN RC_DEB.DT_VENCTO ELSE RC_DEB.DT_PRORROG END)
			 END )   AS DT_LIMITE
		,CONVERT(dATE,GETDATE()) AS DT_ATUAL
	FROM
		dbo.RC_DEB
		INNER JOIN dbo.RC_CLI_CREDIARIO ON
			dbo.RC_DEB.CD_EMP = dbo.RC_CLI_CREDIARIO.CD_EMP AND
			dbo.RC_DEB.CD_CLI = dbo.RC_CLI_CREDIARIO.CD_CLI
		INNER JOIN dbo.RC_MDL_VENDA ON
			dbo.RC_MDL_VENDA.CD_EMP = dbo.RC_CLI_CREDIARIO.CD_EMP AND
			dbo.RC_MDL_VENDA.CD_MDL_VD = dbo.RC_CLI_CREDIARIO.CD_MDL_VD
	     LEFT JOIN RC_DEB_PAG ON 
		  dbo.RC_DEB.CD_EMP=dbo.RC_DEB_PAG.CD_EMP AND
		  dbo.RC_DEB.CD_FILIAL=dbo.RC_DEB_PAG.CD_FILIAL AND
		  dbo.RC_DEB.CD_RC_DEB=dbo.RC_DEB_PAG.CD_RC_DEB
	WHERE
		( dbo.RC_DEB.CD_EMP = 1 ) AND
		( dbo.RC_DEB.STS_DP IN ( 0, 2 ) ) AND
		( dbo.RC_DEB.SLD_DP > 0 ) AND
		( dbo.RC_DEB_PAG.CD_EMP IS NULL)

GO

GO 
