﻿--------------------------------------------------------------------------------------------------------------------
-- Azért futtatjuk le minden intézményre, mert az uspGenerateTanevAdatok csak az újonnan létrehozott esetén insertál,
-- ha előre létre lett hozva, de még nem aktív, arra nem futott le az eredeti.
--------------------------------------------------------------------------------------------------------------------
DECLARE intezmenytanevekCursor CURSOR LOCAL FOR 
  SELECT IntezmenyAdatok.C_INTEZMENYID
        ,IntezmenyAdatok.C_TANEVID
  FROM T_INTEZMENYADATOK IntezmenyAdatok
  INNER JOIN T_TANEV Tanev ON Tanev.ID = C_TANEVID AND Tanev.TOROLT = 'F' AND Tanev.C_NEV > '2020'

DECLARE @intezmenyId int, @tanevId int

OPEN intezmenytanevekCursor  
FETCH NEXT FROM intezmenytanevekCursor INTO @intezmenyId, @tanevId

WHILE @@FETCH_STATUS = 0 
BEGIN  

DECLARE @LELTAR_CONCERNEDId INT = NULL

SELECT TOP 1 @LELTAR_CONCERNEDId = ID FROM dbo.T_SZEREPKOR WHERE C_SZEREPKORTIPUS = 8755 AND C_INTEZMENYID = @intezmenyId AND C_TANEVID = @tanevId

IF(@LELTAR_CONCERNEDId IS NULL)
  INSERT INTO dbo.T_SZEREPKOR (
     C_SZEREPKORTIPUS
    ,C_INTEZMENYID
    ,C_TANEVID
    ,SERIAL
    ,LASTCHANGED
    ,CREATED
    ,MODIFIER
    ,CREATOR
    )
  VALUES (
     8755 --LELTAR_CONCERNED
    ,@intezmenyId
    ,@tanevId
    ,0
    ,GETDATE()
    ,GETDATE()
    ,NULL
    ,1
    )

DECLARE @LELTAR_CONCERNEDJogId INT = NULL

SELECT TOP 1 @LELTAR_CONCERNEDJogId = ID FROM dbo.T_JOGOSULTSAG WHERE C_JOG = 'LELTAR_CONCERNED' AND C_INTEZMENYID = @intezmenyId AND C_TANEVID = @tanevId

IF(@LELTAR_CONCERNEDJogId IS NULL)
  INSERT INTO dbo.T_JOGOSULTSAG (
     C_JOG
    ,C_SZEREPKORTIPUS
    ,C_INTEZMENYID
    ,C_TANEVID
    ,TOROLT
    ,SERIAL
    ,CREATED
    ,CREATOR 
    )
  VALUES (
     N'LELTAR_CONCERNED' --C_JOG
    ,8755 --LELTAR_CONCERNED
    ,@intezmenyId
    ,@tanevId
    ,'F'
    ,0
    ,GETDATE()
    ,0
    )

FETCH NEXT FROM intezmenytanevekCursor INTO @intezmenyId, @tanevId

END

CLOSE intezmenytanevekCursor  
DEALLOCATE intezmenytanevekCursor
