Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Select multiple rows from xml database column using xpath (possible without cursor?)

Tags:

tsql

xpath

Say I have the following table (where History is an xml column):

Id      Value     History
1       "Hello"   <History>
                    <Node date="1-1-2011">World</Node>
                    <Node date="1-2-2011">Foo</Node>
                    <Node date="1-3-2011">Bar</Node>
                  </History>
2       "Baz"     <History>
                    <Node date="1-1-2011">Buzz</Node>
                    <Node date="1-2-2011">Fizz</Node>
                    <Node date="1-3-2011">Beam</Node>
                  </History>

And from that I wanted to select a new table like:

HistoryId   Id      Value       Date
1           1       "World"     1-1-2011
2           1       "Foo"       1-2-2011
3           1       "Bar"       1-3-2011
4           2       "Buzz"      1-1-2011
5           2       "Fizz"      1-2-2011
6           2       "Beam"      1-3-2011

How would I do that?

If it were just a standalone xml value I could do something like this:

DECLARE @xml2 XML = '
<History>
  <Node date="1-1-2011">World</Node>
  <Node date="1-2-2011">Foo</Node>
  <Node date="1-3-2011">Bar</Node>
</History>'

SELECT 
    x.value('(@date)[1]','date') AS [Date]
    ,x.value('.', 'nvarchar(50)') AS Value
FROM @xml2.nodes('/History/Node') temp(x) 

But I'm not sure how to do it when the XML data is part of a table column. I could probably figure out a way to do it imperatively with a cursor but I was wondering if there's a more elegant declarative solution that I'm not aware of.

like image 207
Davy8 Avatar asked Feb 01 '11 18:02

Davy8


1 Answers

Use a cross apply

declare @T table (Id int, Value nvarchar(50), History xml)
insert into @T values (1, 'Hello','
<History>
  <Node date="1-1-2011">World</Node>
  <Node date="1-2-2011">Foo</Node>
  <Node date="1-3-2011">Bar</Node>
</History>')
insert into @T values (2, 'Baz','
<History>
  <Node date="1-1-2011">Buzz</Node>
  <Node date="1-2-2011">Fizz</Node>
  <Node date="1-3-2011">Beam</Node>
</History>')

select
    Id,
    h.n.value('.', 'varchar(10)') as Value,
    h.n.value('@date', 'varchar(10)') as Date
from @T
    cross apply history.nodes('History/Node') h(n)
like image 187
Mikael Eriksson Avatar answered Oct 24 '22 18:10

Mikael Eriksson