XPATH获取在兄弟中保存ID的列表项

时间:2014-10-17 10:27:53

标签: sql-server xml xpath

在T-SQL中使用XPath我试图从选项列表中获取属性值,其中可以在Value元素中找到用于选择正确列表项的Id。

任何帮助都将不胜感激。

declare  @myTable table (pk int primary key identity(1,1), myXML xml)

insert into @myTable values ('
<Fields>
      <Field  ID="1111">
        <Description>How Now Brown Cow</Description>
        <Value>3</Value>
        <Options>
          <Options>
            <Option OptionContent="Select one"  OptionID="-1" />
            <Option OptionContent="Mars"        OptionID="1" />
            <Option OptionContent="Pluto"       OptionID="2" />
            <Option OptionContent="Saturn"      OptionID="3"  />
          </Options>
        </Options>
      </Field>
        <Field  ID="2222">
        <Description>Foo Bar</Description>
        <Value>2</Value>
        <Options>
          <Options>
            <Option OptionContent="Select one"  OptionID="-1"  />
            <Option OptionContent="Coffee"      OptionID="1"  />
            <Option OptionContent="Tea"         OptionID="2"  />
            <Option OptionContent="Water"       OptionID="3" />
            <Option OptionContent="Juice"       OptionID="4" />
            <Option OptionContent="Water"       OptionID="5" />
          </Options>
        </Options>
      </Field>
</Fields>      
')

select
    myField.ref.value('@ID', 'smallint')                                as [ID]
    ,myField.ref.value('(./Description)[1]', 'nvarchar(10)')            as [Description]
    ,myField.ref.value('(./Value)[1]', 'int')                           as [Value]
    ,myField.ref.value('(./Options/Options/Option[@OptionID="-1"]/@OptionContent)[1]', 'nvarchar(10)')      as [SelectedDescription]
from @myTable c
cross apply c.myXML.nodes('/Fields/Field') myField(ref)

ID     Description Value       Actual     Expected
------ ----------- ----------- ---------- --------
1111   How Now Br  3           NULL       Saturn
2222   Foo Bar     2           NULL       Tea

1 个答案:

答案 0 :(得分:2)

更改

(./Options/Options/Option[@OptionID="-1"]/@OptionContent)[1]

let $id := ./Value[1] return (./Options/Options/Option[@OptionID=$id]/@OptionContent)[1]

所以你的查询应该是

select
    myField.ref.value('@ID', 'smallint')                                as [ID]
    ,myField.ref.value('(./Description)[1]', 'nvarchar(10)')            as [Description]
    ,myField.ref.value('(./Value)[1]', 'int')                           as [Value]
    ,myField.ref.value('let $id := ./Value[1] return (./Options/Options/Option[@OptionID=$id]/@OptionContent)[1]', 'nvarchar(10)')      as [SelectedDescription]
from @myTable c
cross apply c.myXML.nodes('/Fields/Field') myField(ref)