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

CREATE PROCEDURE sp_FollowUpAlkalmazottPEP
  @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 @PEPId int
DECLARE PEPCur CURSOR FOR
  SELECT ID FROM T_PEDAGOGUSELETPALYAMODELL_OSSZES WHERE C_TANARID=@alkalmazottId AND C_TANEVID=@aktTanevId AND C_INTEZMENYID=@intezmenyId

OPEN PEPCur
FETCH NEXT FROM PEPCur INTO @PEPId
WHILE @@FETCH_STATUS=0
BEGIN

IF NOT EXISTS(SELECT TOP 1 1 FROM T_PEDAGOGUSELETPALYAMODELL_OSSZES WHERE C_TANEVID=@kovetkezoTanevId AND C_TANARID=@kovTanevAlkalmazottId AND TOROLT='F' AND ELOZOTANEVIREKORDID=@PEPId)
  BEGIN
	INSERT INTO T_PEDAGOGUSELETPALYAMODELL_OSSZES(
			C_FOKOZAT
			,C_MINOSITESDATUM
			,C_PORTFOLIOSTATUSZ
			,C_TANARID
			,C_INTEZMENYID
			,C_TANEVID
			,TOROLT
			,SERIAL
			,LASTCHANGED
			,CREATED
			,MODIFIER
			,CREATOR
			,NNID
			,ELOZOTANEVIREKORDID
			) SELECT 
        t.C_FOKOZAT AS C_FOKOZAT
			  ,C_MINOSITESDATUM AS C_MINOSITESDATUM
			  ,t.C_PORTFOLIOSTATUSZ AS C_PORTFOLIOSTATUSZ
			  ,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_PEDAGOGUSELETPALYAMODELL_OSSZES t
        INNER JOIN T_FELHASZNALO_OSSZES fh ON fh.ELOZOTANEVIREKORDID=t.C_TANARID AND fh.C_TANEVID=@kovetkezoTanevId AND fh.C_INTEZMENYID=@intezmenyId AND fh.TOROLT='F'
      WHERE t.C_TANEVID = @aktTanevId AND t.C_INTEZMENYID = @intezmenyId AND t.C_TANARID=@alkalmazottId AND t.TOROLT='F' AND t.ID=@PEPId
  END
  ELSE
  BEGIN
    UPDATE t set
      C_FOKOZAT=old.C_FOKOZAT
			,C_MINOSITESDATUM=old.C_MINOSITESDATUM
			,C_PORTFOLIOSTATUSZ=old.C_PORTFOLIOSTATUSZ
			,C_INTEZMENYID=@intezmenyId
			,C_TANEVID=@kovetkezoTanevId
			,TOROLT=old.TOROLT
			,SERIAL=t.SERIAL+1
			,LASTCHANGED=GETDATE()
      ,MODIFIER=old.MODIFIER
    FROM T_PEDAGOGUSELETPALYAMODELL_OSSZES t
      INNER JOIN T_PEDAGOGUSELETPALYAMODELL_OSSZES old ON t.ELOZOTANEVIREKORDID=old.ID AND old.ID=@PEPId
    WHERE t.TOROLT='F' AND t.C_TANEVID=@kovetkezoTanevId AND t.C_TANARID=@kovTanevAlkalmazottId AND t.C_INTEZMENYID=@intezmenyId
  END
  FETCH NEXT FROM PEPCur INTO @PEPId
  END
CLOSE PEPCur
DEALLOCATE PEPCur
END
GO