XML smoothing in SQLXML

I have this XML in T-SQL:

<Elements>
    <Element>
        <Index>1</Index>
        <Type>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 get it in the form of 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 rotate the Element nodes into rows, but I cannot get more than just a field value or 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)
+3
source share
1 answer

You can 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)

In my test case, the desired result is created.

Basically, you need to select all the nodes /Elements/Elementin the first step, get their index value, and then in the second step select all the child nodes ( /*) for any given <Element>node.

+3
source

Source: https://habr.com/ru/post/1753278/


All Articles