﻿INSERT INTO T_TANARIATLAGSULY (C_SULY, C_ERTEKELESMODJA, C_INTEZMENYID, C_TANEVID, TOROLT, SERIAL, LASTCHANGED, CREATED, MODIFIER, CREATOR, NNID, ELOZOTANEVIREKORDID)
SELECT tas.C_SULY, tas.C_ERTEKELESMODJA, tas.C_INTEZMENYID, newTe.ID, tas.TOROLT, 0, GETDATE(), GETDATE(), tas.MODIFIER, tas.CREATOR, NULL, NULL 
FROM T_TANARIATLAGSULY tas
  INNER JOIN T_TANEV oldTe ON tas.C_INTEZMENYID = oldTe.C_INTEZMENYID AND oldTe.C_NEV = '2016/2017'
  INNER JOIN T_TANEV newTe ON tas.C_INTEZMENYID = newTe.C_INTEZMENYID AND newTe.C_NEV = '2017/2018'
  JOIN T_ERTEKELESMOD tertm ON tertm.ID = tas.C_ERTEKELESMODJA AND tertm.C_ALINTEZMENYID = oldTe.C_INTEZMENYID AND tertm.C_ALTANEVID = newTe.ID
WHERE NOT EXISTS (SELECT 1 FROM T_TANARIATLAGSULY x WHERE x.C_ERTEKELESMODJA = tas.C_ERTEKELESMODJA AND x.C_INTEZMENYID = tas.C_INTEZMENYID AND x.C_TANEVID = newTe.ID)