﻿-- =============================================
-- Description:  <Json daraboló a dinamikus importhoz>
-- =============================================
DROP PROCEDURE IF EXISTS [dbo].[uspDynamicImportJsonSplit]
GO

CREATE PROCEDURE [dbo].[uspDynamicImportJsonSplit]
   @pIntezmenyId          INT
  ,@pTanevId            INT
  ,@pUserId            INT
  ,@pImportJson          NVARCHAR(MAX)
  ,@pIsTorles            BIT
  ,@pIsSubTable          BIT
  ,@pTableNameList        NVARCHAR(2000)

AS
BEGIN

  SET NOCOUNT ON;

  DECLARE @OrderTable TABLE (  
     Number    INT
    ,TableName  NVARCHAR(50)
  )

  --Paraméterként kapott táblanevek beszúrása
  INSERT INTO 
    @OrderTable 
  SELECT 
    * 
  FROM (
    SELECT 
       ROW_NUMBER() OVER(ORDER BY [value] DESC)  Number
      ,VALUE                    TableName
    FROM
      STRING_SPLIT (@pTableNameList, ',')
    WHERE 
      RTRIM(value) <> ''
  ) AS subSelect
  DECLARE 
     @number    INT = 1
    ,@tableName    NVARCHAR(50)
    ,@actualJson  NVARCHAR(MAX)

  WHILE EXISTS(SELECT TableName FROM @OrderTable WHERE Number = @number)
  BEGIN
        SELECT 
      @tableName = TableName 
    FROM
      @OrderTable
    WHERE 
      Number = @number

    IF EXISTS(SELECT [Key] FROM OPENJSON(@pImportJson, N'strict $.ImportJson') WHERE [Key] = @tableName)
      BEGIN      
        --[dbo].[uspDynamicImport] meghívása a JSON megfelelő részével
        SET @actualJson = CONVERT(NVARCHAR(max), (
          SELECT 
            [value]
          FROM 
            OPENJSON(@pImportJson, N'strict $.ImportJson')
          WHERE 
            [Key] =  @tableName)
        )   
               
        SET @actualJson = '{"ImportJson": {"' + @tableName + '":' + @actualJson + '} }'

        EXECUTE [dbo].[uspDynamicImport] @pIntezmenyId = @pIntezmenyId, @pTanevId = @pTanevId, @pUserId = @pUserId, @pImportJson = @actualJson, @pIsTorles = @pIsTorles, @pIsSubTable = @pIsSubTable          
      END

    SET @number = @number + 1;
  END

END

GO

