2

I have the following xml in my xml-typed column (xml itself is un-typed)

<wi>
  <w wid="16">
    <p>28</p>
    <p>72</p>
    <p>125</p>
  </w>
  <w wid="19">
    <p>89</p>
  </w>
  <w wid="20">
    <p>11</p>
  </w>
  <w wid="21">
    <p>74</p>
  </w>
</wi>

Can't figure out how to produce two-columns using SQL+XQuery:

 p    w
---  ---
11   20
28   16
72   16
74   21
89   19
125  16

2 Answers 2

2

Use:

declare @x xml = '<wi>
  <w wid="16">
    <p>28</p>
    <p>72</p>
    <p>125</p>
  </w>
  <w wid="19">
    <p>89</p>
  </w>
  <w wid="20">
    <p>11</p>
  </w>
  <w wid="21">
    <p>74</p>
  </w>
</wi>'

select *
from
(
    select t.c.value('.', 'int') p
        , t.c.value('../@wid', 'int') w
    from @x.nodes('//p') t(c)
)t
order by p, w
Sign up to request clarification or add additional context in comments.

2 Comments

Assuming I added namespace to the root node: <wi xmlns="example.com">, how do I specify it in the value() call? no syntax I try works.
I guess a better question would be - assuming I have a schema, how do I specify that schema in the value() call? I already added "with xmlnamespaces(default 'example.com')" to the sql query
2

Or another approach using cross apply:

select *
from
(
    select a.b.value('.', 'int') p
        , t.c.value('@wid', 'int') w
    from @x.nodes('//w') t(c)
    cross apply t.c.nodes('p') a(b)
)t
order by p, w 

1 Comment

You will have better performance not using the parent axis ... +1 for this version.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.