split comma separated string into columns

北城以北 提交于 2019-12-14 03:09:40

问题


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

回答1:


Try this:

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)

For more information: Convert Xml to Table SQL Server




回答2:


DECLARE @tags NVARCHAR(400) = '1,A;2,B;3,C'  

SELECT SUBSTRING(value, 1, CHARINDEX(',',value)-1) AS ID
, SUBSTRING(value, CHARINDEX(',',value)+1, LEN(value)) AS TEXT 
FROM(
SELECT value  
FROM STRING_SPLIT(@tags, ',')  
WHERE RTRIM(value) <> ''
) A


来源:https://stackoverflow.com/questions/50383351/split-comma-separated-string-into-columns

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!