如何通过T-SQL从xml中选择数据?

时间:2011-12-29 18:45:26

标签: xml tsql

我有表:TestXml有2列(pk,xCol)。 这是我的表:

    create table TestXml (
pk int primary key, xCol xml)
on [Primary]
insert into Store.dbo.TestXml(pk,xCol) values (1,'<docs><doc id="12"><section> Section 1</section></doc>
<doc id="123"><section> Section 1</section>
<section> Section 2</section>
</doc>
</docs>'
)

我插入的xml值如下所示:

   <docs>
  <doc id="12">
    <section> Section 1</section>
  </doc>
  <doc id="123">
    <section> Section 1</section>
    <section> Section 2</section>
  </doc>
</docs>

如何将“<section>”元素置于“<doc id = "123">”?

1 个答案:

答案 0 :(得分:3)

试试这个:

SELECT c.d.value('(.)[1]', 'varchar (100)') AS Section
FROM Store.dbo.TestXml tx
    CROSS APPLY tx.xCol.nodes('./docs/doc') AS a(b)
    CROSS APPLY a.b.nodes('./section') AS c(d)
WHERE a.b.value('(@id)[1]', 'int') = 123