SQL Server Universal String Delimiter Function

Based on work, it is often necessary to split a specified string into substrings at the specified position using the pointer separator.

After practical application through regular work, I am now sharing it for everyone to participate in.


create FUNCTION  [dbo].[Get_string_bySplit]
(
@List nvarchar (2000), -- the string to be separated 
@SplitOn nvarchar (5) , -- delimiter 
@num1 int
) 
RETURNS varchar(50)
as
BEGIN
declare @i int,
		@j int,
		@p int,
		@num int,
		@aa Varchar(200)
	Set @i=0
	Set @j=len(@SplitOn)
	Set @p=0 
	While LEN(@List) > 0
	Begin
		Set @p = CHARINDEX(@SplitOn,@List)
		if @p > 0
		begin
			set @aa = SUBSTRING(@List,1,@p - 1)
			set @List= SUBSTRING(@List,@p + @j, LEN(@List))
		end
		else
		begin
			set @aa = @List
			set @List= ''
		end
		set @i = @i + 1
		
		If @i=@num1
		Begin
			break
		End	
		else
			set @aa= ''
		
	End
return @aa	
end

Result validation script:

 --remove the first paragraph 
select dbo.Get_string_bySplit('123*456*789','*',1)
 --remove the third paragraph 
select dbo.Get_string_bySplit('123*456*789','*',3)