﻿DROP PROCEDURE IF EXISTS uspFollowUpAlkalmazottPEP
GO

CREATE PROCEDURE uspFollowUpAlkalmazottPEP
   @intezmenyId int
  ,@aktTanevId int
  ,@kovetkezoTanevId int
  ,@PEPId 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 
     @kovPEPId int
    ,@selectColList nvarchar(max)
    ,@insertColList nvarchar(max)
    ,@updateColList nvarchar(max)
    ,@sql nvarchar(max)
  
  SELECT @kovPEPId = ID
  FROM T_PEDAGOGUSELETPALYAMODELL_OSSZES WHERE ELOZOTANEVIREKORDID = @PEPId 
  
  IF (SELECT TOROLT FROM T_PEDAGOGUSELETPALYAMODELL_OSSZES WHERE ID = @PEPId) = 'T' OR (SELECT TOROLT FROM T_PEDAGOGUSELETPALYAMODELL_OSSZES WHERE ID = @kovPEPId) = 'T' 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_PEDAGOGUSELETPALYAMODELL')

  IF @kovPEPId IS NOT NULL BEGIN
    SELECT 
        @updateColList = ISNULL(@updateColList+','+insertColname+' = '+updateColname,insertColName+' = '+updateColname) 
    FROM #columnMapping WHERE updateColName IS NOT NULL
    SET @sql = N'
    UPDATE t set
       '+@updateColList+'
    FROM T_PEDAGOGUSELETPALYAMODELL_OSSZES t
      INNER JOIN T_PEDAGOGUSELETPALYAMODELL_OSSZES s ON t.ELOZOTANEVIREKORDID = s.ID AND t.ID=@kovPEPId'
  END
  ELSE BEGIN
    SELECT @insertColList = ISNULL(@insertColList+','+insertColname,insertColname) FROM #columnMapping
    SELECT @selectColList = ISNULL(@selectColList+','+selectColName,selectColName) FROM #columnMapping
    SET @sql = N'
    INSERT INTO T_PEDAGOGUSELETPALYAMODELL_OSSZES(
       '+@insertColList+'
    ) SELECT 
       '+@selectColList+'
    FROM T_PEDAGOGUSELETPALYAMODELL_OSSZES s
      INNER JOIN T_FELHASZNALO_OSSZES fh ON fh.ELOZOTANEVIREKORDID = s.C_TANARID
    WHERE s.ID=@PEPId'
  END
  
  --PRINT @sql
  EXEC sp_executesql
     @sql,N'
     @intezmenyId int
    ,@aktTanevId int
    ,@kovetkezoTanevId int
    ,@PEPId int
    ,@kovPEPId int'
    ,@intezmenyId = @intezmenyId
    ,@aktTanevId = @aktTanevId
    ,@kovetkezoTanevId = @kovetkezoTanevId
    ,@PEPId = @PEPId 
    ,@kovPEPId = @kovPEPId 
  
END
GO

