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

后端 未结 11 1108
半阙折子戏
半阙折子戏 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 15:18

    you can put this select into UFN. if you need you can customize it for specifying delimiter as well. in that case your ufn will have two input. number Nth and delimiter to use.

        DECLARE @tlist varchar(max)='10,20,30,40,50,60,70,80,90,100'
        DECLARE @i INT=1, @nth INT=3
        While len(@tlist) <> 0
        BEGIN
                IF @i=@nth
                BEGIN
                  select Case when charindex(',',@tlist) <> 0 Then LEFT(@tlist,charindex(',',@tlist)-1)
                              Else @tlist
                        END
                END
    
                  Select @tlist = Case when charindex(',',@tlist) <> 0 Then substring(@tlist,charindex(',',@tlist)+1,len(@tlist))
                              Else ''
                              END
    
                SELECT @i=@i+1
        END
    

提交回复
热议问题