﻿-- =============================================
-- Author: Szekeres András
-- Create date:  2018.04.24.
-- Description:  Egy tanuló telefonszámainak frissítése a következõ tanévre

-- Modifier: Zalán Máriusz
-- Modify date: 2020.02.19
-- Description: Dinamizálás
-- =============================================

DROP PROCEDURE IF EXISTS uspFollowUpFelhasznaloTelefon
GO

CREATE PROCEDURE uspFollowUpFelhasznaloTelefon
   @intezmenyId int
  ,@aktTanevId int
  ,@kovetkezoTanevId int
  ,@felhasznaloId 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 
     @kovFelhasznaloId int
    ,@insertColList nvarchar(max)
    ,@selectColList nvarchar(max)
    ,@sql nvarchar(max)

  CREATE TABLE #columnMapping (
     insertColName nvarchar(max) COLLATE DATABASE_DEFAULT
    ,selectColName nvarchar(max)
  )
  
  INSERT INTO #columnMapping 
  SELECT insertColName,selectColName 
  FROM fnGetFollowUpColumnMapping (NULL,'T_TELEFON')
  
  SELECT @kovFelhasznaloId = kov.ID
  FROM T_FELHASZNALO_OSSZES akt
    INNER JOIN T_FELHASZNALO_OSSZES kov ON akt.C_OKTATASIAZONOSITO = kov.C_OKTATASIAZONOSITO AND kov.C_TANEVID = @kovetkezoTanevId AND kov.C_INTEZMENYID = @intezmenyId
  WHERE akt.ID = @felhasznaloId
    AND akt.C_INTEZMENYID = @intezmenyId
    AND akt.C_TANEVID = @aktTanevId
    AND kov.TOROLT = 'F'
    AND akt.TOROLT = 'F'

  IF @kovFelhasznaloId IS NOT NULL BEGIN
    DELETE FROM T_TELEFON_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_TELEFON_OSSZES (
      '+@insertColList+'
    ) SELECT
      '+@selectColList+' 
    FROM T_TELEFON_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
