﻿DROP PROCEDURE IF EXISTS uspGetElozoOrakAdatai

GO
  CREATE PROCEDURE uspGetElozoOrakAdatai
    @intezmenyId int,
    @tanevId int,
    @orakAdatai nvarchar(max)

  AS
  BEGIN
    SET NOCOUNT ON;

  SELECT
     tao.ID AS Id
    ,tao.C_TEMA AS Tema
    ,tao.C_DATUM AS Datum
    ,fh.C_NYOMTATASINEV AS HelyettesNev
    ,tao.C_ORAEVESSORSZAMA AS EvesSorszam
    ,lista.TantargyId AS TantargyId
    ,lista.OsztalyCsoportId AS OsztalyCsoportId
    ,lista.TanarId AS TanarId
    ,lista.OraKezdete AS OraKezdete
  FROM OPENJSON(@orakAdatai)
  WITH (
    TantargyId INT        '$.TantargyId',
    OsztalyCsoportId INT  '$.OsztalyCsoportId',
    TanarId INT           '$.TanarId',
    OraKezdete DATETIME   '$.OraKezdete'
  ) lista
  CROSS APPLY (
      SELECT TOP 1 *
      FROM T_TANITASIORA tao 
      WHERE tao.C_INTEZMENYID = @intezmenyId
      AND tao.C_TANEVID = @tanevId
      AND tao.C_DATUM < CAST(lista.OraKezdete AS DATE)
      AND tao.C_OSZTALYCSOPORTID = lista.OsztalyCsoportId
      AND tao.C_TANTARGYID = lista.TantargyId
      AND tao.C_TANARID = lista.TanarId
      AND tao.C_ORAKEZDETE <= lista.OraKezdete
      AND tao.C_ORAEVESSORSZAMA IS NOT NULL
      ORDER BY tao.C_ORAKEZDETE DESC, tao.C_ORAEVESSORSZAMA DESC
  ) tao
  LEFT JOIN T_FELHASZNALO fh ON fh.ID = tao.C_HELYETTESITOTANARID

  END 
GO