﻿DROP PROCEDURE IF EXISTS uspFollowUpFelhasznaloCim
GO

CREATE PROCEDURE uspFollowUpFelhasznaloCim
   @intezmenyId int
  ,@aktTanevId int
  ,@kovetkezoTanevId int
  ,@felhasznaloId int
AS
BEGIN
  SET NOCOUNT ON;
  DECLARE 
     @kovFelhasznaloId int
    ,@insertColList nvarchar(max)
    ,@selectColList nvarchar(max)
    ,@sql nvarchar(max)

  CREATE TABLE #columnMapping (
     insertColName nvarchar(128) COLLATE DATABASE_DEFAULT
    ,selectColName nvarchar(128)
  )
  
  INSERT INTO #columnMapping 
  SELECT insertColName,selectColName 
  FROM fnGetFollowUpColumnMapping ('GID','T_CIM')
  
  SELECT @kovFelhasznaloId = kovTanevesTanulo.ID
  FROM T_FELHASZNALO_OSSZES aktTanevesTanulo
    INNER JOIN T_FELHASZNALO_OSSZES kovTanevesTanulo ON aktTanevesTanulo.ID = kovTanevesTanulo.ELOZOTANEVIREKORDID
  WHERE aktTanevesTanulo.ID = @felhasznaloId
    AND aktTanevesTanulo.C_INTEZMENYID = @intezmenyId
    AND aktTanevesTanulo.C_TANEVID = @aktTanevId
    AND kovTanevesTanulo.TOROLT = 'F'
    AND aktTanevesTanulo.TOROLT = 'F';

  IF @kovFelhasznaloId IS NOT NULL BEGIN
    DELETE FROM T_CIM_OSSZES
    WHERE C_FELHASZNALOID = @kovFelhasznaloId
      AND C_GONDVISELOID IS NULL
      AND C_INTEZMENYID = @intezmenyId
      AND C_TANEVID = @kovetkezoTanevId
    
    SELECT @insertColList = ISNULL(@insertColList+','+insertColname,insertColname) FROM #columnMapping 
    SELECT @selectColList = ISNULL(@selectColList+','+selectColName,selectColName) FROM #columnMapping 

    SET @sql = N'
    INSERT INTO T_CIM_OSSZES (
      '+@insertColList+'
    ) SELECT
      '+@selectColList+' 
    FROM T_CIM_OSSZES s
    WHERE s.C_FELHASZNALOID = @felhasznaloId AND s.C_GONDVISELOID IS NULL AND s.TOROLT = ''F'''
    
    --PRINT @sql

    EXEC sp_executesql 
       @sql,N'
       @kovetkezoTanevId int
      ,@intezmenyId int
      ,@felhasznaloId int
      ,@kovFelhasznaloId int'
      ,@kovetkezoTanevId = @kovetkezoTanevId
      ,@intezmenyId = @intezmenyId
      ,@felhasznaloId = @felhasznaloId
      ,@kovFelhasznaloId = @kovFelhasznaloId
  END

END
GO
