﻿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_AKTIV = 'T'

DECLARE @intezmenyId int, @tanevId int

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

WHILE @@FETCH_STATUS = 0 
BEGIN  

  DECLARE @KerdoivKitoltoKerdoivKezeloId INT = NULL

  SELECT TOP 1 @KerdoivKitoltoKerdoivKezeloId = ID FROM dbo.T_SZEREPKOR WHERE C_SZEREPKORTIPUS = 8961 AND C_INTEZMENYID = @intezmenyId AND C_TANEVID = @tanevId
  IF(@KerdoivKitoltoKerdoivKezeloId IS NULL)  BEGIN
  	INSERT INTO [dbo].T_SZEREPKOR
  			   ([C_SZEREPKORTIPUS]
  			   ,[C_INTEZMENYID]
  			   ,[C_TANEVID]
  			   ,[SERIAL]
  			   ,[LASTCHANGED]
  			   ,[CREATED]
  			   ,[MODIFIER]
  			   ,[CREATOR])
  		 VALUES
  			   (8961  -- KerdoivKitolto - KerdoivKezelo
  			   ,@intezmenyId
  			   ,@tanevId
  			   ,0
  			   ,GETDATE()
  			   ,GETDATE()
  			   ,NULL
  			   ,1)
  	SET @KerdoivKitoltoKerdoivKezeloId = SCOPE_IDENTITY()	
  END

  DECLARE @KerdoivKitoltoKerdoivKezeloJogId INT = NULL

  SELECT TOP 1 @KerdoivKitoltoKerdoivKezeloJogId = ID FROM dbo.T_JOGOSULTSAG WHERE C_JOG = 'KerdoivKitolto_KerdoivKezelo' AND C_INTEZMENYID = @intezmenyId AND C_TANEVID = @tanevId
  IF(@KerdoivKitoltoKerdoivKezeloJogId IS NULL)
  BEGIN
  	INSERT INTO dbo.T_JOGOSULTSAG
  	(
  		C_JOG,  C_SZEREPKORTIPUS,[C_INTEZMENYID] , [C_TANEVID],  TOROLT,  SERIAL,  CREATED,  CREATOR 
  	)
  	VALUES
  	(
  		N'KerdoivKitolto_KerdoivKezelo', -- C_JOG - nvarchar
  		8961, -- KerdoivKitolto - KerdoivKezelo
  		@intezmenyId , @tanevId,
  		'F', -- TOROLT - char
  		0, -- SERIAL - int
  		GETDATE(), -- CREATED - datetime
  		0 -- CREATOR - int
  	)

  	SET @KerdoivKitoltoKerdoivKezeloJogId = SCOPE_IDENTITY()
  END

  FETCH NEXT FROM intezmenytanevekCursor INTO @intezmenyId, @tanevId
END  

CLOSE intezmenytanevekCursor  
DEALLOCATE intezmenytanevekCursor

GO
