﻿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  
	PRINT N'INTÉZMÉNY ID: ' + CAST(@intezmenyId AS NVARCHAR(10)) + N', TANÉV ID: ' + CAST(@tanevId AS NVARCHAR(10))

  DECLARE @GAZDASAGIUGYINTEZOID INT = NULL

  SELECT TOP 1 @GAZDASAGIUGYINTEZOID = ID FROM dbo.T_SZEREPKOR WHERE C_SZEREPKORTIPUS = 7698 AND C_INTEZMENYID = @intezmenyId AND C_TANEVID = @tanevId
  IF(@GAZDASAGIUGYINTEZOID IS NULL)  BEGIN
  	INSERT INTO [dbo].T_SZEREPKOR
  			   ([C_SZEREPKORTIPUS]
  			   ,[C_INTEZMENYID]
  			   ,[C_TANEVID]
  			   ,[SERIAL]
  			   ,[LASTCHANGED]
  			   ,[CREATED]
  			   ,[MODIFIER]
  			   ,[CREATOR])
  		 VALUES
  			   (7698  -- GazdaságiÜgyintéző
  			   ,@intezmenyId
  			   ,@tanevId
  			   ,0
  			   ,GETDATE()
  			   ,GETDATE()
  			   ,NULL
  			   ,1)
  	SET @GAZDASAGIUGYINTEZOID = SCOPE_IDENTITY()	
  END

  FETCH NEXT FROM intezmenytanevekCursor INTO @intezmenyId, @tanevId
END  

CLOSE intezmenytanevekCursor  
DEALLOCATE intezmenytanevekCursor
