﻿DROP PROCEDURE IF EXISTS dbo.uspSaveTanitasiOraDigTamEszkozList
GO

CREATE PROCEDURE dbo.uspSaveTanitasiOraDigTamEszkozList
   @pIntezmenyId int
  ,@pTanevId int
  ,@pTanitasiOraId int
  ,@pFelhasznaloId int
  ,@pDigTamEszkozList nvarchar(max)

AS
BEGIN  
  SET NOCOUNT ON;
  CREATE TABLE #items (id INT NOT NULL PRIMARY KEY);

  IF(@pDigTamEszkozList IS NOT NULL AND @pDigTamEszkozList <> '')
  BEGIN

    INSERT INTO #items(id)
    SELECT VALUE FROM STRING_SPLIT(@pDigTamEszkozList, ',');

  END

  UPDATE dte SET 
     TOROLT = 'F'
    ,SERIAL += 1
    ,LASTCHANGED = GETDATE()
    ,MODIFIER = @pFelhasznaloId
  FROM T_TANITASIORADIGTAMESZKOZ_OSSZES dte
  WHERE dte.C_TANITASIORAID = @pTanitasiOraId
    AND dte.C_TANEVID = @pTanevId
    AND dte.C_DIGTAMESZKOZTIPUSID IN (SELECT id FROM #items i)
    AND dte.TOROLT = 'T'

  UPDATE dte SET 
     TOROLT = 'T'
    ,SERIAL += 1
    ,LASTCHANGED = GETDATE()
    ,MODIFIER = @pFelhasznaloId
  FROM T_TANITASIORADIGTAMESZKOZ_OSSZES dte
  WHERE dte.C_TANITASIORAID = @pTanitasiOraId
    AND dte.C_TANEVID = @pTanevId
    AND dte.C_DIGTAMESZKOZTIPUSID NOT IN (SELECT id  FROM #items i)
    AND dte.TOROLT = 'F'
  
  INSERT INTO T_TANITASIORADIGTAMESZKOZ (
    C_DIGTAMESZKOZTIPUSID
    ,C_TANITASIORAID
    ,C_INTEZMENYID
    ,C_TANEVID
    ,TOROLT
    ,SERIAL
    ,LASTCHANGED
    ,CREATED
    ,MODIFIER
    ,CREATOR
    ,ELOZOTANEVIREKORDID
  )
  SELECT
    ID
    ,@pTanitasiOraId
    ,@pIntezmenyId
    ,@pTanevId
    ,'F'
    ,0
    ,GETDATE()
    ,GETDATE()
    ,@pFelhasznaloId
    ,@pFelhasznaloId
    ,NULL
  FROM #items i
  WHERE NOT EXISTS (SELECT 1 FROM T_TANITASIORADIGTAMESZKOZ_OSSZES dte WHERE i.id = dte.C_DIGTAMESZKOZTIPUSID AND dte.C_TANITASIORAID = @pTanitasiOraId AND dte.C_TANEVID = @pTanevId)
END 
GO
