0

I have an XML column in SQL Server populated with:

<concession>
  <schema>
    <data schemaItem="title">Re-label to all boards</data>
    <data schemaItem="problem">These boards have been tested</data>
    <data schemaItem="solution">Ask to print new label and add the word "B" on the old serial numbers. so all serial numbers will be modified to new on B .......</data>
    <data schemaItem="justification">Will help UK test resource</data>
    <data schemaItem="liability">Us</data>
    <data schemaItem="parts">
      <part>075</part>
      <part>076</part>
    </data>
    <data schemaItem="products">
      <product>Pdq </product>
    </data>
    <data schemaItem="faultCode">ILB</data>
    <data schemaItem="processCode">MAT</data>
    <data schemaItem="quantity">273</data>
    <data schemaItem="requestedExpiry">14/12/2011</data>
  </schema>
</concession>

How do I extract the quantity value, ie: 273?

I've tried but no joy:

SELECT 
    [guid],XMLData, 
    (select xmlData.value('(/concession/schema/data)[1]', 'varchar(100)' )), 
    (select xmlData.value('(/concession/schema/data[schemaItem="quantity"])[0]', 'varchar(100)' ))   
FROM 
    tc_Concession

I get the title ok but not the quantity.

2 Answers 2

1

Try using the Outer Apply With the nodes() method,

SELECT
      m.c.value('@schemaItem', 'varchar(max)') as SchemaItem,
      m.c.value('(text())[1]', 'nvarchar(max)') as Value
FROM Yourtablename
    OUTER APPLY xml_data.nodes('concession/schema/data') as m(c)

This will give you the output as,

SchemaItem         Value
title            Re-label to all boards
problem          These boards have been tested
solution         Ask to print new label and add the word "B" on the old serial numbers. so all serial numbers will be modified to new on B .......
justification    Will help UK test resource
liability        Us
parts            NULL
products         NULL
faultCode        ILB
processCode      MAT
quantity         273
requestedExpiry  14/12/2011
Sign up to request clarification or add additional context in comments.

Comments

1

You are very close. The attribute name needs to be preceeded by @, and the index should be 1-based. You don't need the sub-select - the .value() method can be used on it's own.

SELECT 
    [guid],
    XMLData, 
    xmlData.value('(/concession/schema/data)[1]', 'varchar(100)' ),
    xmlData.value('(/concession/schema/data[@schemaItem="quantity"])[1]', 'varchar(100)' )
FROM 
    tc_Concession

If the XML isn't guaranteed to be ordered then you should use the 2nd approach for the title too.

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.