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.
Use a cross apply