insert into T_ESZKOZIGENYLES
    (C_ASZFELFOGADASIDEJE
    ,C_ISELFOGADOTTASZF
    ,C_ISESZKOZKIOSZTVA
    ,C_GONDVISELOID
    ,C_TANULOID
    ,C_ALKALMAZOTTID
    ,C_INTEZMENYID
    ,C_TANEVID
    ,TOROLT
    ,SERIAL
    ,LASTCHANGED
    ,CREATED
    ,MODIFIER
    ,CREATOR
    ,ELOZOTANEVIREKORDID
    ,C_ESZKOZIGENYLESSTATUSZID
    ,C_FELADATELLATASIHELYID
    )
select
     ei.C_ASZFELFOGADASIDEJE as C_ASZFELFOGADASIDEJE
    ,ei.C_ISELFOGADOTTASZF as C_ISELFOGADOTTASZF
    ,ei.C_ISESZKOZKIOSZTVA as C_ISESZKOZKIOSZTVA
    ,gvKov.ID as C_GONDVISELOID
    ,tKov.ID as C_TANULOID
    ,aKov.ID as C_ALKALMAZOTTID
    ,ei.C_INTEZMENYID as C_INTEZMENYID
    ,teKov.ID as C_TANEVID
    ,ei.TOROLT as TOROLT
    ,ei.SERIAL as SERIAL
    ,ei.LASTCHANGED as LASTCHANGED
    ,ei.CREATED as CREATED
    ,0 as MODIFIER
    ,0 as CREATOR
    ,ei.ID as ELOZOTANEVIREKORDID
    ,ei.C_ESZKOZIGENYLESSTATUSZID as C_ESZKOZIGENYLESSTATUSZID
    ,fehKov.ID as C_FELADATELLATASIHELYID

from T_ESZKOZIGENYLES ei
inner join T_INTEZMENY i on i.ID = ei.C_INTEZMENYID
inner join T_TANEV te on te.id = ei.C_TANEVID and te.C_NEV = '2021/2022'

left  join T_ALKALMAZOTT aKov on aKov.ELOZOTANEVIREKORDID = ei.C_ALKALMAZOTTID and aKOv.TOROLT = 'F'
left  join T_TANULO tKov on tKov.ELOZOTANEVIREKORDID = ei.C_TANULOID and tKov.TOROLT = 'F'
left  join T_GONDVISELO gvKov on gvKov.ELOZOTANEVIREKORDID = ei.C_GONDVISELOID and gvKov.TOROLT = 'F'
left  join T_FELADATELLATASIHELY fehKov on fehKov.ELOZOTANEVIREKORDID = ei.C_FELADATELLATASIHELYID and fehKov.TOROLT = 'F'

inner join T_TANEV teKov on teKov.C_SORSZAM = te.C_SORSZAM + 2 and teKov.C_INTEZMENYID = ei.C_INTEZMENYID and teKov.TOROLT = 'F'

where not exists (select 1 from T_ESZKOZIGENYLES_OSSZES u where u.ELOZOTANEVIREKORDID = ei.ID)
