﻿DROP PROCEDURE IF EXISTS sp_FollowUpOraterv
GO

CREATE PROCEDURE sp_FollowUpOraterv
  @intezmenyId int,
  @aktTanevId int,
  @kovetkezoTanevId int,
  @oratervId int,
  @tantervId int --ezt mondjuk minek?
AS
BEGIN

DECLARE
   @kovOratervId int 
  ,@oraTervNev nvarchar(510)=(SELECT C_NEV FROM T_ORATERV_OSSZES WHERE ID = @oratervId)

  IF EXISTS(SELECT 1 FROM T_ORATERV_OSSZES WHERE TOROLT='F' AND C_TANEVID=@kovetkezoTanevId AND C_NEV=@oraTervNev AND ISNULL(ELOZOTANEVIREKORDID,0)<>@oratervId)
  BEGIN
    UPDATE T_ORATERV_OSSZES SET ELOZOTANEVIREKORDID = NULL WHERE ELOZOTANEVIREKORDID=@oratervId
    UPDATE T_ORATERV_OSSZES SET ELOZOTANEVIREKORDID = @oratervId WHERE C_NEV=@oraTervNev AND TOROLT='F' AND C_TANEVID=@kovetkezoTanevId AND ISNULL(ELOZOTANEVIREKORDID,0)<>@oratervId
  END

  SELECT @kovOratervId = ID FROM T_ORATERV_OSSZES WHERE ELOZOTANEVIREKORDID = @oratervId

	IF (SELECT TOROLT FROM T_ORATERV_OSSZES WHERE ID = @oratervId) = 'T' OR (SELECT TOROLT FROM T_ORATERV_OSSZES WHERE ID = @kovOratervId) = 'T' BEGIN
		RETURN
	END

IF (@kovOratervId IS NULL) 
	BEGIN
	INSERT INTO T_ORATERV_OSSZES (
		   C_EVFOLYAM
	    ,C_INTEZMENYID
	    ,C_NEV
	    ,C_TANEVID
	    ,C_TANTERVID
	    ,SERIAL
	    ,LASTCHANGED
	    ,CREATED
	    ,MODIFIER
	    ,CREATOR
	    ,ELOZOTANEVIREKORDID
    ) SELECT 
	     e.ID
      ,@intezmenyID AS C_INTEZMENYID
      ,t.C_NEV AS C_NEV
	    ,@kovetkezoTanevId AS C_TANEVID
	    ,tr.ID
      ,0 AS SERIAL
      ,t.LASTCHANGED AS LASTCHANGED
      ,t.LASTCHANGED AS CREATED
      ,t.MODIFIER AS MODIFIER
      ,t.MODIFIER AS CREATOR
	    ,t.ID AS ELOZOTANEVIREKORDID
    FROM T_ORATERV_OSSZES t 
      INNER JOIN T_TANTERV_OSSZES tr ON tr.ELOZOTANEVIREKORDID=t.ID AND tr.TOROLT='F'
      INNER JOIN T_EVFOLYAMTIPUS_OSSZES e ON e.ELOZOTANEVIREKORDID=t.C_EVFOLYAM AND e.TOROLT='F' AND e.C_ALTANEVID = @kovetkezoTanevId
    WHERE t.ID=@oratervId

	END
ELSE
	BEGIN
	UPDATE kovetkezo SET
		 kovetkezo.C_EVFOLYAM = e.ID
		,kovetkezo.C_NEV = aktiv.C_NEV
		,kovetkezo.SERIAL += 1
		,kovetkezo.LASTCHANGED = aktiv.LASTCHANGED
		,kovetkezo.MODIFIER = aktiv.MODIFIER
	FROM T_ORATERV_OSSZES kovetkezo
		INNER JOIN T_ORATERV_OSSZES aktiv ON aktiv.ID = @oratervId AND aktiv.ID=kovetkezo.ELOZOTANEVIREKORDID
    INNER JOIN T_EVFOLYAMTIPUS_OSSZES e ON e.ELOZOTANEVIREKORDID=aktiv.C_EVFOLYAM AND e.TOROLT='F' AND e.C_ALTANEVID = @kovetkezoTanevId
	END

END
GO