I have a need to create a function the will return nth element of a delimited string.
For a data migration project, I am converting JSON audit records stored in a S
I cannot comment on Gary's solution because of my low reputation
I know Gary was referencing another link.
I have struggled to understand why we need this variable
@ld INT = LEN(@Delimiter)
I also don't understand why charindex has to start at the position of length of delimiter, @ld
I tested with many examples with a single character delimiter, and they work. Most of the time, delimiter character is a single character. However, since the developer included the ld as length of delimiter, the code has to work for delimiters that have more than one character
In this case, the following case will fail
11,,,22,,,33,,,44,,,55,,,
I cloned from the codes from this link. http://codebetter.com/raymondlewallen/2005/10/26/quick-t-sql-to-parse-a-delimited-string/
I have tested various scenarios including the delimiters that have more than one character
alter FUNCTION [dbo].[split1]
(
@string1 VARCHAR(8000) -- List of delimited items
, @Delimiter VARCHAR(40) = ',' -- delimiter that separates items
, @ElementNumber int
)
RETURNS varchar(8000)
AS
BEGIN
declare @position int
declare @piece varchar(8000)=''
declare @returnVal varchar(8000)=''
declare @Pattern varchar(50) = '%' + @Delimiter + '%'
declare @counter int =0
declare @ld int = len(@Delimiter)
declare @ls1 int = len (@string1)
declare @foundit int = 0
if patindex(@Pattern , @string1) = 0
return ''
if right(rtrim(@string1),1) <> @Delimiter
set @string1 = @string1 + @Delimiter
set @position = patindex(@Pattern , @string1) + @ld -1
while @position > 0
begin
set @counter = @counter +1
set @ls1 = len (@string1)
if (@ls1 >= @ld)
set @piece = left(@string1, @position - @ld)
else
break
if (@counter = @ElementNumber)
begin
set @foundit = 1
break
end
if len(@string1) > 0
begin
set @string1 = stuff(@string1, 1, @position, '')
set @position = patindex(@Pattern , @string1) + @ld -1
end
else
set @position = -1
end
if @foundit =1
set @returnVal = @piece
else
set @returnVal = ''
return @returnVal