﻿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 = (SELECT TOP 1 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 
	   t.C_EVFOLYAM AS C_EVFOLYAM
      ,@intezmenyID AS C_INTEZMENYID
      ,C_NEV AS C_NEV
	  ,@kovetkezoTanevId AS C_TANEVID
	  ,(SELECT ID FROM T_TANTERV_OSSZES WHERE ELOZOTANEVIREKORDID = @tantervId) AS C_TANTERVID
      ,0 AS SERIAL
      ,LASTCHANGED AS LASTCHANGED
      ,LASTCHANGED AS CREATED
      ,MODIFIER AS MODIFIER
      ,MODIFIER AS CREATOR
	  ,t.ID AS ELOZOTANEVIREKORDID
    FROM T_ORATERV_OSSZES t WHERE ID=@oratervId

	END
ELSE
	BEGIN
	UPDATE kovetkezo SET
		 kovetkezo.C_EVFOLYAM = aktiv.C_EVFOLYAM
		,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
	END

END
GO
