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.