1

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
  • Many dups about splitting a string; Tsql split string Commented Dec 2, 2014 at 17:35

1 Answer 1

2

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
Sign up to request clarification or add additional context in comments.

1 Comment

Great! Thank you so much. Will accept this within 5 min.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.