SET NOCOUNT ON

DECLARE @STR_EXEC VARCHAR(2000)

SET @STR_EXEC = 'CREATE '

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

	SET @STR_EXEC = @STR_EXEC + 'VIEW dbo.V_TELE_ORC_EM_CHECK_OUT
			AS
			SELECT  A.CD_FILIAL
				  , A.CD_ORC
				  , A.DTHR_PEDIDO
				  , A.ENT_DTHR, DATEDIFF(minute, GETDATE(), A.ENT_DTHR) - D.SEPARACAO AS PRAZO
				  , C.NM_USU
				  , C.CD_USU, A.PROD_CONTROLADO
			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.GLB_USU AS C ON B.CD_USU = C.CD_USU INNER JOIN
				  dbo.V_TELE_TEMPO_ETAPA AS D ON A.CD_TIPO_ENTREGA = D.CD_TIPO_ENTREGA AND A.CD_FILIAL = D.CD_FILIAL
			WHERE (A.CD_ETAPAS = 2) AND (A.CD_TIPO = 1) '	
		
	EXEC (@STR_EXEC)