I got the same / similar problem as in 'How to split a comma-separated value to columns' , but my solution code needs to be more flexible.
I got multiple (N) columns with comma separated values. E.G.:
Column1 Column2
======================
a1, a2, a3 er, asw, as
a2, a3 qwe, qw
What I now need is this
Column1_1 Column1_2 Columm1_3 Column2_1 Column2_2 Column2_3
==================================================================
a1 a2 a3 er asw as
a2 a3 NULL qwe qw NULL
So depending on the columns "longest" (most by comma seperated values) I need new Columns with the same name and an index (here 1-3). If one cell has less than the maximum values (e.g. in this case 2) the remaining new columns should not contain any values respecectively NULL.
I hope someone could help me with this!
Thanks a lot!
EDIT:
I tried using this code. It works so far, but its not flexible and only taking one column instead of "N columns"
DECLARE @xml xml
SELECT @xml = (
SELECT CAST(
'<i id="' + CAST(COLUMN1 as nvarchar(10)) + '"><w>' + REPLACE(NID,' ','</w> <w>') + '</w></i>' as xml)
FROM table4
FOR XML PATH('')
)
SELECT
t.v.value('w[1]','nvarchar(100)') as String1,
t.v.value('w[2]','nvarchar(100)') as String2,
t.v.value('w[3]','nvarchar(100)') as String3,
t.v.value('w[4]','nvarchar(100)') as String4,
t.v.value('w[5]','nvarchar(100)') as String5,
t.v.value('w[6]','nvarchar(100)') as String6,
t.v.value('w[7]','nvarchar(100)') as String7
FROM @xml.nodes('/i') as t(v)