I am trying to separate strings into different columns which are separated by commas. I tried all the article that is on stackoverflow but not successful.
Example:
Column1
mouse,monitor,keyboard
cable,mouse
headset,desk,cable,monitor,usb,charger
Expected results:
Column1 |Column2 |Column3 |Column4 |Column5 |Column6
mouse |monitor |keyboard | NULL | NULL | NULL
cable |mouse |NULL | NULL | NULL | NULL
headset |desk |cable | monitor | usb | charger
Please note that the strings under Column1 can be as many as 10 strings and the strings are different every week so they are undefined.
This is one of the code I tried:
Declare #TblName (id int, Column1 varchar(max))
Insert into #TblName
Select A.Column1
,B.*
From #TblNameK A
Cross Apply (
Select Pos1 = xDim.value('/x[1]','varchar(max)')
,Pos2 = xDim.value('/x[2]','varchar(max)')
,Pos3 = xDim.value('/x[3]','varchar(max)')
,Pos4 = xDim.value('/x[4]','varchar(max)')
,Pos5 = xDim.value('/x[5]','varchar(max)')
,Pos6 = xDim.value('/x[6]','varchar(max)')
,Pos7 = xDim.value('/x[7]','varchar(max)')
,Pos8 = xDim.value('/x[8]','varchar(max)')
,Pos9 = xDim.value('/x[9]','varchar(max)')
From (Select Cast('<x>' + Replace(A.Column1,',','</x><x>')+'</x>' as XML) as xDim) A
) B