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

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

  DECLARE @KonyvtarosJogId INT = NULL

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

  	SET @KonyvtarosJogId = SCOPE_IDENTITY()
  END

  FETCH NEXT FROM intezmenytanevekCursor INTO @intezmenyId, @tanevId
END  

CLOSE intezmenytanevekCursor  
DEALLOCATE intezmenytanevekCursor

GO
