﻿INSERT INTO T_SZEREPKOR (
     C_SZEREPKORTIPUS
    ,C_INTEZMENYID
    ,C_TANEVID
    ,TOROLT
    ,SERIAL
    ,LASTCHANGED
    ,CREATED
    ,MODIFIER
    ,CREATOR
    ,ELOZOTANEVIREKORDID
  ) SELECT 
     sz.C_SZEREPKORTIPUS AS C_SZEREPKORTIPUS       -- C_SZEREPKORTIPUS - int
    ,sz.C_INTEZMENYID   AS C_INTEZMENYID           -- C_INTEZMENYID - int
    ,(SELECT ID FROM T_TANEV_OSSZES 
      WHERE C_NEV = '2021/2022' AND TOROLT = 'F'
            AND C_INTEZMENYID = sz.C_INTEZMENYID    )   AS C_TANEVID        -- C_TANEVID - int
    ,'F'  AS TOROLT                 -- TOROLT  char(1)
    ,0 AS SERIAL                    -- SERIAL - int
    ,getdate() AS LASTCHANGED       -- LASTCHANGED - datetime
    ,getdate() AS CREATED           -- CREATED - datetime
    ,NULL AS MODIFIER               -- MODIFIER - int
    ,NULL AS CREATOR                -- CREATOR - int
    ,sz.ID AS ELOZOTANEVIREKORDID   -- ELOZOTANEVIREKORDID - int
  FROM T_SZEREPKOR_OSSZES sz
  INNER JOIN T_TANEV_OSSZES tanev ON tanev.ID = sz.C_TANEVID  AND tanev.TOROLT = 'F'
  INNER JOIN T_INTEZMENY_OSSZES intezmeny ON intezmeny.ID = sz.C_INTEZMENYID and intezmeny.TOROLT ='F'
  WHERE 
        sz.TOROLT = 'F'
    AND sz.C_SZEREPKORTIPUS = 8753
    AND tanev.C_NEV = '2020/2021' 
    AND NOT EXISTS 
    (SELECT 1 FROM T_SZEREPKOR_OSSZES x 
      INNER JOIN T_TANEV_OSSZES tanev ON tanev.ID = x.C_TANEVID AND tanev.Torolt = 'F'
    WHERE
    tanev.C_NEV = '2021/2022' 
    AND x.C_SZEREPKORTIPUS = 8753
    AND x.ELOZOTANEVIREKORDID = sz.ID 
    AND x.TOROLT = 'F'
    )