I have some data as under
Declare @t table (Id int identity,CommaSeperatedValue varchar(100))
Insert Into @t
Select 'Somalia,Vietnam' Union All
Select 'apple,banana,guava,India,Australia'
There is no limit in the CommaSeperated value. The desired output for the sample provided will be
Id Col1 Col2 Col3 Col4 Col5
1 Somalia Vietnam Null Null Null
2 apple banana guava India Australia
That means , the columns will be generated dynamically. Let us take another example
Declare @t table (Id int identity,CommaSeperatedValue varchar(100))
Insert Into @t
Select 'Somalia,Vietnam,Honolulu,Spain' Union All
Select 'apple,banana,guava,India,Australia,Smart,Bus' Union All
Select 'Mango'
The desired output
Id Col1 Col2 Col3 Col4 Col5 Col6 Col7
1 Somalia Vietnam Honolulu Spain Null Null Null
2 apple banana guava India Australia Smart Bus
3 Mango Null Null Null Null Null Null
How to do this query?
My attempt so far(after this I am lost)
SELECT
X.id,
X.CommaSeperatedValue,
Y.splitdata
FROM
(
SELECT *,
CAST('<X>'+REPLACE(F.CommaSeperatedValue,',','</X><X>')+'</X>' AS XML) AS xmlfilter
FROM @t F
)X
CROSS APPLY
(
SELECT fdata.D.value('.','varchar(50)') as splitdata
FROM X.xmlfilter.nodes('X') as fdata(D)
)Y
Thanks in advance
Well here is the Dynamic Solution you are looking for .I used Temp Table you can replace it with Permanent Table or Table Variable.