将逗号分隔的字符串拆分为列
问题描述:
我有一个这样的字符串:
I have a string like this:
'1,A;2,B;3,C'
无论如何我可以将逗号分隔的值拆分为列,然后通过 ;
拆分为行,如下所示:
Is there anyway that I can split comma separated values into columns then split to rows by ;
like below:
ID Text
1 A
2 B
3 C
答
试试这个:
declare @s varchar(50) = '1,A;2,B;3,C'
--convert string to xml table (I used HTML tags for clarity)
declare @xml xml = cast('<tr><td>' + replace(replace(@s, ';', '</td></tr><tr><td>'), ',', '</td><td>') + '</td></tr>' as xml)
--query the xml to get SQL table
select tbl.col.value('td[1]', 'int') [ID],
tbl.col.value('td[2]', 'varchar(10)') [Text]
from @xml.nodes('/tr') tbl(col)