SET NOCOUNT ON

DECLARE @STR_EXEC VARCHAR(2000)

SET @STR_EXEC = 'CREATE '

IF EXISTS(
	SELECT 
		ID 
	FROM 
		SYSOBJECTS 
	WHERE 
		NAME = 'V_TELE_ORC_PENDENCIA' AND XTYPE = 'V')
BEGIN
	SET	@STR_EXEC = 'ALTER '
END

	SET @STR_EXEC = @STR_EXEC + 'VIEW [dbo].[V_TELE_ORC_PENDENCIA] AS  
			SELECT A.CD_FILIAL
				 , A.CD_ORC
				 , E.CD_PENDENCIA
				 , B.DTHR_ETAPA
				 , A.ENT_DTHR
				 , DATEDIFF(MINUTE, GETDATE(), A.ENT_DTHR) - F.SEPARACAO AS PRAZO
				 , E.DS_PENDENCIA  
			FROM dbo.TELE_ORC AS A INNER JOIN 
				 dbo.TELE_ORC_ETAPA AS B ON A.CD_ORC = B.CD_ORC AND A.CD_ORC_ETAPA = B.CD_ORC_ETAPA INNER JOIN 
				 dbo.TELE_ORC_ETAPA_PENDENCIA AS C ON B.CD_ORC_ETAPA = C.CD_ORC_ETAPA INNER JOIN 
				 dbo.TELE_PENDENCIA AS D ON C.CD_PENDENCIA = D.CD_PENDENCIA INNER JOIN 
				 dbo.TELE_TIPO_PENDENCIA AS E ON D.CD_TIPO_PENDENCIA = E.CD_PENDENCIA INNER JOIN 
				 dbo.V_TELE_TEMPO_ETAPA AS F ON A.CD_TIPO_ENTREGA = F.CD_TIPO_ENTREGA AND A.CD_FILIAL = F.CD_FILIAL
			WHERE A.CD_ETAPAS = 8 AND A.CD_TIPO = 0 '	
		
	EXEC (@STR_EXEC)