﻿--Migration
DECLARE 
   @pIntezmenyId int
  ,@pKovTanevId int
  ,@pAktTanevId int

DECLARE Intcursor CURSOR FAST_FORWARD READ_ONLY FOR 
SELECT i.ID, tvKov.ID, tvAkt.ID 
FROM T_INTEZMENY i 
INNER JOIN T_TANEV tvAkt ON tvAkt.C_INTEZMENYID = i.ID AND tvAkt.C_AKTIV = 'T' AND tvAkt.TOROLT = 'F'
INNER JOIN T_TANEV tvKov ON tvKov.C_INTEZMENYID = i.ID AND tvKov.C_KOVETKEZO = 'T' AND tvKov.C_NEV = '2021/2022' AND tvKov.TOROLT = 'F'

OPEN Intcursor

FETCH NEXT FROM Intcursor 
INTO @pIntezmenyId, @pKovTanevId, @pAktTanevId

WHILE @@FETCH_STATUS = 0
BEGIN
  INSERT INTO T_JOGOSULTSAG (
     C_JOG
    ,C_SZEREPKORTIPUS
    ,C_INTEZMENYID
    ,C_TANEVID
    ,TOROLT
    ,SERIAL
    ,LASTCHANGED
    ,CREATED
    ,MODIFIER
    ,CREATOR
    ,ELOZOTANEVIREKORDID
  ) SELECT
     t.C_JOG
    ,t.C_SZEREPKORTIPUS AS C_SZEREPKORTIPUS       -- C_SZEREPKORTIPUS - int
    ,C_INTEZMENYID   AS C_INTEZMENYID           -- C_INTEZMENYID - int
    ,@pKovTanevId   AS C_TANEVID               -- C_TANEVID - int
    ,'F'                 -- 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
    ,t.ID AS ELOZOTANEVIREKORDID    -- ELOZOTANEVIREKORDID - int
  FROM T_JOGOSULTSAG t
  WHERE t.C_INTEZMENYID = @pintezmenyId
    AND t.C_TANEVID = @pAktTanevId
    AND t.TOROLT = 'F'
    AND NOT EXISTS (SELECT 1 FROM T_JOGOSULTSAG x WHERE x.C_TANEVID = @pKovTanevId AND x.ELOZOTANEVIREKORDID = t.ID AND x.TOROLT = 'F') 

  FETCH NEXT FROM Intcursor 
  INTO @pIntezmenyId, @pKovTanevId, @pAktTanevId
END

CLOSE Intcursor
DEALLOCATE Intcursor
