SET NOCOUNT ON

DECLARE @STR_EXEC VARCHAR(2000)

SET @STR_EXEC = 'CREATE '

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

	SET @STR_EXEC = @STR_EXEC + 'VIEW dbo.V_TELE_ORC_PENDENCIA_RESOLUCAO AS  
			SELECT A.CD_FILIAL
				 , A.CD_ORC
				 , D.CD_PENDENCIA
				 , B.DTHR_ETAPA
				 , A.ENT_DTHR
				 , DATEDIFF(HOUR, GETDATE(), A.ENT_DTHR) - F.SEPARACAO AS PRAZO
				 , E.NM_USU  
			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 D ON D.CD_ORC_ETAPA =  (SELECT MAX(CD_ORC_ETAPA) FROM TELE_ORC_ETAPA WHERE CD_ETAPAS = 8 AND CD_TIPO = 0 AND CD_ORC = A.CD_ORC)  INNER JOIN  
				 dbo.GLB_USU AS E ON B.CD_USU = E.CD_USU 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 = 1) '	
		
	EXEC (@STR_EXEC)