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

IF OBJECT_ID('sp_FollowUpTanuloTelefon') IS NOT NULL BEGIN
  DROP PROCEDURE sp_FollowUpTanuloTelefon
END;
GO

CREATE PROCEDURE sp_FollowUpTanuloTelefon
  @intezmenyId int,
  @aktTanevId int,
  @kovTanevId int,
  @tanuloId int
AS
BEGIN

	DECLARE @kovTanevesTanuloId int;
	SELECT @kovTanevesTanuloId = kovTanevesTanulo.ID
	FROM T_FELHASZNALO_OSSZES aktTanevesTanulo
	INNER JOIN T_FELHASZNALO_OSSZES kovTanevesTanulo ON aktTanevesTanulo.C_OKTATASIAZONOSITO = kovTanevesTanulo.C_OKTATASIAZONOSITO AND kovTanevesTanulo.C_TANEVID = @kovTanevId AND kovTanevesTanulo.C_INTEZMENYID = @intezmenyId
	WHERE aktTanevesTanulo.ID = @tanuloId
	  AND aktTanevesTanulo.C_INTEZMENYID = @intezmenyId
	  AND aktTanevesTanulo.C_TANEVID = @aktTanevId
	  AND kovTanevesTanulo.TOROLT = 'F'
	  AND aktTanevesTanulo.TOROLT = 'F'; --kell? elv olyat nem módosíthat, aki törölt

	IF @kovTanevesTanuloId IS NOT NULL
	BEGIN
		DELETE FROM T_TELEFON_OSSZES
		WHERE C_FELHASZNALOID = @kovTanevesTanuloId
		  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
		   ,@kovTanevesTanuloId
		   ,C_INTEZMENYID
		   ,@kovTanevId
		   ,TOROLT
		   ,0
		   ,GETDATE()
		   ,GETDATE()
		   ,MODIFIER
		   ,MODIFIER
		   ,ID
		   ,NULL
		FROM T_TELEFON_OSSZES
		WHERE C_FELHASZNALOID = @tanuloId
		  AND C_GONDVISELOID IS NULL
		  AND C_INTEZMENYID = @intezmenyId
		  AND C_TANEVID = @aktTanevId
		  AND TOROLT = 'F';

	END
END
GO
