1

I'm trying to convert a string to rows using T-SQL. I've found some people using XML for this but I'm running into troubles.

The original record:

A new line seperated string of data

New  In Progress  Left Message  On Hold  Researching  Researching (2nd Level)  Researching (3rd Level)  Resolved  Positive  False Positive  Security Respond

Using the following statement converts this string into XML:

select 
    cast('<i>'+REPLACE(convert(varchar(max), list_items), CHAR(13) + CHAR(10),'</i><i>')+'</i>' as xml)
from 
    field
where 
    column_name = 'state' and table_name = 'sv_inquiry'

XML string:

<i>Unassigned</i><i>Assigned</i><i>Transferred</i><i>Accepted</i><i>Closed</i><i>Reactivated</i>

Now I would like to convert every 'i' node into a separate row. I've constructed the query below, but I can't get it working in the way that it returns all the rows...

select x.i.value('i[1]', 'varchar(30)')
from (
    select cast('<i>'+REPLACE(convert(varchar(max), list_items), CHAR(13) + CHAR(10),'</i><i>')+'</i>' as xml)
    from field
    where column_name='state' and table_name='sv_inquiry'
) x(i)

This will return

Unassigned

To be clear, when i change 'i[1]' into 'i[2]' it will return 'Assigned'. I've tried '.', this will return the whole string in a single record...

2 Answers 2

1

How about using the nodes method on an XML datatype.

declare @xml xml

set @xml = '<i>Unassigned</i><i>Assigned</i><i>Transferred</i><i>Accepted</i><i>Closed</i><i>Reactivated</i>'

select
    t.c.value('.', 'nvarchar(100)') as [Word]
from 
    @xml.nodes('/i') as t(c)
Sign up to request clarification or add additional context in comments.

2 Comments

Is it possible to put this in one statement. I tried calling the .nodes('/i') after the from, like this from (select ...).nodes('/i') x(i)
@Bas: You can use cross apply for that, example in my answer. +1 for the nodes() function which is the central machinery for turning XML into rows.
0

You can split a string into rows without XML, see for example the fnSplitString function at SQL Server Central.

Here's an example using the nodes() function of the xml type. I'm using a space as the delimiter because SQL Fiddle doesn't play well with line feeds:

select  node_column.value('.', 'varchar(max)')
from    (
        select  cast('<i>' + replace(list_items, ' ', '</i><i>') +
                    '</i>' as xml) xml_value
        from    field
        ) f
cross apply
        xml_value.nodes('/i') node_table(node_column);

Live example at SQL Fiddle.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.