﻿DROP PROCEDURE IF EXISTS dev.uspCreateSchemaSPFN
GO

CREATE PROCEDURE dev.uspCreateSchemaSPFN
   @pRoutinList nvarchar(max) -- Vesszővel elválasztott SP és FN lista (akár vegyesen is), NULL esetén az összeset frissíti
  ,@pSchemaName nvarchar(max) = NULL -- Schema neve, amit frissíteni kell, NULL esetén az összes schemán végigmegy
AS
BEGIN
  SET NOCOUNT ON
  
  DECLARE 
     @spList nvarchar(max)
    ,@fnList nvarchar(max)
  
  DECLARE @Routine TABLE (
     Id int IDENTITY(1, 1)
    ,RoutineName nvarchar(255)
  )

  IF @pRoutinList IS NULL BEGIN
    EXEC dbo.sp_Global_CreateSchemaFunctions @pSchemaName, NULL
    EXEC dbo.sp_Global_CreateSchemaStoredProcedures @pSchemaName, NULL
    
    RETURN
  END

  INSERT INTO @Routine (RoutineName)
  SELECT LTRIM(RTRIM(s.value))
  FROM STRING_SPLIT (@pRoutinList, N',') s

  SET @fnList = (
    SELECT r.ROUTINE_NAME AS "FunctionName" 
    FROM INFORMATION_SCHEMA.ROUTINES r
      INNER JOIN @Routine s ON RoutineName = r.ROUTINE_NAME
    WHERE r.ROUTINE_SCHEMA = 'dbo'
      AND r.ROUTINE_TYPE = 'FUNCTION'
    ORDER BY s.Id
    FOR XML PATH(''), ROOT('FunctionNames')
  )
  
  SET @spList = (      
    SELECT r.ROUTINE_NAME AS "StoredProcedureName" 
    FROM INFORMATION_SCHEMA.ROUTINES r
      INNER JOIN @Routine s ON RoutineName = r.ROUTINE_NAME
    WHERE r.ROUTINE_SCHEMA = 'dbo'
      AND r.ROUTINE_TYPE = 'PROCEDURE'
    ORDER BY s.Id
    FOR XML PATH(''), ROOT('StoredProcedureNames')
  )

  IF @fnList IS NOT NULL BEGIN  
    EXEC dbo.sp_Global_CreateSchemaFunctions @pSchemaName, @fnList
  END  
  IF @spList IS NOT NULL BEGIN
    EXEC dbo.sp_Global_CreateSchemaStoredProcedures @pSchemaName, @spList
  END
END
GO

