﻿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  
IF ((SELECT C_ISSZAKKEPZO FROM T_INTEZMENYADATOK_OSSZES WHERE C_INTEZMENYID = @intezmenyId AND C_TANEVID = @tanevId AND TOROLT = 'F') = 'T')
  BEGIN
  DECLARE @DualisAdminId INT = NULL

  SELECT TOP 1 @DualisAdminId = ID FROM dbo.T_SZEREPKOR WHERE C_SZEREPKORTIPUS = 9001 AND C_INTEZMENYID = @intezmenyId AND C_TANEVID = @tanevId
  IF(@DualisAdminId IS NULL)  BEGIN
  	INSERT INTO [dbo].T_SZEREPKOR
  			   ([C_SZEREPKORTIPUS]
  			   ,[C_INTEZMENYID]
  			   ,[C_TANEVID]
  			   ,[SERIAL]
  			   ,[LASTCHANGED]
  			   ,[CREATED]
  			   ,[MODIFIER]
  			   ,[CREATOR])
  		 VALUES
  			   (9001  -- Duális képzőhelyi adminisztrátor
  			   ,@intezmenyId
  			   ,@tanevId
  			   ,0
  			   ,GETDATE()
  			   ,GETDATE()
  			   ,NULL
  			   ,1)
  	SET @DualisAdminId = SCOPE_IDENTITY()	
  END

  DECLARE @DualisAdminJogId INT = NULL

  SELECT TOP 1 @DualisAdminJogId = ID FROM dbo.T_JOGOSULTSAG WHERE C_JOG = 'Dualis_Admin' AND C_INTEZMENYID = @intezmenyId AND C_TANEVID = @tanevId
  IF(@DualisAdminJogId IS NULL)
  BEGIN
  	INSERT INTO dbo.T_JOGOSULTSAG
  	(
  		C_JOG,  C_SZEREPKORTIPUS,[C_INTEZMENYID] , [C_TANEVID],  TOROLT,  SERIAL,  CREATED,  CREATOR 
  	)
  	VALUES
  	(
  		N'Dualis_Admin', -- C_JOG - nvarchar
  		9001, -- Duális képzőhelyi adminisztrátor
  		@intezmenyId , @tanevId,
  		'F', -- TOROLT - char
  		0, -- SERIAL - int
  		GETDATE(), -- CREATED - datetime
  		0 -- CREATOR - int
  	)

  	SET @DualisAdminJogId = SCOPE_IDENTITY()
    END
  END
  FETCH NEXT FROM intezmenytanevekCursor INTO @intezmenyId, @tanevId
END  

CLOSE intezmenytanevekCursor  
DEALLOCATE intezmenytanevekCursor

GO
