IF OBJECT_ID('fnGetUtkozesByTanar') IS NOT NULL BEGIN
  DROP FUNCTION fnGetUtkozesByTanar
END
GO

CREATE FUNCTION [fnGetUtkozesByTanar] (
  @startTime datetime, 
  @endTime datetime,
  @tanarId int,
  @intezmenyId int,
  @tanevId int
) RETURNS TABLE 
RETURN (
  SELECT o.ID AS OrarendiOraId, NULL AS TanitasiOraId
  FROM T_NAPTARINAP_OSSZES n
    LEFT JOIN T_TANEVRENDJE_OSSZES tr ON tr.C_DATUM = n.C_NAPDATUMA 
    INNER JOIN T_ORARENDIORA_OSSZES o ON (ISNULL(tr.C_HETIREND, n.C_HETIREND) = o.C_HETIREND OR o.C_HETIREND = 1554) 
      AND ISNULL(tr.C_HETNAPJA, n.C_HETNAPJA) = o.C_HETNAPJA 
      AND n.C_INTEZMENYID = o.C_INTEZMENYID 
      AND n.C_TANEVID = o.C_TANEVID
    LEFT JOIN T_CSENGETESIRENDORA csro ON csro.ID = o.C_CSENGETESIRENDORAID 
      AND o.C_ORASZAM = csro.C_ORASZAM  
  WHERE CAST(CAST(@startTime AS DATE) AS DATETIME) + CAST(CAST(ISNULL(csro.C_KEZDETE, o.C_ORAKEZDETE) AS TIME) AS DATETIME) < @endTime 
    AND CAST(CAST(@endTime AS DATE) AS DATETIME) + CAST(CAST(ISNULL(csro.C_VEGE   , o.C_ORAVEGE)    AS TIME) AS DATETIME) > @startTime
    AND o.C_TANARID = @tanarId
    AND n.C_TANEVID = @tanevId 
    AND n.C_INTEZMENYID = @intezmenyId
    AND n.C_NAPDATUMA >= CAST(@startTime AS DATE) AND n.C_NAPDATUMA <= CAST(@endTime AS DATE)
    AND n.TOROLT = 'F' AND (tr.TOROLT = 'F' OR tr.TOROLT IS NULL) AND o.TOROLT = 'F' and o.C_PARHUZAMOSORA = 'F'
    AND o.C_ORAERVENYESSEGKEZDETE <= CAST(@endTime AS DATE) AND o.C_ORAERVENYESSEGVEGE >= CAST(@startTime AS DATE)
  
  UNION 
  
  SELECT o.ID AS OrarendiOraId, tn.ID AS TanitasioraId
  FROM T_TANITASIORA_OSSZES tn
    LEFT JOIN T_ORARENDIORA o ON o.ID = tn.C_ORARENDIORAID
  WHERE tn.C_ORAKEZDETE <= @endTime
    AND tn.C_ORAVEGE >= @startTime
    AND ISNULL(tn.C_HELYETTESITOTANARID, tn.C_ORATULAJDONOSID) = @tanarId
    AND tn.C_TANEVID = @tanevId
    AND tn.C_INTEZMENYID = @intezmenyId
    AND tn.TOROLT = 'F' and tn.C_PARHUZAMOSORA = 'F'
);
GO
