﻿DROP PROCEDURE IF EXISTS uspFollowUpDictionaryItemBaseNyelv 
GO

CREATE PROCEDURE uspFollowUpDictionaryItemBaseNyelv
   @Id int
  ,@aktTanevId int
  ,@kovetkezoTanevId int
  ,@IntezmenyId 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
     @kovId int
    ,@insertColList nvarchar(max)
    ,@selectColList nvarchar(max)
    ,@updateColList nvarchar(max)
    ,@sql nvarchar(max)

  CREATE TABLE #columnMapping (
     insertColName nvarchar(max) COLLATE DATABASE_DEFAULT
    ,selectColName nvarchar(max)
    ,updateColName nvarchar(max)
  )
  INSERT INTO #columnMapping (
     insertColName 
    ,selectColName 
    ,updateColName 
  ) SELECT
     insertColName 
    ,selectColName 
    ,updateColName 
  FROM fnGetFollowUpColumnMapping (NULL,'T_DICTIONARYITEMBASENYELV')

  SELECT @kovId=ID FROM T_DICTIONARYITEMBASENYELV_OSSZES WHERE ELOZOTANEVIREKORDID = @Id AND TOROLT='F' AND C_TANEVID=@kovetkezoTanevId
  IF (SELECT TOROLT FROM T_DICTIONARYITEMBASENYELV_OSSZES WHERE ID = @Id) = 'T' OR (SELECT TOROLT FROM T_TEREM_OSSZES WHERE ID = @kovId) = 'T' 
  BEGIN
    RETURN
  END

  IF (@kovId IS NULL) BEGIN
    SELECT @insertColList = ISNULL(@insertColList+','+insertColname,insertColname) FROM #columnMapping 
    SELECT @selectColList = ISNULL(@selectColList+','+selectColName,selectColName) FROM #columnMapping
    SET @selectColList = REPLACE(@selectColList, 's.C_DICTIONARYITEMBASEID', 'dib.ID')
    SET @selectColList = REPLACE(@selectColList, 's.MODIFIER', 's.CREATOR')
    SET @sql = N'
    INSERT INTO T_DICTIONARYITEMBASENYELV_OSSZES (
      '+@insertColList+'
    ) SELECT 
       '+@selectColList+'
    FROM T_DICTIONARYITEMBASENYELV_OSSZES s
    INNER JOIN T_DICTIONARYITEMBASE_OSSZES dib ON dib.ELOZOTANEVIREKORDID = s.C_DICTIONARYITEMBASEID AND dib.C_TANEVID = @kovetkezoTanevId
    WHERE s.ID=@Id AND s.TOROLT=''F'''
  END
  ELSE BEGIN
    SELECT 
      @updateColList = ISNULL(@updateColList+','+insertColName+' = '+updateColname,insertColName+' = '+updateColname)
    FROM #columnMapping
    WHERE updateColname IS NOT NULL
    SET @updateColList = REPLACE(@updateColList, 's.C_DICTIONARYITEMBASEID', 't.C_DICTIONARYITEMBASEID')
    SET @updateColList = REPLACE(@updateColList, 's.C_NYELVID', 't.C_NYELVID')
    
    SET @sql = N'
    UPDATE t SET
      '+@updateColList+'
    FROM T_DICTIONARYITEMBASENYELV_OSSZES s
      INNER JOIN T_DICTIONARYITEMBASENYELV_OSSZES t ON t.ELOZOTANEVIREKORDID=s.ID AND t.TOROLT=''F''
    WHERE s.ID=@Id AND s.TOROLT=''F'''
  END
  
  --PRINT @sql
  exec sp_executesql
     @sql,N'
     @intezmenyId int
    ,@aktTanevId int
    ,@kovetkezoTanevId int
    ,@Id int'
    ,@intezmenyId = @intezmenyId
    ,@aktTanevId = @aktTanevId
    ,@kovetkezoTanevId = @kovetkezoTanevId 
    ,@Id = @Id 
    
END
GO
