0

I need some more help with another XML query. Below is an example of a record of my XML column:

<Fields>
  <MappedFields>
    <Field name="FormNumber" value="21" />
    <Field name="ProcedureCode" value="T2023" />
    <Field name="CurrentDate" value="4/23/2012" />
  </MappedFields>
</Fields>

The field elements may appear in any order, so it can appear like this as well:

<Fields>
  <MappedFields>
    <Field name="ProcedureCode" value="G5532" />
    <Field name="FormNumber" value="12" />
    <Field name="CurrentDate" value="3/29/2011" />
  </MappedFields>
</Fields>

What I am looking for, is a query that will get the value of the Field with the name "FormNumber" for all the records in the table. The query I have below works if the Field with the name of "FormNumber" is the first Field element in the XML. What I need is a query that will find the Field element even if it is not the first element. Can someone help me out with this?

SELECT
     X.Node.value(N'(Field/@value)[1]', 'nvarchar(max)') AS FormNumber
FROM 
    dbo.MHTCM_LetterSent A
CROSS APPLY A.LetterXML.nodes(N'/Fields/MappedFields') AS X(Node)
WHERE
    X.Node.value(N'(Field/@name)[1]', 'nvarchar(max)') = 'FormNumber'
4

1 回答 1

2

You can have a test in the xml path like [@name="FormNumber"].

SELECT
     X.Node.value(N'(Field[@name="FormNumber"]/@value)[1]', 'nvarchar(max)') AS FormNumber
FROM 
    dbo.MHTCM_LetterSent A
CROSS APPLY A.LetterXML.nodes(N'//Fields/MappedFields') AS X(Node)

Note the WHERE isn't needed now.

It might make more sense to move the test to the CROSS APPLY:

SELECT
     X.Node.value(N'(./@value)[1]', 'nvarchar(max)') AS FormNumber
FROM 
    dbo.MHTCM_LetterSent A
CROSS APPLY A.LetterXML.nodes(N'//Fields/MappedFields/Field[@name="FormNumber"]') AS X(Node)

Edit- I made the paths absolute (//) and both examples are working for me.

于 2012-04-30T18:54:23.187 回答