﻿DROP PROCEDURE IF EXISTS uspFollowUpOratervTargy
GO

CREATE PROCEDURE uspFollowUpOratervTargy
  @intezmenyId int,
  @aktTanevId int,
  @kovetkezoTanevId int,
  @oratervTargyId int
AS
BEGIN

DECLARE
   @kovOratervTargyId int 
  ,@kovTantargyId int=(
    SELECT tgyKov.ID FROM T_TANTARGY_OSSZES tgyKov
      INNER JOIN T_ORATERVTARGY_OSSZES ottgy ON ottgy.C_TANTARGYID=tgyKov.ELOZOTANEVIREKORDID AND ottgy.TOROLT='F'
     WHERE tgyKov.TOROLT='F' AND tgyKov.C_TANEVID=@kovetkezoTanevId AND ottgy.ID=@oratervTargyId)
  
  ,@kovOratervId int =(
    SELECT otKov.ID FROM T_ORATERV_OSSZES otKov
      INNER JOIN T_ORATERVTARGY_OSSZES ottgy ON ottgy.ID=@oratervTargyId AND otKov.ELOZOTANEVIREKORDID=ottgy.C_ORATERVID AND ottgy.TOROLT='F'
    WHERE otKov.C_TANEVID=@kovetkezoTanevId AND otKov.TOROLT='F')

  IF EXISTS(SELECT 1 FROM T_ORATERVTARGY_OSSZES WHERE TOROLT='F' AND C_TANEVID=@kovetkezoTanevId AND C_TANTARGYID=@kovTantargyId AND C_ORATERVID=@kovOratervId AND ISNULL(ELOZOTANEVIREKORDID,0)<>@oratervTargyId)
  BEGIN
    UPDATE T_ORATERVTARGY_OSSZES SET ELOZOTANEVIREKORDID = NULL WHERE ELOZOTANEVIREKORDID=@oratervTargyId
    UPDATE T_ORATERVTARGY_OSSZES SET ELOZOTANEVIREKORDID = @oratervTargyId WHERE TOROLT='F' AND C_TANEVID=@kovetkezoTanevId AND C_TANTARGYID=@kovTantargyId AND C_ORATERVID=@kovOratervId AND ISNULL(ELOZOTANEVIREKORDID,0)<>@oratervTargyId
  END

  SELECT @kovOratervTargyId = ID FROM T_ORATERVTARGY_OSSZES WHERE ELOZOTANEVIREKORDID = @oratervTargyId

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

IF (@kovOratervTargyId IS NULL) 
	BEGIN
	INSERT INTO T_ORATERVTARGY_OSSZES (
     C_EVESORASZAM
    ,C_INTEZMENYID
    ,C_TANEVID
    ,C_ORATERVID
    ,C_TANTARGYID
    ,SERIAL
    ,LASTCHANGED
    ,CREATED
    ,MODIFIER
    ,CREATOR
    ,ELOZOTANEVIREKORDID
    ) SELECT 
	     ottgy.C_EVESORASZAM
      ,ottgy.C_INTEZMENYID
      ,@kovetkezoTanevId
      ,otKov.ID
      ,C_TANTARGYID
      ,0
      ,GETDATE()
      ,GETDATE()
      ,ottgy.MODIFIER
      ,ottgy.MODIFIER
      ,ottgy.ID
    FROM T_ORATERVTARGY_OSSZES ottgy
      INNER JOIN T_ORATERV_OSSZES otKov ON otKov.ELOZOTANEVIREKORDID=ottgy.C_ORATERVID AND otKov.TOROLT='F'
    WHERE ottgy.ID=@oratervTargyId

	END
ELSE
	BEGIN
	UPDATE kovetkezo SET
		 kovetkezo.C_EVESORASZAM = aktiv.C_EVESORASZAM
		,kovetkezo.C_TANTARGYID = tgy.ID
		,kovetkezo.SERIAL += 1
		,kovetkezo.LASTCHANGED = aktiv.LASTCHANGED
		,kovetkezo.MODIFIER = aktiv.MODIFIER
	FROM T_ORATERVTARGY_OSSZES kovetkezo
		INNER JOIN T_ORATERVTARGY_OSSZES aktiv ON aktiv.ID = @oratervTargyId AND aktiv.ID=kovetkezo.ELOZOTANEVIREKORDID
    INNER JOIN T_TANTARGY_OSSZES tgy ON tgy.ELOZOTANEVIREKORDID=aktiv.C_TANTARGYID AND tgy.TOROLT='F'
	END

END
GO