﻿DROP PROCEDURE IF EXISTS uspFollowUpTanuloSni
GO

CREATE PROCEDURE uspFollowUpTanuloSni
   @intezmenyId int
  ,@aktTanevId int
  ,@kovetkezoTanevId int
  ,@tanuloSniId int
AS
BEGIN
  SET NOCOUNT ON;
  DECLARE @kovSniId int = (SELECT ID FROM T_TANULOSNI_OSSZES WHERE ELOZOTANEVIREKORDID=@tanuloSniId AND TOROLT='F')
  DECLARE @elsoNap datetime = (select C_KEZDONAP from T_TANEV_OSSZES WHERE ID = @kovetkezoTanevId)
	DECLARE 
     @selectColList nvarchar(max)
    ,@insertColList nvarchar(max)
    ,@updateColList nvarchar(max)
    ,@sql nvarchar(max)

  CREATE TABLE #ColumnMapping (
     selectColName nvarchar(128)
    ,insertColName nvarchar(128)
    ,updateColName nvarchar(128)
  )
  INSERT INTO #ColumnMapping (
     selectColName
    ,insertColName
    ,updateColName
  ) SELECT
     selectColName
    ,insertColName
    ,updateColName
  FROM fnGetFollowUpColumnMapping (NULL,'T_TANULOSNI')

   
  IF @kovSniId IS NULL
  BEGIN
    SELECT @insertColList = ISNULL(@insertColList+','+insertColname,insertColname) FROM #columnMapping
    SELECT @selectColList = ISNULL(@selectColList+','+selectColName,selectColName) FROM #columnMapping
    SET @sql = N'
    INSERT INTO T_TANULOSNI_OSSZES (
      '+@insertColList+'
    ) SELECT
      '+@selectColList+'
    FROM T_TANULOSNI_OSSZES s
  		INNER JOIN T_FELHASZNALO_OSSZES t ON t.ID = s.C_TANULOID
  		INNER JOIN T_FELHASZNALO_OSSZES tKov ON tKov.C_OKTATASIAZONOSITO = t.C_OKTATASIAZONOSITO AND tKov.C_TANEVID = @kovetkezoTanevId AND tKov.TOROLT=''F''
    WHERE s.ID=@tanuloSniId '
    END
  ELSE 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_TANULOSNI_OSSZES t
			INNER JOIN T_TANULOSNI_OSSZES s ON s.ID=t.ELOZOTANEVIREKORDID AND s.TOROLT=''F'' AND s.ID=@tanuloSniId'
  END

  --PRINT @sql
  exec sp_executesql 
     @sql,N'
     @intezmenyId int
    ,@aktTanevId int
    ,@kovetkezoTanevId int
    ,@tanuloSniId int
    ,@kovSniId int
    ,@elsoNap datetime'
    ,@intezmenyId = @intezmenyId 
    ,@aktTanevId = @aktTanevId 
    ,@kovetkezoTanevId = @kovetkezoTanevId 
    ,@tanuloSniId = @tanuloSniId 
    ,@kovSniId = @kovSniId
    ,@elsoNap = @elsoNap

END
GO
