2

I would like to split a string into a new table that I can use to join to the original table. See code for an idea how data is stored in a column. I've

CREATE TABLE #tmpsplit
(
id INT IDENTITY(1,1) 
, StringToSplit varchar(100) 
)
INSERT INTO #tmpsplit VALUES ('Lable1:Value1|Lable2:Value2')
INSERT INTO #tmpsplit VALUES ('Lable1:ValueOne|Lable2:ValueTwo|Lable3:ValueThree')

I would very much like this to be split in three columns, ID, Lable, Value like so:

id  lable      value

1   Lable1     Value1
1   Lable2     Value2
2   LableOneV  ValueOne
2   LableTwo   ValueTwo
2   LableThree ValueThree

Preferably I'd like to do this without cursors, without variables using ths XML trick. I've come up with this (I cannot figure out how to add the ID per record).

SELECT
  SUBSTRING(t2.value,1,CHARINDEX(':',t2.value)-1) AS Lable 
, SUBSTRING(t2.value,CHARINDEX(':',t2.value)+1,LEN(t2.value)) AS Value
FROM
(SELECT Cast ('<x>' + Replace(StringToSplit, '|', '</x><x>') + '</x>' AS XML) AS RawData FROM #tmpsplit) t1
CROSS APPLY
(SELECT y.value('.','varchar(100)') as value FROM RawData.nodes('x') as f(y)) t2

Thank you.

Jan-Willem
  • 75
  • 1
  • 7
  • You could do this accordingly to this post [split comma separated string into columns](https://stackoverflow.com/questions/50383351/split-comma-separated-string-into-columns). – Michał Turczyn Aug 24 '18 at 06:53

2 Answers2

2

just include the id field in your subquery

SELECT
id
,SUBSTRING(t2.value,1,CHARINDEX(':',t2.value)-1) AS Lable 
,SUBSTRING(t2.value,CHARINDEX(':',t2.value)+1,LEN(t2.value)) AS Value
FROM
(SELECT id, Cast ('<x>' + Replace(StringToSplit, '|', '</x><x>') + '</x>' AS XML) AS 
RawData FROM #tmpsplit) t1
CROSS APPLY
(SELECT y.value('.','varchar(100)') as value FROM RawData.nodes('x') as f(y)) t2
0

You can use STRING_SPLIT function. this function available in SQL 2016 and it's above version. If you have smaller version then you can create table value split function and use that function in below query. Hope this will help you.

SELECT   
t.id
,SUBSTRING(t2.value,1,CHARINDEX(':',t2.value)-1) AS Lable 
, SUBSTRING(t2.value,CHARINDEX(':',t2.value)+1,LEN(t2.value)) AS Value
FROM #tmpsplit T
CROSS APPLY (SELECT value FROM STRING_SPLIT(T.StringToSplit, '|'))T2
NP007
  • 659
  • 8
  • 21