0

I'm trying to select nodes in XML document by provided name.

declare @xdoc xml = '

    <data>
        <box><id>1</id><weight>10</weight></box>
        <tube><id>2</id><weight>20</weight></tube> <!-- Should be skipped -->
        <box><id>3</id><weight>30</weight></box>
    </data>

'

declare @node nvarchar(100)='box'

select
    ref.value('id[1]','bigint') as Id,
    ref.value('weight[1]','bigint') as Weight
from @xdoc.nodes('/data/*[local-name()=[sql:variable("@node")]]') as xdata(ref)
-- WORKS FINE:from @xdoc.nodes('/data/*[local-name()="box"]') as xdata(ref)

and it gives me error message:

XQuery [nodes()]: Syntax error near '[', expected a step expression.

How do I access local variable in xml.nodes()? Or may be there is some better way to achieve it?

1 Answer 1

1

Your XPath expression misses a * around /data/ and has some superfluous [] around sql:variable("@node"):
it should be

select
  ref.value('id[1]','bigint') as Id,
  ref.value('weight[1]','bigint') as Weight
from @xdoc.nodes('/data/*[local-name()=sql:variable("@node")]') as xdata(ref)

EDIT: added correction mentioned in comment by author.

Sign up to request clarification or add additional context in comments.

2 Comments

Ah, copypaste is not my friend :) Correct full query looks like /data/*[local-name()=sql:variable("@node")]
@dmay: Yes, You're expression makes more sense. I hope you don't mind if I put it in the answer for future reference.

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.