1

我正在尝试检索在 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。当我运行下面的脚本时,我得到空值。

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'

4

1 回答 1

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>
于 2013-11-06T06:23:32.387 回答