﻿DROP PROCEDURE IF EXISTS dbo.uspFollowUpTBJogviszony
GO

CREATE PROCEDURE dbo.uspFollowUpTBJogviszony
   @IntezmenyId int
  ,@AktTanevId int
  ,@KovetkezoTanevId int
  ,@FelhasznaloId int
AS
BEGIN
  SET NOCOUNT ON;

  DECLARE @KovFelhasznaloId int = (SELECT ID FROM T_FELHASZNALO_OSSZES WHERE ELOZOTANEVIREKORDID = @FelhasznaloId AND C_TANEVID = @kovetkezoTanevId AND TOROLT = 'F')
  DECLARE 
     @SelectColList nvarchar(max)
    ,@InsertColList nvarchar(max)
    ,@UpdateColList nvarchar(max)
    ,@sql nvarchar(max)

  IF @KovFelhasznaloId IS NULL
    BEGIN
    RETURN;
    END

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

  CREATE TABLE #ColumnMapping (
     SelectColName nvarchar(max)
    ,InsertColName nvarchar(max)
    ,UpdateColName nvarchar(max)
  );

  INSERT INTO #ColumnMapping (
     SelectColName
    ,InsertColName
    ,UpdateColName
  ) SELECT
     SelectColName
    ,InsertColName
    ,UpdateColName
  FROM fnGetFollowUpColumnMapping (NULL, 'T_TBJOGVISZONY');

  UPDATE #columnMapping SET SelectColName = '@KovFelhasznaloId' where InsertColName = 'C_TANULOID';

  SELECT @SelectColList = ISNULL(@SelectColList + ', ', '') + SelectColName FROM #columnMapping;
  SELECT @InsertColList = ISNULL(@InsertColList + ', ', '') + InsertColname FROM #columnMapping;
  SELECT @UpdateColList = ISNULL(@UpdateColList + ', ', '') + InsertColname + ' = ' + SelectColName FROM #columnMapping WHERE UpdateColName IS NOT NULL;

  SET @sql = '
  MERGE INTO T_TBJOGVISZONY_OSSZES t
  USING (
    SELECT *
    FROM T_TBJOGVISZONY_OSSZES
    WHERE TOROLT = ''F''
    AND C_TANULOID = @FelhasznaloId
    AND C_TANEVID = @AktTanevId
  ) s ON t.ELOZOTANEVIREKORDID = s.ID
  WHEN MATCHED AND t.TOROLT = ''F'' THEN
    UPDATE
    SET ' + @UpdateColList + '
  WHEN NOT MATCHED BY TARGET THEN
    INSERT (' + @InsertColList + ')
    VALUES(' + @SelectColList + ');';

  --print @sql
  EXEC sp_executesql 
     @sql, N'
     @intezmenyId int
    ,@AktTanevId int
    ,@kovetkezoTanevId int
    ,@FelhasznaloId int
    ,@KovFelhasznaloId int'
    ,@intezmenyId = @IntezmenyId 
    ,@AktTanevId = @AktTanevId 
    ,@kovetkezoTanevId = @KovetkezoTanevId 
    ,@FelhasznaloId = @FelhasznaloId
    ,@KovFelhasznaloId = @KovFelhasznaloId 

END
GO
    