string into single column [duplicate]

蓝咒 提交于 2020-01-15 12:13:02

问题


I have the comma separated string as shown below to convert into a column.

Example:

Given String:

DECLARE @STR VARCHAR(MAX) = 'ABC,DEF,GHI,JKL,MNO'

Have to convert into a single column:

columnName
-----------
ABC
DEF
GHI
JKL
MNO

回答1:


Try this. Used LTRIM and RTRIM function to remove Leading and Trailing spaces.

DECLARE @STR VARCHAR(MAX) = 'ABC,DEF,GHI,JKL,MNO'

SELECT Rtrim(Ltrim(Split.a.value('.', 'VARCHAR(100)'))) Split_Data
FROM   (SELECT Cast ('<M>' + Replace(@STR, ',', '</M><M>') + '</M>' AS XML) AS Data) AS A
       CROSS APPLY Data.nodes ('/M') AS Split(a) 

OUTPUT :

Split_Data
----------
ABC
DEF
GHI
JKL
MNO


来源:https://stackoverflow.com/questions/27255512/string-into-single-column

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