The following code converts the CSV string to a table with its original order (the order is returned in the column Pos).
declare @input nvarchar(max) = 'x,y,z';
declare @x xml = '<s>' + replace(@input, ',', '</s><s>') + '</s>';
select c.value('.', 'nvarchar(max)') Col, identity(int) Pos
into #t
from @x.nodes('/s') x ( c );
select * from #t;
drop table #t
returns
Col Pos
y 1
x 2
z 3
There are two problem
- The
Pos
is not right,y
got 1 andx
got 2. identity(int)
requiresselect into
For input of 'z,y,x', z, y, and x should get 1, 2, and 3 respectively.