﻿DECLARE intezmenytanevekCursor CURSOR LOCAL FOR 
  SELECT T_INTEZMENYADATOK.C_INTEZMENYID, T_INTEZMENYADATOK.C_TANEVID
    FROM T_INTEZMENYADATOK
    INNER JOIN T_TANEV ON T_TANEV.C_INTEZMENYID = T_INTEZMENYADATOK.C_INTEZMENYID
    INNER JOIN T_INTEZMENY ON T_INTEZMENY.ID = T_INTEZMENYADATOK.C_INTEZMENYID
    WHERE T_TANEV.TOROLT = 'F' AND T_INTEZMENY.TOROLT = 'F' AND T_INTEZMENYADATOK.TOROLT = 'F'

DECLARE @intezmenyId int, @tanevId int, @gazdasagiUgyintezoId int = NULL

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

WHILE @@FETCH_STATUS = 0
BEGIN
  SET @gazdasagiUgyintezoId = 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)
    END

  FETCH NEXT FROM intezmenytanevekCursor INTO @intezmenyId, @tanevId
END

CLOSE intezmenytanevekCursor
DEALLOCATE intezmenytanevekCursor