Using T-SQL, return nth delimited element from a string

后端 未结 11 951
半阙折子戏
半阙折子戏 2020-11-22 14:45

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

11条回答
  •  名媛妹妹
    2020-11-22 14:59

    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
    

提交回复
热议问题