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

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

    I would rather create a temp table with an identity column and fill it up with output from the SPLIT function.

      CREATE TABLE #tblVals(Id INT IDENTITY(1,1), Val NVARCHAR(100))
      INSERT INTO #tblVals (Val)
      SELECT [value] FROM STRING_SPLIT('Val1-Val3-Val2-Val5', '-')
      SELECT * FROM #tblVals
    

    Now you can easily do something like below.

    DECLARE @val2 NVARCHAR(100) = (SELECT TOP 1 Val FROM #tblVals WHERE Id = 2)
    

    See the snapshot below:

提交回复
热议问题