If I issue
SELECT ID FROM TestAhmet
I get this result:
1,2,3,4,5
but what I really need is multiple column with all the values separated by comma, like this:
1
3
5
2
4
How do I do this?
If I issue
SELECT ID FROM TestAhmet
I get this result:
1,2,3,4,5
but what I really need is multiple column with all the values separated by comma, like this:
1
3
5
2
4
How do I do this?
If you are running SQL Server 2016 or later, you can use table-valued function string_split()
:
select value
from TestAhmet t
cross apply string_split(t.id, ',')
You can make this query as a function and use it across procs.
DECLARE @list varchar(MAX)= '1,2,3,4,5',
@pos int,
@nextpos int,
@valuelen int
DECLARE @tbl TABLE (number int NULL)
SELECT @pos = 0, @nextpos = 1
WHILE @nextpos > 0
BEGIN
SELECT @nextpos = charindex(',', @list, @pos + 1)
SELECT @valuelen = CASE WHEN @nextpos > 0
THEN @nextpos
ELSE len(@list) + 1
END - @pos - 1
INSERT @tbl (number)
VALUES (convert(int, substring(@list, @pos + 1, @valuelen)))
SELECT @pos = @nextpos
END
SELECT * FROM @tbl
You can use XML related functions that are available on SQL Server 2012
Reference: XML nodes() function and XML value() function
DECLARE @text_to_split nvarchar(100) = '1,10,4,6'
SELECT document.node.value('.', 'int') as id
FROM
(SELECT CAST('<content><x>' + REPLACE(@text_to_split, ',', '</x><x>') + '</x></content>' AS XML) as content) xml_data
CROSS APPLY xml_data.content.nodes('/content/x') as document(node)
The output is:
1
10
4
6
CAST('<content><x>' + REPLACE(@text_to_split, ',', '</x><x>') + '</x></content>' AS XML) as content
Then we do a CROSS APPLY
to be able to work with it as a table estructured XML data
CROSS APPLY xml_data.content.nodes('/content/x') as document(node)
And finally we extract the content of the XML nodes and cast it as integers
SELECT document.node.value('.', 'int') as id