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

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

    Alternatively, one can use xml, nodes() and ROW_NUMBER. We can order the elements based on their document order. For example:

    DECLARE @Input VARCHAR(100) = '1a,2b,3c,4d,5e,6f,7g,8h'
           ,@Number TINYINT = 3
    
    DECLARE @XML XML;
    DECLARE @value VARCHAR(100);
    
    SET @XML = CAST('' + REPLACE(@Input,',','') + '' AS XML);
    
    WITH DataSource ([rowID], [rowValue]) AS
    (
        SELECT ROW_NUMBER() OVER (ORDER BY T.c ASC) 
                ,T.c.value('.', 'VARCHAR(100)')
        FROM @XML.nodes('./x') T(c)
    )
    SELECT @value = [rowValue]
    FROM DataSource
    WHERE [rowID] = @Number;
    
    SELECT @value;
    

提交回复
热议问题