IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[UFD_PRM_IN_STRING]') AND type in (N'FN', N'IF', N'TF', N'FS', N'FT'))
	DROP FUNCTION [dbo].[UFD_PRM_IN_STRING]
GO

declare @SqlCmd as varchar(max);

if exists(SELECT compatibility_level  
			FROM sys.databases WHERE name = db_name() and compatibility_level  >=130)
begin
	--RotinaNova
	set @SqlCmd = 'CREATE FUNCTION [dbo].[UFD_PRM_IN_STRING] (@STRING VARCHAR(MAX)) RETURNS @CARACTER TABLE (ID INT )   
					with schemabinding AS
	BEGIN 
		INSERT  @CARACTER
		SELECT Value
		FROM 
			STRING_SPLIT(@STRING,'','')
		RETURN
	END  ';
end
else
begin
	--RotinaAntiga
	 
	set @SqlCmd = 'CREATE  FUNCTION [dbo].[UFD_PRM_IN_STRING] (@STRING VARCHAR(MAX)) 
	RETURNS @CARACTER TABLE (ID INT )   with schemabinding 
	AS
	BEGIN
		DECLARE @POSICAO INT
		DECLARE @TMP VARCHAR (MAX)
		SELECT  @POSICAO = 1
		SELECT  @TMP = ''''
	DELETE  FROM @CARACTER

	SET @STRING = REPLACE(@STRING,'' '','''')
	WHILE @POSICAO <= LEN(@STRING)
		BEGIN
			IF CHAR(ASCII(SUBSTRING(@STRING,@POSICAO,1))) <> '','' 
			   BEGIN
					SELECT @TMP = @TMP + CHAR(ASCII(SUBSTRING(@STRING,@POSICAO,1)))
				END
			ELSE
				BEGIN
					INSERT  @CARACTER
						SELECT @TMP 
					SELECT @TMP = ''''
				END
	
			SET @POSICAO = @POSICAO + 1
		END
	
		IF RTRIM(@TMP) <> ''''
			BEGIN
				INSERT  @CARACTER
					SELECT @TMP		
			END
		RETURN
	END' 
end

	Exec (@sqlcmd);

	--select * From [dbo].[UFD_PRM_IN_STRING] ('1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18')