3

In a table, I have multiple rows, each containing xml based on common schema. An example of the XML might be:

<Items>
    <Item>Item 1</Item>
    <Item>Item 2</Item>
</Items>

If I have multiple rows in a table, all containing similar xml, is it possible to write a query that returns all values in the Item node for all rows, in a single resultset? We're using SQL Server 2008 R2

1
  • Is the column defined as XML datatype? Commented Sep 12, 2012 at 0:01

1 Answer 1

6

If your xml is defined in an XML column ..

DECLARE @Items AS TABLE 
(
    ItemXml XML
)

-- test data with a couple rows of xml
INSERT INTO @Items(ItemXml)
VALUES ('<Items><Item>Item 1</Item><Item>Item 2</Item></Items>')
      ,('<Items><Item>Item 3</Item><Item>Item 4</Item></Items>')

-- the query
SELECT t.i.value('.','VARCHAR(8000)') AS Item
FROM @Items CROSS APPLY ItemXml.nodes('/Items/Item') t(i)

Will give you

Item
------
Item 1
Item 2
Item 3
Item 4

The key here is nodes() which

is useful when you want to shred an xml data type instance into relational data. It allows you to identify nodes that will be mapped into a new row.

Sign up to request clarification or add additional context in comments.

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.