DROP PROCEDURE IF EXISTS [dbo].[uspGetOralatogatasok]
GO

CREATE PROCEDURE [dbo].[uspGetOralatogatasok]
  @pIntezmenyId int,
  @pTanevId int,
  @pIdoszakKezdete datetime,
  @pIdoszakVege datetime,
  @pTanarId int
AS
BEGIN
  SET NOCOUNT ON;

  SELECT
    tao.Id AS Id
    ,tao.C_Orarendioraid AS Orarendiid
    ,tao.C_Bontott AS Bontott
    ,nn.C_Hetirend AS Hetirend
    ,nn.C_Hetnapja AS Hetnapja
    ,tao.C_Orakezdete AS Orakezdete
    ,tao.C_Oravege AS Oravege
    ,tao.C_Oraszam AS Oraszam
    ,tgy.C_Rovidnev AS Targynev
    ,tao.C_Megtartott AS Megtartott
    ,tao.C_Csengetesirendoraid AS Csengetesirendoraid
    ,ocs.C_Nev AS Osztalynev
    ,IIF(tao.C_Helyettesitotanarid IS NULL, tanar.C_Nyomtatasinev, hTanar.C_Nyomtatasinev) AS Tanarnev
    ,tm.C_Nev AS Teremnev
    ,IIF(tao.C_Csengetesirendoraid IS NOT NULL, 'TanitasiOra', 'TanoranKivuliFoglalkozas') AS Oratipus
    ,tao.C_Helyettesitotanarid AS Helyettesitotanarid
    ,tanar.Id AS Tanarid
  FROM T_Tanitasiora_Osszes AS tao
    INNER JOIN T_Naptarinap_Osszes AS nn ON (nn.Torolt = 'F' AND nn.Id = tao.C_Naptarinapid AND nn.C_Intezmenyid = tao.C_Intezmenyid AND nn.C_Tanevid = tao.C_Tanevid)
    INNER JOIN T_Felhasznalo_Osszes AS tanar ON (tanar.Torolt = 'F' AND tao.C_Tanarid = tanar.Id)
    INNER JOIN T_Osztalycsoport_Osszes AS ocs ON (ocs.Torolt = 'F' AND tao.C_Osztalycsoportid = ocs.Id)
    INNER JOIN T_Tantargy_Osszes AS tgy ON (tgy.Torolt = 'F' AND tgy.Id = tao.C_Tantargyid)
    LEFT OUTER JOIN T_Terem_Osszes AS tm ON (tm.Torolt = 'F' AND tm.Id = tao.C_Teremid)
    LEFT OUTER JOIN T_Felhasznalo_Osszes AS hTanar ON (hTanar.Torolt = 'F' AND hTanar.Id = tao.C_Helyettesitotanarid)
  WHERE tao.Torolt = 'F'
    AND tao.C_Intezmenyid = @pIntezmenyId
    AND tao.C_Tanevid = @pTanevId
    AND tao.C_Megtartott = 'T'
    AND (tao.C_Orakezdete >= @pIdoszakKezdete AND tao.C_Oravege <= @pIdoszakVege)
    AND (tao.C_Helyettesitotanarid = @pTanarId OR tao.C_Tanarid = @pTanarId)
  ORDER BY Orakezdete
END
GO