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;
		SET @KovTanevAlkalmazottId = (SELECT ID FROM T_ALKALMAZOTT_OSSZES WHERE ELOZOTANEVIREKORDIDA = @alkalmazottId AND C_ALTANEVID = @kovetkezoTanevId AND TOROLT = 'F')
		
	DELETE FROM T_VEGZETTSEG_OSSZES WHERE C_TANARID = @KovTanevAlkalmazottId
		
	INSERT INTO T_VEGZETTSEG_OSSZES (
			C_EGYEB
			,C_VEGZETTSEGTIPUSID
			,C_TANARID
			,C_INTEZMENYID
			,C_TANEVID
			,TOROLT
			,SERIAL
			,LASTCHANGED
			,CREATED
			,MODIFIER
			,CREATOR
			,NNID
			,ELOZOTANEVIREKORDID
			) SELECT 
				C_EGYEB AS C_EGYEB
				,IIF((SELECT COUNT(1) FROM T_VEGZETTSEGTIPUS_OSSZES WHERE C_ALTANEVID = @kovetkezoTanevId AND ID = t.C_VEGZETTSEGTIPUSID) = 0,6855,t.C_VEGZETTSEGTIPUSID) AS C_VEGZETTSEGTIPUSID
				,@KovTanevAlkalmazottId AS C_TANARID
				,@intezmenyID AS C_INTEZMENYID
				,@kovetkezoTanevId AS C_TANEVID
				,TOROLT AS TOROLT
				,0 AS SERIAL
				,GETDATE() AS LASTCHANGED
				,GETDATE() AS CREATED
				,MODIFIER AS MODIFIER
				,MODIFIER AS CREATOR
				,NULL AS NNID
				,t.ID AS ELOZOTANEVIREKORDID
			FROM T_VEGZETTSEG_OSSZES t WHERE C_TANEVID = @aktTanevId AND C_INTEZMENYID = @intezmenyId 
				AND 0 = (SELECT COUNT(1) FROM T_VEGZETTSEG_OSSZES WHERE C_TANEVID = @kovetkezoTanevId AND C_INTEZMENYID = @intezmenyId AND ELOZOTANEVIREKORDID = t.ID)

END
GO
