﻿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 @BelepokartyaAdminId INT = NULL

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

  DECLARE @BelepokartyaAdminJogId INT = NULL

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

  	SET @BelepokartyaAdminJogId = SCOPE_IDENTITY()
  END

  FETCH NEXT FROM intezmenytanevekCursor INTO @intezmenyId, @tanevId
END  

CLOSE intezmenytanevekCursor  
DEALLOCATE intezmenytanevekCursor
