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

后端 未结 11 1041
半阙折子戏
半阙折子戏 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:20

    In a rare moment of lunacy I just thought that split is far easier if we use XML to parse it out for us:

    (Using the variables from @Gary Kindel's answer)

    declare @xml xml
    set @xml = '' + replace(@list,@Delimiter,'') + ''
    
    select
        el = split.el.value('.','varchar(max)')
    from  @xml.nodes('/split/el') split(el))
    

    This lists all elements of the string, split by the specified character.

    We can use an xpath test to filter out empty values, and a further xpath test to restrict this to the element we're interested in. In full Gary's function becomes:

    alter FUNCTION dbo.GetSplitString_CTE
    (
       @List       VARCHAR(MAX),
       @Delimiter  VARCHAR(255),
       @ElementNumber int
    )
    RETURNS VARCHAR(max)
    AS
    BEGIN
           -- escape any XML https://dba.stackexchange.com/a/143140/65992  
           set @list = convert(VARCHAR(MAX),(select @list for xml path(''), type));
    
           declare @xml xml
           set @xml = '' + replace(@list,@Delimiter,'') + ''
    
           declare @ret varchar(max)
           set @ret = (select
                  el = split.el.value('.','varchar(max)')
           from  @xml.nodes('/split/el[string-length(.)>0][position() = sql:variable("@elementnumber")]') split(el))
    
           return @ret
    
    END
    

提交回复
热议问题