﻿DECLARE @now DATETIME = GETDATE();
INSERT INTO T_Tanariatlagsuly (
  C_Suly
, C_Ertekelesmodid
, C_Intezmenyid
, C_Tanevid
, Torolt
, Serial
, Lastchanged
, Created
)
SELECT
  100 AS C_Suly
  ,em.Id AS C_Ertekelesmodid
  ,t.C_Intezmenyid AS C_Intezmenyid
  ,t.Id AS C_Tanevid
  ,'F' AS Torolt
  ,1 AS Serial
  ,@now AS Lastchanged
  ,@now AS Created
FROM T_Ertekelesmod em
  INNER JOIN T_Tanev AS t ON t.Id = em.C_Altanevid AND t.C_Intezmenyid = em.C_Alintezmenyid
  INNER JOIN T_Intezmeny AS i ON i.Id = em.C_Alintezmenyid
  LEFT OUTER JOIN T_Tanariatlagsuly AS tas ON em.Id = tas.C_Ertekelesmodid AND em.C_Alintezmenyid = tas.C_Intezmenyid
  AND em.C_Altanevid = tas.C_Tanevid
WHERE em.Torolt = 'F'
  AND (t.C_Aktiv = 'T' OR t.C_Sorszam <= 40)
  AND tas.C_Ertekelesmodid IS NULL;