﻿DROP PROCEDURE IF EXISTS uspFollowUpTanulo
GO

CREATE PROCEDURE uspFollowUpTanulo
   @intezmenyId int
  ,@aktTanevId int
  ,@kovetkezoTanevId int
  ,@tanuloId int
AS
BEGIN
  SET NOCOUNT ON;
  DECLARE 
     @kovTanuloId int
    ,@updateColListT nvarchar(max)
    ,@insertColListT nvarchar(max)
    ,@updateColListFH nvarchar(max)
    ,@insertColListFH nvarchar(max)
    ,@sql nvarchar(max)
    
  CREATE TABLE #ColumnMappings(
     insertColname nvarchar(128)   
    ,updateColName nvarchar(128)
    ,tableName nvarchar(128)
  )
  INSERT INTO #ColumnMappings (
     insertColname
    ,updateColName
    ,tableName
  ) SELECT 
     insertColName
    ,updateColName
    ,'T_TANULO' 
  FROM fnGetFollowUpColumnMapping ('C_NAPLOSORSZAM,C_TANULOEVFOLYAMTIPUS','T_TANULO')
  WHERE updateColName IS NOT NULL
  UNION ALL
  SELECT 
     insertColName
    ,updateColName
    ,'T_FELHASZNALO' 
  FROM fnGetFollowUpColumnMapping ('FTIP','T_FELHASZNALO')
  WHERE updateColName IS NOT NULL
  
  SELECT @kovTanuloId = kov.ID
  FROM T_FELHASZNALO_OSSZES akt
    INNER JOIN T_FELHASZNALO_OSSZES kov ON akt.C_OKTATASIAZONOSITO = kov.C_OKTATASIAZONOSITO --Import miatt nem elég az ELOZOTANEVIREKORDID
  WHERE akt.ID = @tanuloId AND kov.C_TANEVID = @kovetkezoTanevId 

  IF @kovTanuloId IS NULL OR (SELECT TOROLT FROM T_FELHASZNALO_OSSZES WHERE ID = @tanuloId) = 'T' OR (SELECT TOROLT FROM T_FELHASZNALO_OSSZES WHERE ID = @kovTanuloId) = 'T' BEGIN
    RETURN
  END 
  
  SELECT 
    @updateColListT = ISNULL(@updateColListt+','+insertColName+' = '+updateColname,insertColName+' = '+updateColname)
  FROM #ColumnMappings WHERE tableName = 'T_TANULO'
  SELECT 
    @updateColListfh = ISNULL(@updateColListfh+','+insertColName+' = '+updateColname,insertColName+' = '+updateColname)
  FROM #ColumnMappings WHERE tableName = 'T_FELHASZNALO'

  SET @sql = N'

  UPDATE t SET
    '+@updateColListT+'
  FROM T_TANULO_OSSZES t
    INNER JOIN T_TANULO_OSSZES s ON t.ID = @kovTanuloId AND s.ID = @tanuloId
    LEFT JOIN T_TANTERV_OSSZES tr ON tr.ELOZOTANEVIREKORDID = s.C_TANTERVID AND tr.TOROLT=''F''

  UPDATE t SET
    '+@updateColListFH+'
  FROM T_FELHASZNALO_OSSZES t
    INNER JOIN T_FELHASZNALO_OSSZES s ON s.C_OKTATASIAZONOSITO = t.C_OKTATASIAZONOSITO
  WHERE t.ID = @kovTanuloId
    AND s.ID = @tanuloId'

  --PRINT @sql
  
  EXEC sp_executesql 
     @sql,N'
     @intezmenyId int
    ,@aktTanevId int
    ,@kovetkezoTanevId int
    ,@tanuloId int
    ,@kovTanuloId int'
    ,@intezmenyId = @intezmenyId 
    ,@aktTanevId = @aktTanevId
    ,@kovetkezoTanevId = @kovetkezoTanevId
    ,@tanuloId = @tanuloId 
    ,@kovTanuloId = @kovTanuloId

  
  EXEC uspFollowUpFelhasznaloCim @intezmenyId, @aktTanevId, @kovetkezoTanevId, @tanuloId;
  EXEC uspFollowUpFelhasznaloEmail @intezmenyId, @aktTanevId, @kovetkezoTanevId, @tanuloId;
  EXEC uspFollowUpTanuloFelmentes @intezmenyId, @aktTanevId, @kovetkezoTanevId, @tanuloId;
  EXEC uspFollowUpFelhasznaloTelefon @intezmenyId, @aktTanevId, @kovetkezoTanevId, @tanuloId;

END
GO

