﻿DECLARE @csengetesiRend int;

DECLARE intezmenytanevekCursor CURSOR LOCAL FOR 
	SELECT C_INTEZMENYID, C_TANEVID
		FROM T_INTEZMENYADATOK

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))
 
  SET @csengetesiRend = (
    SELECT TOP 1 ID
    FROM T_CSENGETESIREND
    WHERE TOROLT = 'F'
      AND C_INTEZMENYID = @intezmenyId
      AND C_TANEVID = @tanevId
    ORDER BY C_AKTIV DESC)

  IF NOT EXISTS (SELECT 1 FROM T_TANEVRENDJE WHERE C_DATUM = '20180310 00:00:00.000' AND C_INTEZMENYID = @intezmenyId AND C_TANEVID = @tanevId) BEGIN
    INSERT INTO T_TANEVRENDJE
      VALUES ('T', '20180310', 1554, 1413, N'', 1385, 'T', 'T', @csengetesiRend, @intezmenyId, @tanevId, 'F', 0, GETDATE(), GETDATE(), NULL, NULL, NULL, NULL, NULL)
  END
  
  IF NOT EXISTS (SELECT 1 FROM T_TANEVRENDJE WHERE C_DATUM = '20180316 00:00:00.000' AND C_INTEZMENYID = @intezmenyId AND C_TANEVID = @tanevId) BEGIN
    INSERT INTO T_TANEVRENDJE
      VALUES ('T', '20180316', 1554, 1412, N'', 6833, 'T', 'T', @csengetesiRend, @intezmenyId, @tanevId, 'F', 0, GETDATE(), GETDATE(), NULL, NULL, NULL, NULL, NULL)
  END
 
  IF NOT EXISTS (SELECT 1 FROM T_TANEVRENDJE WHERE C_DATUM = '20180421 00:00:00.000' AND C_INTEZMENYID = @intezmenyId AND C_TANEVID = @tanevId) BEGIN
    INSERT INTO T_TANEVRENDJE
      VALUES ('T', '20180421', 1554, 1413, N'', 1385, 'T', 'T', @csengetesiRend, @intezmenyId, @tanevId, 'F', 0, GETDATE(), GETDATE(), NULL, NULL, NULL, NULL, NULL)
  END

  IF NOT EXISTS (SELECT 1 FROM T_TANEVRENDJE WHERE C_DATUM = '20180430 00:00:00.000' AND C_INTEZMENYID = @intezmenyId AND C_TANEVID = @tanevId) BEGIN
    INSERT INTO T_TANEVRENDJE
      VALUES ('T', '20180430', 1554, 1408, N'', 6833, 'T', 'T', @csengetesiRend, @intezmenyId, @tanevId, 'F', 0, GETDATE(), GETDATE(), NULL, NULL, NULL, NULL, NULL)
  END

	FETCH NEXT FROM intezmenytanevekCursor INTO @intezmenyId, @tanevId
END  

CLOSE intezmenytanevekCursor  
DEALLOCATE intezmenytanevekCursor

GO
