﻿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 @kovAlkalmazottId int
  
  SELECT @kovAlkalmazottId = ID
  FROM T_FELHASZNALO_OSSZES 
  WHERE ELOZOTANEVIREKORDID = @alkalmazottId 
    AND C_TANEVID = @kovetkezoTanevId
  
  IF (SELECT TOROLT FROM T_FELHASZNALO_OSSZES WHERE ID = @alkalmazottId) = 'T' OR (SELECT TOROLT FROM T_FELHASZNALO_OSSZES WHERE ID = @kovAlkalmazottId) = 'T' BEGIN
    RETURN
  END

  UPDATE kov SET
     C_EGYEB = akt.C_EGYEB
		,C_VEGZETTSEGTIPUSID = akt.C_VEGZETTSEGTIPUSID
		,C_TANARID = @kovAlkalmazottId
		,C_INTEZMENYID = @intezmenyId
		,C_TANEVID = @kovetkezoTanevId
		,SERIAL += 1
		,LASTCHANGED = GETDATE()
		,MODIFIER = akt.MODIFIER
  FROM T_VEGZETTSEG_OSSZES kov
    INNER JOIN T_VEGZETTSEG_OSSZES akt ON akt.ELOZOTANEVIREKORDID = kov.ID 
  WHERE akt.C_TANEVID = @aktTanevId 
    AND akt.C_INTEZMENYID = @intezmenyId 
    AND akt.C_TANARID = @alkalmazottId
    AND akt.TOROLT = 'F' 
    AND kov.C_TANARID = @kovAlkalmazottId 
    AND kov.C_TANEVID = @kovetkezoTanevId 
    AND kov.C_INTEZMENYID = @intezmenyId 
    AND kov.TOROLT = 'F'
    
  INSERT INTO T_VEGZETTSEG_OSSZES (
		 C_EGYEB
		,C_VEGZETTSEGTIPUSID
		,C_TANARID
		,C_INTEZMENYID
		,C_TANEVID
		,TOROLT
		,SERIAL
		,LASTCHANGED
		,CREATED
		,MODIFIER
		,CREATOR
		,NNID
		,ELOZOTANEVIREKORDID
	) SELECT 
		 akt.C_EGYEB AS C_EGYEB
		,akt.C_VEGZETTSEGTIPUSID AS C_VEGZETTSEGTIPUSID
		,@kovAlkalmazottId AS C_TANARID
		,@intezmenyId AS C_INTEZMENYID
		,@kovetkezoTanevId AS C_TANEVID
		,akt.TOROLT AS TOROLT
		,0 AS SERIAL
		,GETDATE() AS LASTCHANGED
		,GETDATE() AS CREATED
		,akt.MODIFIER AS MODIFIER
		,akt.MODIFIER AS CREATOR
		,akt.NNID AS NNID
		,akt.ID AS ELOZOTANEVIREKORDID
  FROM T_VEGZETTSEG_OSSZES akt 
  WHERE akt.C_TANEVID = @aktTanevId 
    AND akt.C_INTEZMENYID = @intezmenyId 
    AND akt.C_TANARID = @alkalmazottId 
    AND akt.TOROLT = 'F'
    AND NOT EXISTS (SELECT 1 FROM T_VEGZETTSEG_OSSZES kov WHERE kov.ELOZOTANEVIREKORDID = akt.ID AND kov.C_TANEVID = @kovetkezoTanevId AND kov.C_TANARID = @kovAlkalmazottId)
    
END
GO
