DROP PROCEDURE IF EXISTS uspFollowUpIntezmenyAdatok
GO

CREATE PROCEDURE uspFollowUpIntezmenyAdatok
   @intezmenyId int
  ,@aktTanevId int
  ,@kovetkezoTanevId int
AS
BEGIN
  SET NOCOUNT ON;

  IF NOT EXISTS (SELECT 1 from T_TANEV where ID = @kovetkezoTanevId and C_KOVETKEZO = 'T' and C_AKTIVALVA is null and C_ISKIVALASZTHATO = 'T')
    BEGIN
      RETURN;
    END

  DECLARE @aktivIntezmenyAdatokId int = (
    SELECT TOP 1 ID FROM T_INTEZMENYADATOK_OSSZES WHERE C_TANEVID = @aktTanevId AND TOROLT='F')
    ,@updateColList nvarchar(max)
    ,@sql nvarchar(max)

  SELECT 
      @updateColList = ISNULL(@updateColList+','+insertColName+' = '+updateColname,insertColName+' = '+updateColname)
  FROM fnGetFollowUpColumnMapping (NULL,'T_INTEZMENYADATOK')
  WHERE updateColname IS NOT NULL

  SET @sql = N'
  UPDATE t SET
    '+@updateColList+'
  FROM T_INTEZMENYADATOK_OSSZES t
    INNER JOIN T_INTEZMENYADATOK_OSSZES s ON s.ID = @aktivIntezmenyAdatokId AND s.ID = t.ELOZOTANEVIREKORDID'

  --PRINT @sql
  EXEC sp_executesql
     @sql,N'
     @intezmenyId int
    ,@kovetkezoTanevId int
    ,@aktivIntezmenyAdatokId int'
    ,@intezmenyId = @intezmenyId 
    ,@kovetkezoTanevId = @kovetkezoTanevId 
    ,@aktivIntezmenyAdatokId = @aktivIntezmenyAdatokId

END
GO
