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

DROP PROCEDURE IF EXISTS uspFollowUpFelhasznaloTelefon
GO

CREATE PROCEDURE uspFollowUpFelhasznaloTelefon
  @intezmenyId int,
  @aktTanevId int,
  @kovTanevId int,
  @felhasznaloId int
AS
BEGIN

  DECLARE @kovTanuloId int;
  
  SELECT @kovTanuloId = kov.ID
  FROM T_FELHASZNALO_OSSZES akt
    INNER JOIN T_FELHASZNALO_OSSZES kov ON akt.C_OKTATASIAZONOSITO = kov.C_OKTATASIAZONOSITO AND kov.C_TANEVID = @kovTanevId 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 @kovTanuloId IS NOT NULL BEGIN
    DELETE FROM T_TELEFON_OSSZES
    WHERE C_FELHASZNALOID = @kovTanuloId
      AND C_GONDVISELOID IS NULL
      AND C_INTEZMENYID = @intezmenyId
      AND C_TANEVID = @kovTanevId;

    INSERT INTO T_TELEFON_OSSZES (
       C_TELEFONTIPUSA
      , C_TELEFONSZAM
      , C_LEIRAS
      , C_ALAPERTELMEZETT
      , C_ISPUBLIC
      , C_GONDVISELOID
      , C_FELHASZNALOID
      , C_INTEZMENYID
      , C_TANEVID
      , TOROLT
      , SERIAL
      , LASTCHANGED
      , CREATED
      , MODIFIER
      , CREATOR
      , ELOZOTANEVIREKORDID
      , NNID
    ) SELECT
       C_TELEFONTIPUSA
      ,C_TELEFONSZAM
      ,C_LEIRAS
      ,C_ALAPERTELMEZETT
      ,C_ISPUBLIC
      ,C_GONDVISELOID
      ,@kovTanuloId
      ,C_INTEZMENYID
      ,@kovTanevId
      ,TOROLT
      ,0
      ,GETDATE()
      ,GETDATE()
      ,MODIFIER
      ,MODIFIER
      ,ID
      ,NULL
    FROM T_TELEFON_OSSZES
    WHERE C_FELHASZNALOID = @felhasznaloId
      AND C_GONDVISELOID IS NULL
      AND C_INTEZMENYID = @intezmenyId
      AND C_TANEVID = @aktTanevId
      AND TOROLT = 'F';
  END
END
GO
