按节点属性查询XML节点值

时间:2013-11-06 00:33:09

标签: sql sql-server xml xpath sqlxml

我正在尝试检索在sql server列中存储为xml数据类型的xml节点的值。例如,我的xml列数据是:

<fields>
<field id="StudentName">John Smith</field>
<field id="StudentID">1310021003</field>
<field id="SchoolName">Little Kid Elementary School</field>
</fields>

我想检索StudentID。当我运行下面的脚本时,我得到null。

select MyColumnName.value('(/fields/field/@StudentID)[1]', 'varchar(20)') as StudentId from MyTable

[红利问题] - 如果可能,我还想通过studentid查询表格,例如:select * from MyTable where MyColumnName.value('(/fields/field/@StudentID)[1]', 'varchar(20)') = '1310021003'

1 个答案:

答案 0 :(得分:2)

首先,这将是测试环境:

declare @MyTable table (MyColumnName xml)

insert into @MyTable 
select '<fields>
<field id="StudentName">John Smith</field>
<field id="StudentID">1310021003</field>
<field id="SchoolName">Little Kid Elementary School</field>
</fields>' union all

select '<fields>
<field id="StudentName">John Smith</field>
<field id="StudentID">2343343434</field>
<field id="SchoolName">Little Kid Elementary School</field>
</fields>'

要从xml获取数据,请使用value()函数:

select
    MyColumnName.value('(fields/field[@id="StudentID"]/text())[1]', 'nvarchar(max)') as StudentID
from @MyTable

输出:

StudentID
-----------
1310021003
2343343434

要按xml数据过滤,请使用exist()函数

select
    *
from @MyTable
where MyColumnName.exist('fields/field[@id="StudentID" and text()=1310021003]') = 1

输出:

MyColumnName
-----------
<fields>
    <field id="StudentName">John Smith</field>
    <field id="StudentID">1310021003</field>
    <field id="SchoolName">Little Kid Elementary School</field>
</fields>