October 26, 2011

Convert comma separated value into individual row

I have a string “1,2,3,4,5” and i want to convert it into individual row like as below.

image

Is it possible? yes we can do it.We need to convert this string into XML form then after
we are able to do it.

T-SQL

DECLARE @XML XML
DECLARE @Str NVARCHAR(1000)
SET @Str = N'1,2,3,4,5'
SET @XML = N'<root><r>' + REPLACE(@Str,',','</r><r>') + '</r></root>'
SELECT T.value('.','VARCHAR(10)') AS [Row] FROM @XML.nodes('//root/r') AS X(T)
It is very handy technique and we can use it in a real problem.

That’s It.
Enjoy Learning.

No comments:

Post a Comment