IF OBJECT_ID('sp_FollowUpAlkalmazottVegzettseg') IS NOT NULL BEGIN
  DROP PROCEDURE sp_FollowUpAlkalmazottVegzettseg
END;
GO

CREATE PROCEDURE sp_FollowUpAlkalmazottVegzettseg
  @intezmenyId int,
  @aktTanevId int,
  @kovetkezoTanevId int,
  @alkalmazottId int
 
AS
BEGIN

DECLARE @kovTanevAlkalmazottId int
  SELECT @kovTanevAlkalmazottId=ID FROM T_FELHASZNALO_OSSZES WHERE ELOZOTANEVIREKORDID=@alkalmazottId AND TOROLT='F' AND C_TANEVID=@kovetkezoTanevId

DECLARE @vegzettsegId int
DECLARE vegzettsegCur CURSOR FOR
  SELECT ID FROM T_VEGZETTSEG_OSSZES WHERE C_TANARID=@alkalmazottId AND C_TANEVID=@aktTanevId AND C_INTEZMENYID=@intezmenyId

OPEN vegzettsegCur
FETCH NEXT FROM vegzettsegCur INTO @vegzettsegId
WHILE @@FETCH_STATUS=0
BEGIN
IF NOT EXISTS(SELECT TOP 1 1 FROM T_VEGZETTSEG_OSSZES WHERE C_TANEVID=@kovetkezoTanevId AND C_TANARID=@kovTanevAlkalmazottId AND ELOZOTANEVIREKORDID=@vegzettsegId AND TOROLT='F')
  BEGIN
	  INSERT INTO T_VEGZETTSEG_OSSZES (
			C_EGYEB
			,C_VEGZETTSEGTIPUSID
			,C_TANARID
			,C_INTEZMENYID
			,C_TANEVID
			,TOROLT
			,SERIAL
			,LASTCHANGED
			,CREATED
			,MODIFIER
			,CREATOR
			,NNID
			,ELOZOTANEVIREKORDID
			) SELECT 
				 t.C_EGYEB AS C_EGYEB
				,t.C_VEGZETTSEGTIPUSID AS C_VEGZETTSEGTIPUSID
				,fh.ID AS C_TANARID
				,@intezmenyId AS C_INTEZMENYID
				,@kovetkezoTanevId AS C_TANEVID
				,t.TOROLT AS TOROLT
				,0 AS SERIAL
				,GETDATE() AS LASTCHANGED
				,GETDATE() AS CREATED
				,t.MODIFIER AS MODIFIER
				,t.MODIFIER AS CREATOR
				,t.NNID AS NNID
				,t.ID AS ELOZOTANEVIREKORDID
			FROM T_VEGZETTSEG_OSSZES t 
        INNER JOIN T_FELHASZNALO_OSSZES fh ON fh.ELOZOTANEVIREKORDID=t.C_TANARID AND fh.TOROLT='F' AND fh.C_TANEVID=@kovetkezoTanevId AND fh.C_INTEZMENYID=@intezmenyId
      WHERE t.C_TANEVID = @aktTanevId AND t.C_INTEZMENYID = @intezmenyId AND t.TOROLT='F' AND t.C_TANARID=@alkalmazottId AND t.ID=@vegzettsegId
  END
  ELSE
  BEGIN
    UPDATE T SET
      C_EGYEB=old.C_EGYEB
			,C_VEGZETTSEGTIPUSID=old.C_VEGZETTSEGTIPUSID
			,C_TANARID=@kovTanevAlkalmazottId
			,C_INTEZMENYID=@intezmenyId
			,C_TANEVID=@kovetkezoTanevId
			,TOROLT=old.TOROLT
			,SERIAL=t.SERIAL+1
			,LASTCHANGED=GETDATE()
			,MODIFIER=old.MODIFIER
    FROM T_VEGZETTSEG_OSSZES t
      INNER JOIN T_VEGZETTSEG_OSSZES old ON t.ELOZOTANEVIREKORDID=old.ID AND old.C_TANEVID=@aktTanevId AND old.C_INTEZMENYID=@intezmenyId AND old.ID=@vegzettsegId
    WHERE t.TOROLT='F' AND t.C_INTEZMENYID=@intezmenyId AND t.C_TANEVID=@kovetkezoTanevId AND t.C_TANARID=@kovTanevAlkalmazottId
  END
    FETCH NEXT FROM vegzettsegCur INTO @vegzettsegId
  END
  CLOSE vegzettsegCur
  DEALLOCATE vegzettsegCur
END
GO
