﻿CREATE TABLE #TanuloSnik (intezmenyId int, aktTanevId int, kovetkezoTanevId int, tanuloSniId int)
INSERT INTO #TanuloSnik (intezmenyId, aktTanevId, kovetkezoTanevId, tanuloSniId)
  SELECT
     i.ID
    ,t.ID
    ,tkov.ID
    ,sni.ID
  FROM T_TANULOSNI_OSSZES sni
  INNER JOIN T_INTEZMENY i ON i.ID= sni.C_INTEZMENYID AND i.TOROLT = 'F'
  INNER JOIN T_TANEV_OSSZES t ON t.C_INTEZMENYID = i.ID AND t.ID = sni.C_TANEVID AND t.C_AKTIV = 'T' AND t.TOROLT = 'F'
  LEFT JOIN T_TANEV_OSSZES tkov ON tkov.C_INTEZMENYID = i.ID AND tkov.C_KOVETKEZO = 'T' AND tkov.TOROLT = 'F'
  WHERE sni.TOROLT = 'F' AND tkov.ID IS NOT NULL 
   
  DECLARE @tanuloSniId int
  DECLARE @intezmenyId int, @aktTanevId int, @kovetkezoTanevId int
  DECLARE sniCur CURSOR FOR
  SELECT intezmenyId, aktTanevId, kovetkezoTanevId, tanuloSniId FROM #TanuloSnik
  
  OPEN sniCur
  FETCH NEXT FROM sniCur INTO @intezmenyId, @aktTanevId, @kovetkezoTanevId, @tanuloSniId
  WHILE @@FETCH_STATUS = 0
  BEGIN
   EXEC uspFollowUpTanuloSni @intezmenyId, @aktTanevId, @kovetkezoTanevId, @tanuloSniId

    FETCH NEXT FROM sniCur INTO @intezmenyId, @aktTanevId, @kovetkezoTanevId, @tanuloSniId
  END
  CLOSE sniCur
  DEALLOCATE sniCur