Flattening XML in SQLXML
I have this XML in T-SQL:
<Elements>
<Element>
<Index>1</Index>
<T开发者_Python百科ype>A</Type>
<Code>AB</Code>
<Time>1900-01-01T10:21:00</Time>
</Element>
<Element>
<Index>2</Index>
<Type>M</Type>
<Code>AL</Code>
<Time>1900-01-01T10:22:00</Time>
</Element>
</Elements>
And I want to retrieve it as a table:
Index FieldName FieldValue
-------- ------------ ----------
1 Index 1
1 Type A
1 Code AB
1 Time 1900-01-01T10:21:00
2 Index 2
2 Type M
2 Code AL
2 Time 1900-01-01T10:22:00
Of course, what I'm looking for here is to pivot the Element nodes into rows, but I can't get more than just the field value OR the index at a time...
select
-- r.value('.[1]', 'nvarchar(10)') Value,
-- r.value('fn:local-name(.)', 'nvarchar(50)') FieldName
r.value('Index[1]', 'nvarchar(10)') f,
r.value('./node()[fn:local-name(.)]', 'nvarchar(10)') v
from
@content.nodes('/Elements/*') as records(r)
You could try something like this:
SELECT
El.Elem.value('(Index)[1]', 'int'),
SubEl.SubElem.value('local-name(.)', 'varchar(100)') AS 'Field Name',
SubEl.SubElem.value('.', 'varchar(100)') AS 'Field Value'
FROM
@content.nodes('/Elements/Element') AS El(elem)
CROSS APPLY
El.Elem.nodes('*') AS SubEl(SubElem)
That seems to produce your desired output in my test case.
You basically need to select all /Elements/Element
nodes in a first step, get their index value, and then in a second step, select all child nodes (/*
)for any given <Element>
node.
精彩评论