2

I have the table: TestXml with 2 columns(pk , xCol). This is my table:

    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>'
)

the xml value , that I was insert looks like this:

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

How can I take "<section>" element where "<doc id = "123">" ?

John Saunders
  • 160,644
  • 26
  • 247
  • 397
Oleg
  • 1,467
  • 4
  • 26
  • 39

1 Answers1

3

Try this:

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
mwigdahl
  • 16,268
  • 7
  • 50
  • 64
  • Thank you @mwigdahl for your example. This reasoning clears out my issue on how to dinamically read xml data types on SQL Server. – G21 Mar 13 '12 at 15:20